P4-M 4/24 Big Idea 3
Lesson about Big Idea 3
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
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)
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()
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)
Iteration Game
- Link to the game
- Play the levels (only play the first 2 in class)
- Explain how the game relates to itertation
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);
}
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])
How I used a dictonary to make a game
Memory Game:James- Link
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!")
Hacks General Answers
What are some examples of 2d Arrays?
Examples of 2D Arrays include: A chessboard where each row represents a row of the board and each column represents a column of the board. A spreadsheet, where each row represents a record and each column represents a specific field. Or a basic game board, where each row represents a row of the board and each column represents a column of the board.
What is a modern day game that could be classified as a 2D array?
Tetris is a modern day puzzle game where players must stack falling blocks into complete rows. The game board is a 2D array, with each row representing a row of the board and each column representing a column of the board.
Describe a 2D array in your own words
A 2D array is one with two dimensions, or axes. This means it can be viewed as a rectangular grid of elements. A 2D array element is uniquely recognized by its row and column indexes.
What is the definition of iteration in your own words
Iteration is the process of repeating a procedure until the desired result is obtained. For example, a for loop can use iteration to step though objects in a list or array.
What parts of the code use iteration
The for loops in the movements array. These loops iterate over the UPinput, DOWNinput, LEFTinput, and RIGHTinput variables to create an array of movements.
2D Array 0.2
To represent the Tic Tac Toe game board, create a 2D array of size 3x3, also called a matrix. You can initialize all elements to a default value, for example, an empty string ' '.
Write a function to display the game board, by iterating over the rows and columns of the 2D array and printing out their values.
Write a function to update the board when a player makes a move. This function should take as input the row and column where the player wants to place their symbol (either 'X' or 'O') and update the corresponding element in the 2D array.
Write a function to check if the game has ended. To check for winning conditions, iterate over the rows, columns, and diagonals of the 2D array and check if all elements are equal to the same symbol ('X' or 'O').
Write a main function to run the game. The main function should alternate between the two players, prompting them to enter their moves and displaying the updated board after each move. The game should end when a player wins or the board is full (a tie). You can call the play_game function to start playing the Tic Tac Toe game.
1) Connect Four: This is a two-player game in which players take turns dropping colored tokens into a vertically suspended 2D grid. The objective is to connect four of one's own tokens of the same color vertically, horizontally, or diagonally. The 2D array can be used to represent the game board, and each element can hold the color of the token at that position.
2) Minesweeper: This is a single-player game in which the player must clear a rectangular grid containing hidden "mines" without detonating any of them. The 2D array can be used to represent the game board, and each element can hold information about whether it is a mine or not, and how many neighboring cells contain mines.
3) Battleship: This is a two-player game in which each player places a number of ships on a 10x10 grid representing the ocean. Players take turns guessing the coordinates of the other player's ships, and the objective is to sink all of the opponent's ships. The 2D array can be used to represent the game board, and each element can hold information about whether it contains a ship or not, and whether it has been hit by a guess or not.
List and Dictionaries 0.2
Lists and dictionaries are both used to store and manipulate data in Python, but they have some key differences.
A list is an ordered collection of values, which can be of any data type. The elements in a list are indexed by their position, starting from 0 for the first element. Lists are mutable, which means you can add, remove, or modify elements in place.
A dictionary, on the other hand, is an unordered collection of key-value pairs, where each key must be unique. Dictionaries are also mutable, and you can add, remove, or modify key-value pairs in place.
Here's an example code block that demonstrates how to manipulate a list:
numbers = [1, 2, 3, 4, 5]
# add an element to the end of the list
numbers.append(6)
# remove the first element of the list
numbers.pop(0)
# modify the second element of the list
numbers[1] = 10
# print the updated list
print(numbers)
# create a dictionary of prices
prices = {"apple": 0.5, "banana": 0.25, "orange": 0.75}
# add a new key-value pair to the dictionary
prices["pear"] = 0.4
# remove a key-value pair from the dictionary
del prices["banana"]
# modify the value associated with a key in the dictionary
prices["apple"] = 0.6
# print the updated dictionary
print(prices)
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