Introduction: Zeen

Hello, my name is zeen and today we will be presenting big idea 3. Our topics include 2d arrays, iteration, and lists and dictionaries.

Objectives

Master the concepts of iteration, list, 2d-arrays, Dictionaries, and APIs

Vocab

Here is some vocab during the lesson, you should be familar with them already no need for me to read these out, now I will pass the speaking off to Kush

  • Iteration: A process that repates itself
  • Array: Sometimes called a list, can keep strings and intergers inside it
  • 2D-Array: A collection of data elements arranged in a grid-like structure with rows and columns
  • Mutable: the ability to be changed or modified
  • Key: A Singular identifier that is associated with a certin value

1: 2D Array

Tic Tac Toe:Kush Sirohi

- What are some examples of 2d Arrays

- What is a modern day game that could be classified as a 2D array

array = ["Hello", "Hi", "Whats up"]
twoDArray = [["Name", "ID", "Age"], ["Kush", "1", "16"], ["Finn", "2", "16"]]

print(f"This is a normal array: {array}")

print("This is a 2D array")
for row in twoDArray:
    print(row)
This is a normal array: ['Hello', 'Hi', 'Whats up']
This is a 2D array
['Name', 'ID', 'Age']
['Kush', '1', '16']
['Finn', '2', '16']

How I used 2D Arrays (game example)

  • Describe a 2D array in your own words
    • A 2d array is basically a list within a list
board = [[' ', ' ', ' '],
         [' ', ' ', ' '],
         [' ', ' ', ' ']]
         
# Function to print the current state of the game board
def print_board():
    print("   0   1   2")
    for i in range(3):
        print(i, end='  ')
        for j in range(3):
            print(board[i][j], end=' ')
        print()

# Function to check if a player has won the game
def check_win(player):
    # Check rows for a win
    for i in range(3):
        if board[i][0] == player and board[i][1] == player and board[i][2] == player:
            return True
    # Check columns for a win
    for j in range(3):
        if board[0][j] == player and board[1][j] == player and board[2][j] == player:
            return True
    # Check diagonals for a win
    if board[0][0] == player and board[1][1] == player and board[2][2] == player:
        return True
    if board[0][2] == player and board[1][1] == player and board[2][0] == player:
        return True
    # If no win condition is met, return False
    return False

# Function to check if the game is a tie
def check_tie():
    for i in range(3):
        for j in range(3):
            if board[i][j] == ' ':
                return False
    return True

# Function to play the game
def play_game():
    # Initialize player and turn counter
    player = 'X'
    turns = 0
    # Loop until the game is over
    while True:
        # Print the current state of the board
        print_board()
        # Get the player’s move
        row = int(input(f"{player}'s turn. Enter row (0-2): "))
        col = int(input(f"{player}'s turn. Enter column (0-2): "))
        # Check if the move is valid
        if board[row][col] == ' ':
            board[row][col] = player
            turns += 1
            # Check if the player has won
            if check_win(player):
                print_board()
                print(f"{player} wins!")
                return
            # Check if the game is a tie
            if check_tie():
                print_board()
                print("It's a tie!")
                return
            # Switch players
            player = 'O' if player == 'X' else 'X'
        else:
            print("That space is already taken. Try again.")

# Start the game
play_game()
   0   1   2
0        
1        
2        
   0   1   2
0        
1    X   
2        
   0   1   2
0        
1    X O 
2        
   0   1   2
0        
1    X O 
2  X     
   0   1   2
0        
1  O X O 
2  X     
   0   1   2
0      X 
1  O X O 
2  X     
X wins!

2: Iteration

> Robot Game:Finn Carpenter- What is the defenition of iteration in your own words

times = 0
numbers = [1, 2, 3, 4, 5]

## Loops
for i in range(5):
    print("hi")


while times <= 5:
    print("hello")
    times = times + 1

## Function with a parameters
def print_numbers(x):
    for num in x:
        print(num)

print_numbers(numbers)
hi
hi
hi
hi
hi
hello
hello
hello
hello
hello
hello
1
2
3
4
5

Iteration Game

  • Link to the game
  • Play the levels (only play the first 2 in class)
  • Explain how the game relates to itertation

How I used iteration (game example)

  • What parts of the code use iteration
    • The for loops that push the movement controls to the array`
function run() {
    // Read input values from the HTML document and convert them to integers.
    UPinput = parseInt(document.getElementById("up").value);
    DOWNinput = parseInt(document.getElementById("down").value);
    LEFTinput = parseInt(document.getElementById("left").value);
    RIGHTinput = parseInt(document.getElementById("right").value);
    looper = parseInt(document.getElementById("loop").value);

    runner.style.opacity = 0;
    

    // Create an array to hold the movements.
    let movements = [];

    // Push 'up' movements to the array.
    for (let l = 0; l < looper; l++) {
        for (let k = 0; k < UPinput; k++) {
            movements.push(up);
        }

        // Push 'down' movements to the array.
        for (let i = 0; i < DOWNinput; i++) {
            movements.push(down);
        }

        // Push 'left' movements to the array.
        for (let a = 0; a < LEFTinput; a++) {
            movements.push(left);
        }

        // Push 'right' movements to the array.
        for (let c = 0; c < RIGHTinput; c++) {
            movements.push(right);
        }
    }


    // Set the initial index to 0 and execute each movement in sequence with a delay of 800 milliseconds.
    let index = 0;
    let intervalId = setInterval(() => {
        // If the end of the movements array has been reached, stop executing movements.
        if (index >= movements.length) {
            clearInterval(intervalId);
            win(); // Call the win function.
            return;
        }
        movements[index](); // Execute the movement at the current index.
        index++; // Increment the index.
    }, 800);
}

3: List and Dictionaries

Scramble Game:Edwin

List = [1, 2, 3, 4, 5]
Dict = {
    1: "Hi",
    2: "Hello",
    3: "Whats Up"
}

# Why Do I call 0 for the first thing in a list, but 1 for Dict
# The index of a list starts at 0

print(List[0])
print(Dict[1])
1
Hi

How I used a dictonary to make a game

Memory Game:James- Link

  • Code

How I used List to make a game

- Explain which parts of the code use lists

- Explain what list manipulation is happening in that part

import random

word_list = ["python", "computer", "programming", "algorithm", "database", "function", "variable", "loop", "iteration", "array", "mutable", "insertion", "deletion", "key", "API"]

word = random.choice(word_list)

scrambled_word = "".join(random.sample(word, len(word)))

print(f"Unscramble the following Computer Science Word: {scrambled_word}")

hints = 1
guesses = 1
guess = ""

while guess != word and guesses <= 4:
    guess = input("What's the unscrambled word? ").lower()
    if guess != word:
        print("Sorry, that's not the word. Try again!")
        if guesses == 1:
            guesses += 1
        elif guesses == 2:
            print(f"Hint 1: The first letter of the word is '{word[0]}'")
            guesses += 1
        elif guesses == 3:
            print(f"Hint 2: The second letter of the word is '{word[1]}'")
            guesses += 1
        else:
            print(f"All 4 Guesses have been used, you didn't unscramble the word, the word was {word}")
            guesses += 1
    else:
        print("Congratulations, you unscrambled the word!")
Unscramble the following Computer Science Word: teldeion
Congratulations, you unscrambled the word!

Hacks

Self grade:0.93/1.0

General 0.3

  • [x] Copy this noteboook into your personal fastpages
  • [x] Answer all questions
    1. What are some examples of 2D arrays?
      • Spreadsheets, images, chessboard, etc. They all consist of rows and columns.
    2. What is a modern day game that could be classified as a 2D array?
      • Sudoku is a 2D array game. The game is played on a 9x9 grid of squares, which is rows and columns, so it can be conisdered a 2D array.
    3. Describe a 2D array in your own words
      • A 2D array is a data collection type where data is indexed by two indices. It is visually comprised of 2 dimensions (hence 2D), which are rows and columns, so it is structured like a table. It can also be visualized as a collection of arrays, with each array representing a row of data (basically lists within a list).
    4. What is the definition of iteration in your own words
      • Iteration is the process of repeating an operation or block of code multiple times. This usually takes place in a loop, until a condition is met, then it stops.
    5. Explain how the game relates to iteration
      • Iteration is used to create an array of movements and execute them in a sequence. It allows the code to repeat the certain instruction a certain amount of times. Without it, the code would manually execute each movement, which is not efficient.
    6. What parts of the code use iteration
      • There are several for loops in the code. The one that iterates over the looper variable determines how many times the set of movements should be excuted. The four for loops within that add movement to the array.
    7. Explain which parts of the code use lists
      • At the beginning of the code, a list of string words are assigned to the variable word_list. The random module selects one of these items from the list to scramble for the game
    8. Explain what list manipulation is happening in that part
      • There is list manipulation happening through the random.sample() function. The function returns a list of the string scrambled. The items of the list is being manipulated, by having the letters be mixed up.

Iteration 0.2 (can get up to 0.23)

  • [x] Get to level 5
  • [x] Create a code segment with iteration that does something cool
import random

def play_game():
    answer = random.randint(1, 10) # generate random number between 1 and 10
    guess_count = 0 #count number of guesses
    
    while guess_count < 3: # user only gets 3 guesses
        guess = int(input("Guess a number between 1 and 10: ")) # get user input
        guess_count += 1 # add to the guess count
        
        if guess == answer: # check if guess is correct
            print("You guessed the number! You win.")
            return # end game
        elif guess < answer:
            print(guess, "is too low.")
        else:
            print(guess, "is too high.")
    
    # user loses if they reach 3 guesses, and does not guess correctly
    print("You didn't guess the number. Game over.")

play_game() # start the game
5 is too high.
3 is too low.
You guessed the number! You win.

2D array 0.2 (can get up to 0.23)

  • [x] Explain how the tic tac toe game works
    • The tic tac toe game uses a 2d array to represent a 3x3 board. It initially starts off empty, and is printed to the user. The user is instructed to enter the value of the row and column of where they want to position their X or O symbol. If the move is valid (position not already taken), then the board is updated with the symbol in place. Then, the check_win() function checks whether there are any instances of 3 X's or 3 O's in a row, vertically, horizontally, or diagonally. If there are, then the game ends and the winner is declared. A tie can also be checked, when all the spaces are filled up and there are no wins. The game continues in a loop, where each player inputs the position of their respective symbol, until a player wins or there is a tie.
  • [x] Give 3 Examples of games that can be made from 2D arrays
    1. Snake: The game board is made up of a grid of cells, and the values in the array represent the snake and the apple
      • Here is me and my groupmate's own snake game with a 2d grid: Snake
    2. Sudoku: The puzzle is made up of a 9x9 grid, and the values in the arrays contain the value of a cell in the grid
    3. Tetris: The game is made up of a grid of cells, and each cell can either be empty or occupied by a piece

List and Dictionaries 0.2 (can get up to 0.23)

  • [x] Explain the differences between Lists and Dictionaries
    • They are both data collection structures in Python. However, here are some of their differences: | | Dictionary | List | | --- | --- | --- | | Syntax | Curly brackets | Square brackets | | Indexing | Keys, which may be represented by any data type | Integer indexes | | Order | Unordered collection of key-value pairs | Ordered collection, order of elements is preserved | | Duplication | Cannot contain duplicates | Can contain duplicates | | Pros | - Easy search/lookup
      - Flexible key types | - Ordered
      - Allows duplicates
      - Easy iteration | | Cons | - Unordered
      - Keys must be unique | - Slow lookup
      - Fixed index |
  • [x] Make a code block that manipulates either a list or a dictionary
album = {
    'title': 'Humbug',
    'artist': 'Arctic Monkeys',
    'year': 2009,
    'songs': [
        {'title': 'My Propeller', 'duration': 214},
        {'title': 'Crying Lightning', 'duration': 204},
        {'title': 'Dangerous Animals', 'duration': 220},
        {'title': 'Secret Door', 'duration': 182},
        {'title': 'Potion Approaching', 'duration': 238},
        {'title': 'Fire and the Thud', 'duration': 230},
        {'title': 'Cornerstone', 'duration': 201},
        {'title': 'Dance Little Liar', 'duration': 336},
        {'title': 'Pretty Visitors', 'duration': 234},
        {'title': 'The Jeweller\'s Hands', 'duration': 345},
    ]
}

# Print the album's title and artist
print(f"{album['title']} by {album['artist']}")

# Print the tracks with durations
for i, song in enumerate(album['songs']):
    print(f"{i+1}. {song['title']} ({song['duration']} seconds)")

# Add a new song to the album (manipulation)
new_song = {'title': 'Catapult', 'duration': 215}
album['songs'].append(new_song)

# Print the updated track listing with durations
print("\n Updated track listing:")
for i, song in enumerate(album['songs']):
    print(f"{i+1}. {song['title']} ({song['duration']} seconds)")

# Calculate the total duration of the album
total_duration = sum(song['duration'] for song in album['songs'])
print(f"\n Total duration of the album: {total_duration} seconds")
Humbug by Arctic Monkeys
1. My Propeller (214 seconds)
2. Crying Lightning (204 seconds)
3. Dangerous Animals (220 seconds)
4. Secret Door (182 seconds)
5. Potion Approaching (238 seconds)
6. Fire and the Thud (230 seconds)
7. Cornerstone (201 seconds)
8. Dance Little Liar (336 seconds)
9. Pretty Visitors (234 seconds)
10. The Jeweller's Hands (345 seconds)

 Updated track listing:
1. My Propeller (214 seconds)
2. Crying Lightning (204 seconds)
3. Dangerous Animals (220 seconds)
4. Secret Door (182 seconds)
5. Potion Approaching (238 seconds)
6. Fire and the Thud (230 seconds)
7. Cornerstone (201 seconds)
8. Dance Little Liar (336 seconds)
9. Pretty Visitors (234 seconds)
10. The Jeweller's Hands (345 seconds)
11. Catapult (215 seconds)

 Total duration of the album: 2619 seconds

How my CPT relates to iteration (extra points):

A for loop is used to iterate over the period cycle dates that were calculated. For each cycle, the start and end dates are retrieved from the corresponding list returned by the "calculateDates()" function. Depending on the value of the loop variable i, the output is displayed. Once the loop has been completed, the function will be finished displaying the interface with menstrual cycle dates and any identified notice messages.