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
    • A chessboard can be represented as an 8x8 2D array, where each square on the board is a cell in the array.
    • A spreadsheet is another example of a 2D array, where each cell is identified by its row and column indices, and contains a value or formula.
  • What is a modern day game that could be classified as a 2D array
  • Stardew Valley and ROTMG
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 a type of data structure that is organized as a grid or matrix with rows and columns. It can be thought of as a table with rows and columns, where each cell in the table holds a value. Each cell is uniquely identified by its row and column indices, which are used to access or manipulate the value in that cell.
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        
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/vscode/ahadsblog/_notebooks/2023-04-21-EOYPLAYGROUND.ipynb Cell 6 in <cell line: 72>()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-04-21-EOYPLAYGROUND.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=68'>69</a>             print("That space is already taken. Try again.")
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-04-21-EOYPLAYGROUND.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=70'>71</a> # Start the game
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-04-21-EOYPLAYGROUND.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=71'>72</a> play_game()

/vscode/ahadsblog/_notebooks/2023-04-21-EOYPLAYGROUND.ipynb Cell 6 in play_game()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-04-21-EOYPLAYGROUND.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=47'>48</a> print_board()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-04-21-EOYPLAYGROUND.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=48'>49</a> # Get the player’s move
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-04-21-EOYPLAYGROUND.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=49'>50</a> row = int(input(f"{player}'s turn. Enter row (0-2): "))
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-04-21-EOYPLAYGROUND.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=50'>51</a> col = int(input(f"{player}'s turn. Enter column (0-2): "))
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-04-21-EOYPLAYGROUND.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=51'>52</a> # Check if the move is valid

ValueError: invalid literal for int() with base 10: ''

2: Iteration

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

  • Iteration refers to the process of repeatedly executing a set of instructions or a block of code until a specific condition is met or a desired result is achieved.
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 movement segments (up down right left) use nested iteration
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);
}
  Input In [10]
    function run() {
             ^
SyntaxError: invalid syntax

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
#

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
  • Word lists is a list
  • Explain what list manipulation is happening in that part
  • The word is being scrambled and the list is edited
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: labeirav
Sorry, that's not the word. Try again!
Sorry, that's not the word. Try again!
Hint 1: The first letter of the word is 'v'
Sorry, that's not the word. Try again!
Hint 2: The second letter of the word is 'a'
Sorry, that's not the word. Try again!
All 4 Guesses have been used, you didn't unscramble the word, the word was variable

Hacks: Your Score/1

General 0.3

  • Copy this noteboook into your personal fastpages
  • Answer all questions
    • put the question in a new markdown block (so we can grade faster)

Iteration 0.2 (can get up to 0.23)

  • Get to level 5
    • Take ScreenShots of your name inside the box an put them in your ticket
    • Create a code segment with iteration that does something cool

2D array 0.2 (can get up to 0.23)

  • Explain how the tic tac toe game works
  • Give 3 Examples of games that can be made from 2D arrays

List and Dictionaries 0.2 (can get up to 0.23)

  • Explain the differences between Lists and Dictionaries
  • Make a code block that manipulates either a list or a dictionary

my hacks

General Hacks

Tic Tac Toe:Kush Sirohi

  • What are some examples of 2d Arrays
    • A chessboard can be represented as an 8x8 2D array, where each square on the board is a cell in the array.
    • A spradsheet is another example of a 2D array, where each cell is identified by its row and column indices, and contains a value or formula.
  • What is a modern day game that could be classified as a 2D array
  • Stardew Valley and ROTMG
  • Describe a 2D array in your own words
  • A 2D array is a type of data structure that is organized as a grid or matrix with rows and columns. It can be thought of as a table with rows and columns, where each cell in the table holds a value. Each cell is uniquely identified by its row and column indices, which are used to access or manipulate the value in that cell.

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

  • Iteration refers to the process of repeatedly executing a set of instructions or a block of code until a specific condition is met or a desired result is achieved.

  • What parts of the code use iteration

  • The movement segments (up down right left) use nested iteration

  • Explain which parts of the code use lists

  • Word lists is a list
  • Explain what list manipulation is happening in that part
  • The word is being scrambled and the list is edited

Iteration Hacks

for i in range(1, 11):
    for j in range(1, 11):
        print(i * j, end="\t")
    print()
# prints times table
1	2	3	4	5	6	7	8	9	10	
2	4	6	8	10	12	14	16	18	20	
3	6	9	12	15	18	21	24	27	30	
4	8	12	16	20	24	28	32	36	40	
5	10	15	20	25	30	35	40	45	50	
6	12	18	24	30	36	42	48	54	60	
7	14	21	28	35	42	49	56	63	70	
8	16	24	32	40	48	56	64	72	80	
9	18	27	36	45	54	63	72	81	90	
10	20	30	40	50	60	70	80	90	100	

2D array Hacks

Tic-Tac-Toe - A classic two-player game that is played on a 3x3 grid of cells. Each player takes turns placing their symbol (either X or O) in an empty cell. The first player to get three of their symbols in a row (either horizontally, vertically, or diagonally) wins the game.

Minesweeper - A single-player game in which the player must clear a rectangular grid of cells that contains hidden mines. Each cell either contains a mine or a number indicating how many mines are adjacent to that cell. The player must use this information to deduce the location of the mines and clear all the safe cells without detonating any mines.

Tic Tac Toe

The play_game() function initializes the game board as a 2D array with empty cells represented by spaces. It then enters into a loop that continues until the game is over (either a win or a tie). In each iteration of the loop, it prints the current state of the board using the print_board() function and prompts the current player for their move. The player's move is represented as a row and column index on the game board.

The function then checks if the move is valid (i.e., the chosen cell is empty). If the move is valid, it updates the game board with the player's symbol and checks if the player has won using the check_win() function. If the game is not over, it checks if the game is a tie using the check_tie() function and switches to the other player's turn if the game is still ongoing.

List and Dictionaries

In summary, lists and dictionaries are both data structures in Python, but they differ in their indexing, mutability, representation, and use cases. Lists are ordered collections of elements, identified by their position or index in the list, and are useful for homogeneous data and operations such as sorting and filtering. Dictionaries are unordered collections of key-value pairs, identified by their unique key, and are useful for heterogeneous data and operations such as lookup and mapping. Lists are represented using square brackets and dictionaries using curly braces. Lists are mutable, and so are dictionaries, but keys in dictionaries must be immutable.

ages = {'Alice': 25, 'Bob': 30, 'Charlie': 35}

# add a new key-value pair to the dictionary
ages['David'] = 40

# print the updated dictionary
print(ages)  # Output: {'Alice': 25, 'Bob': 30, 'Charlie': 35, 'David': 40}

# remove a key-value pair from the dictionary
del ages['Charlie']

# print the updated dictionary
print(ages)  # Output: {'Alice': 25, 'Bob': 30, 'David': 40}

# update the value of an existing key in the dictionary
ages['Bob'] = 35

# print the updated dictionary
print(ages)  # Output: {'Alice': 25, 'Bob': 35, 'David': 40}
{'Alice': 25, 'Bob': 30, 'Charlie': 35, 'David': 40}
{'Alice': 25, 'Bob': 30, 'David': 40}
{'Alice': 25, 'Bob': 35, 'David': 40}