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
How I used iteration (game example)
- What parts of the code use iteration
- The code uses dour for loops to iterate through the number of UPinput, DOWNinput, LEFTinputvalues, respeciviley, and push corresponding movements to the movement array. Also uses a for loop to iterate through the looper value, which determines the number of times the nested for loops run.
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])
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: 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)
New Block with answered questions
1: 2D Array
Tic Tac Toe:Kush Sirohi
- What are some examples of 2d Arrays
- Some examples of 2d arrays, are int main()[ and #include<stdio.h>
- What is a modern day game that could be classified as a 2D array
- Checkers, tic-tac-toe, crosswords and mazes
How I used 2D Arrays (game example)
- Describe a 2D array in your own words
- They are arrays where the data element's position is refereed to by two indices
2: Iteration
Robot Game:Finn Carpenter- What is the defenition of iteration in your own words -Iteration is the process of repeatedly performing a set of instructions or activities until a particular condition is satisfied, for a predetermined number of times.
Iteration Game
- Link to the game
- Play the levels (only play the first 2 in class)
- Explain how the game relates to itertation
- This game relates to iteration since it involves repeating steps until a condition is satisfied, which in this case is bringing the robot to the desired location.
How I used iteration (game example)
- What parts of the code use iteration
- The code uses dour for loops to iterate through the number of UPinput, DOWNinput, LEFTinputvalues, respeciviley, and push corresponding movements to the movement array. Also uses a for loop to iterate through the looper value, which determines the number of times the nested for loops run.
How I used List to make a game
- Explain which parts of the code use lists
- the word_list is used for the code and word_list is then called later
- Explain what list manipulation is happening in that part
- word_list is called in word where they use a random choice from the word_list, the words are then used for the game
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
import time
# Define the text to spin.
text = "SPINNING!"
# Set the delay between frames.
delay = 0.1
# Iterate through each character in the text, shifting the characters to the right by one position on each iteration.
for i in range(len(text)):
# Clear the console screen.
print("\033[H\033[J")
# Create a new text string with the shifted characters.
shifted_text = " " * i + text[i:] + text[:i]
# Print the shifted text to the console.
print(shifted_text)
# Wait for a short delay before printing the next frame.
time.sleep(delay)
2D array 0.2 (can get up to 0.23)
- Explain how the tic tac toe game works
A 3x3 grid is used for the game, and each cell is either vacant or marked with a "x" or a "o". The 3 rows and 3 columns of the 2D array are used to map out the potential locations of a "x" or "o" on the game board.
- Give 3 Examples of games that can be made from 2D arrays
Chess, 2048, Sudoku
List and Dictionaries 0.2 (can get up to 0.23)
- Explain the differences between Lists and Dictionaries
Dictionaries are used to store collections of key-value pairs, while lists are used to store ordered collections of items. Both of them are useful for creating a lot of code and are used to store values in various ways.
- Make a code block that manipulates either a list or a dictionary
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original list:", list)
list.append(11)
print("List after adding 11:", list)
list.pop(0)
print("List after removing the first element:", list)
list.reverse()
print("List after reversing the order:", list)
list.sort()
print("List after sorting in ascending order:", list)
Lists:
The players' names are stored in the players list, which is created as a list of tuples that contains each player's name and score. The sorted_data variable is a list of tuples that contains the player's name and their score, sorted in descending order based on the score. There is also an empty list [] used to clear the leaderboard.
Dictionaries:
The player's data is stored in the data dictionary, which contains the player's name and their high score. It is loaded from and saved to a JSON file using the json library. The sorted_data variable is a list of tuples containing data from the data dictionary.
import turtle
import json
# Define the function to display leaderboard
def display_leaderboard(leaderboard):
# Load the data from the file
with open('data.json', 'r') as f:
data = json.load(f)
# Sort the data based on high score
sorted_data = sorted(data.items(), key=lambda x: x[1]['high_score'], reverse=True)
# Clear the leaderboard
leaderboard.clear()
leaderboard.write("Leaderboard", align="center", font=("Courier", 18, "normal"))
leaderboard.goto(0, -260)
leaderboard.write("--------------------", align="center", font=("Courier", 14, "normal"))
for i, (name, score) in enumerate(sorted_data[:5]):
leaderboard.goto(0, -300 + i * 30)
leaderboard.write(f"{i+1}. {name}: {score['high_score']}", align="center", font=("Courier", 14, "normal"))
# Load or create the data file
try:
with open('data.json', 'r') as f:
data = json.load(f)
except FileNotFoundError:
data = {}
# Update the score for the player
player_name = input('Enter your name: ')
if player_name in data:
score = data[player_name]['high_score']
else:
score = 0
data[player_name] = {'high_score': score}
# Initialize score variable to 0
player_score = input("Enter your score: ")
# Convert player score to an integer and assign it to the score variable
score = max(score, int(player_score))
# Update the high score for the player in the data file
if score > data[player_name]['high_score']:
data[player_name]['high_score'] = score
# Print the score
print("Your score is:", score)
# Save the updated data
with open('data.json', 'w') as f:
json.dump(data, f)
# Display the high score for the player
print(f'Your highest score is {data[player_name]["high_score"]}')
# Define the function to display leaderboard
def display_leaderboard():
# Load the data from the file
with open('data.json', 'r') as f:
data = json.load(f)
# Sort the data based on high score
sorted_data = sorted(data.items(), key=lambda x: x[1]['high_score'], reverse=True)
# Display the top 5 players and their scores
print("Leaderboard")
print("-----------")
for i, (name, score) in enumerate(sorted_data[:5]):
print(f"{i+1}. {name}: {score['high_score']}")
print("")
# Users enter their names
left_player_name = turtle.textinput("Player 1", "Enter your name:")
right_player_name = turtle.textinput("Player 2", "Enter your name:")
# Update the score for the player
for player_name in [left_player_name, right_player_name]:
if player_name in data:
score = data[player_name]['high_score']
else:
score = 0
data[player_name] = {'high_score': score}
# Save the updated data
with open('data.json', 'w') as f:
json.dump(data, f)
# Create screen
sc = turtle.Screen()
sc.title("Pong game")
sc.bgcolor("pink")
sc.setup(width=1000, height=600)
# Left paddle
left_pad = turtle.Turtle()
left_pad.speed(0)
left_pad.shape("square")
left_pad.color("red")
left_pad.shapesize(stretch_wid=6, stretch_len=2)
left_pad.penup()
left_pad.goto(-400, 0)
# Right paddle
right_pad = turtle.Turtle()
right_pad.speed(0)
right_pad.shape("square")
right_pad.color("red")
right_pad.shapesize(stretch_wid=6, stretch_len=2)
right_pad.penup()
right_pad.goto(400, 0)
# Ball of circle shape
hit_ball = turtle.Turtle()
hit_ball.speed(40)
hit_ball.shape("circle")
hit_ball.color("hot pink")
hit_ball.penup()
hit_ball.goto(0, 0)
hit_ball.dx = 5
hit_ball.dy = -5
# Initialize the score
left_player = 0
right_player = 0
# Displays the score
sketch = turtle.Turtle()
sketch.speed(0)
sketch.color("blue")
sketch.penup()
sketch.hideturtle()
sketch.goto(0, 260)
sketch.write("{} : {} {} : {}".format(left_player_name, left_player, right_player_name, right_player),
align="center", font=("Courier", 24, "normal"))
# Leaderboard
leaderboard = turtle.Turtle()
leaderboard.speed(0)
leaderboard.color("blue")
leaderboard.penup()
leaderboard.hideturtle()
leaderboard.goto(0, -260)
leaderboard.write("Leaderboard", align="center", font=("Courier", 18, "normal"))
# Create a list of tuples to store player names and scores
players = [(left_player_name, left_player), (right_player_name, right_player)]
# Sort the list in descending order based on scores
players.sort(key=lambda x: x[1], reverse=True)
# Display the top 5 players and their scores
for i in range(min(5, len(players))):
leaderboard.goto(0, -300 + i * 30)
leaderboard.write(f"{i+1}. {players[i][0]}: {players[i][1]}", align="center", font=("Courier", 14, "normal"))
# Functions to move paddle vertically
def paddleaup():
y = left_pad.ycor()
y += 20
left_pad.sety(y)
def paddleadown():
y = left_pad.ycor()
y -= 20
left_pad.sety(y)
def paddlebup():
y = right_pad.ycor()
y += 20
right_pad.sety(y)
def paddlebdown():
y = right_pad.ycor()
y -= 20
right_pad.sety(y)
# Keyboard bindings
sc.listen()
sc.onkeypress(paddleaup, "e")
sc.onkeypress(paddleadown, "x")
sc.onkeypress(paddlebup, "Up")
sc.onkeypress(paddlebdown, "Down")
# Function to clear the screen
def sketch_clear():
sketch.clear()
while True:
sc.update()
hit_ball.setx(hit_ball.xcor()+hit_ball.dx)
hit_ball.sety(hit_ball.ycor()+hit_ball.dy)
# Checking borders
if hit_ball.ycor() > 280:
hit_ball.sety(280)
hit_ball.dy *= -1
if hit_ball.ycor() < -280:
hit_ball.sety(-280)
hit_ball.dy *= -1
if hit_ball.xcor() > 500:
hit_ball.goto(0, 0)
hit_ball.dy *= -1
left_player += 1
sketch_clear()
sketch.write("{} : {} {} : {}".format(left_player_name, left_player, right_player_name, right_player),
align="center", font=("Courier", 24, "normal"))
if hit_ball.xcor() < -500:
hit_ball.goto(0, 0)
hit_ball.dy *= -1
right_player += 1
sketch_clear()
sketch.write("{} : {} {} : {}".format(left_player_name, left_player, right_player_name, right_player),
align="center", font=("Courier", 24, "normal"))
# Paddle ball collision
if (hit_ball.xcor() > 360 and hit_ball.xcor() < 370) and (hit_ball.ycor() < right_pad.ycor()+40 and hit_ball.ycor() > right_pad.ycor()-40):
hit_ball.setx(360)
hit_ball.dx*=-1
if (hit_ball.xcor()<-360 and hit_ball.xcor()>-370) and (hit_ball.ycor()<left_pad.ycor()+40 and hit_ball.ycor()>left_pad.ycor()-40):
hit_ball.setx(-360)
hit_ball.dx*=-1