
Jump to:
Day 1 – Game Development & Python Basics
Ice Breaker – Gaming History Quiz
Part 1: Gaming History
OBJECTIVE:
Discover our gaming DNA.
In the following game, write down your answers to the following question on the piece of paper provided. In your group decide on your group name and write down your group name and your name on the piece of paper and hand it up to the educators.
Gaming Heritage Questions:
- What was the first video game you ever played? (If you can’t remember, what’s the earliest one you do remember?)
- What’s your most memorable gaming moment? (A specific time you’ll never forget)
- Which game have you spent the most time playing? (Could be mobile, console, PC, etc.)
- What’s a game that taught you something important? (A skill, lesson, or way of thinking)
- If you could only play one game for the rest of your life, what would it be and why?
The educators will quiz you on the answers of the other members of your groups and see if we have a winning team who can remember the most about their group.
Class Discussion Questions:
- What patterns did you notice in our gaming histories?
- How have games changed from the earliest ones we played to now?
- What makes certain gaming moments stick in our memory?
- How do games teach us things without feeling like school?
Part 2: Daily Game Challenge – “Interactive Fiction Adventure”
Online Game: Play a text-based adventure together.
Try out: A Dark Room
What to do?
- Play the game for 10 minutes – educators will project a stop watch on the screen.
- Write down on a piece of paper the choices you make as you play the game.
- Discuss what happens with each choice
Meta Discussion Questions:
- How does the computer understand our choices?
- What information is the game keeping track of?
- How do our decisions change the story?
Connection: The game responds to player choices – we are going to try and build a text based game that responds to player choices.
Part 3: “What Makes Games Tick?”
Activity: Game Element Detective Work
Interactive Discussion: Let’s analyze the text game we just played
Think-Pair-Share:
- Think: What were the different “parts” of the game? (2 minutes)
- Pair: Share with a partner (3 minutes)
- Share: Tell the class what you discovered (10 minutes)
Your Mission: Now that we’ve discussed it as a class, go back and play the text adventure game again, but this time analyze it like a programmer.
Step 1: Game Elements Hunt
- 🎮 Find the Player/Character: Who or what are you playing as? What can you control?
- 🔀 List 3 specific choices: Write down exactly what options the game gives you
- 📊 Track information: What does the game remember about you? (health, location, items, etc.)
- ⚡ Find consequences: Give an example: “When I chose _______, then _______”
Step 2: Programming Connection
- Think like a programmer: If you were coding this game, what would the computer need to remember?
- List at least 3 things the program must track
- Partner Discussion: Compare your findings with someone next to you
Step 3: Design Thinking
- What made the game interesting?
- What would make it better?
- What choice would you add?
Introduction to Python Basics
Our Game Development Playground:
Step 1: Getting Started with Trinket
- Go to trinket.io
- Click “Sign Up” (use school email if available)
- Create a new Python project
- You should see a blank coding area
Step 2: Understanding What Programming Is: Before we start typing code, let’s understand what we’re doing:
What is Programming?
- Programming is giving instructions to a computer
- Just like giving directions to a friend, we need to be very specific
- Computers follow instructions exactly as written
- If we make a mistake, the computer will tell us with an “error message”
Step 3: Your First Python Command – The Print Statement
What is a Print Statement?
print()tells the computer to display text on the screen- It’s like telling the computer “say this out loud”
- The text goes inside quotation marks
- This is how we communicate with the user
Example:
print("Hello, World!")
Try this exact code in your Trinket:
print("I am going to be a game developer!")
Click the “Run” button. You should see your message appear below!
Important Coding Rules:
- Spelling matters:
printnotPrintorPRINT - Quotation marks matter:
"text goes here" - Parentheses matter:
print("text")
This is a parentheses ( or ), they are a type of bracket. Knowing your different kinds of brackets is important as your educators will refer to them in this way.
Step 4: Making Programs Interactive – The Input Function
What is Input?
input()lets the program ask the user a question- The program waits for the user to type something and press Enter
- We can save what the user types for later use
Example:
input("What's your name? ")
Personalization Challenge: Now modify the name program to ask a different question of your choice:
- “What’s your favorite color?”
- “What’s your superhero power?”
- “What’s your dream vacation spot?”
- Or create your own question!
Template to modify:
print("Welcome to my personalized program!")
user_answer = input("Your question here: ")
print(f"Interesting! {user_answer} is a great answer!")
Pair Work: Show your working code to a classmate and test it together Advanced Challenge: Can you ask TWO questions and use both answers in your response? Instructor Check: Demonstrate your modified code to get approval before moving on
When we have inputs, we need to SAVE the answer! This is where variables come in…
Building Your Game Character with Variables
What are Variables? Variables are like labeled boxes that store information for us. Imagine you have a box labeled “player_name” – you can put a name inside it and use it later.
Why do we need Variables?
- Games need to remember things (your score, health, location)
- Without variables, the computer would forget everything immediately
- Variables let us store and change information as the game progresses
Understanding Different Types of Variables
1. STRINGS – Text Information
What are Strings?
- Strings store text (letters, words, sentences)
- They ALWAYS go inside quotation marks
- Used for names, messages, locations, descriptions
Examples:
player_name = "Hero"
location = "Village"
character_class = "Warrior"
game_message = "Welcome to the adventure!"
Why the quotation marks?
- Without quotes, Python thinks you’re talking about a variable
- With quotes, Python knows it’s actual text
Try both of these – see the difference:
# This works - "Hero" is text
player_name = "Hero"
print(player_name)
# This would cause an error - Python looks for a variable called Hero
# player_name = Hero # Don't run this!
Why do we have # in the code above. In a line of code if we write in a # then everything that comes after will be a comment – which is txt that is not part of your code and is just for the code writer and future readers to understand why they code is written in the way that it is.
2. INTEGERS – Whole Numbers
What are Integers?
- Integers store whole numbers (no decimal points)
- Used for things you count: health points, gold coins, levels
- NO quotation marks needed
Examples:
health = 100
gold = 50
level = 1
damage = 25
Math with Integers:
health = 100
damage = 25
health = health - damage # health is now 75
print(f"Health remaining: {health}")
Why is the f in front of the (f”Health remaining: {health}”) – The f tells Python: “This string has variables inside it”
3. FLOATS – Decimal Numbers
What are Floats?
- Floats store numbers with decimal points
- Used for precise measurements: percentages, rates, speeds
Examples:
hit_chance = 0.75 # 75% chance to hit
speed = 2.5 # movement speed
price_multiplier = 1.2 # 20% markup
4. BOOLEANS – True or False
What are Booleans?
- Booleans store only True or False
- Used for yes/no questions: Is the player alive? Do they have a key?
- Notice: True and False are capitalized, no quotes
Examples:
is_alive = True
has_key = False
game_over = False
found_treasure = True
Using Booleans:
if is_alive == True:
print("The adventure continues!")
else:
print("Game Over!")
Creating Your Game Character with All Variable Types
Complete Character Example:
# Character Information (Strings)
player_name = "Sir Galahad"
location = "Village"
character_class = "Knight"
# Character Stats (Integers)
health = 100
gold = 50
level = 1
# Precise Values (Floats)
hit_chance = 0.85 # 85% accuracy
speed = 1.5 # movement speed
# Status Flags (Booleans)
is_alive = True
has_weapon = False
quest_complete = False
# Display all information
print("=== Character Stats ===")
print(f"Name: {player_name}")
print(f"Class: {character_class}")
print(f"Location: {location}")
print(f"Health: {health}")
print(f"Gold: {gold}")
print(f"Level: {level}")
print(f"Hit Chance: {hit_chance}")
print(f"Speed: {speed}")
print(f"Alive: {is_alive}")
print(f"Has Weapon: {has_weapon}")
Understanding f-strings (Formatted Strings)
What are f-strings?
- f-strings let us mix text with variables
- Put an
fbefore the quotation marks - Put variables inside curly braces
{}
Examples:
name = "Hero"
health = 100
# Without f-string (doesn't work well):
print("Name: " + name + " Health: " + str(health))
# With f-string (much better!):
print(f"Name: {name} Health: {health}")
Why f-strings are amazing:
player_name = "Dragon Slayer"
current_level = 5
next_level = current_level + 1
print(f"Congratulations {player_name}!")
print(f"You are level {current_level}")
print(f"Only {next_level - current_level} more level to go!")
Why f-strings are amazing:
1. They’re much easier to read:
- You can see exactly where each variable goes in the text
- No confusing plus signs or extra quotation marks
- The code looks similar to what actually gets printed
2. They prevent common errors:
- No forgetting to convert numbers to text (Python does it automatically)
- No missing spaces between words
- No mixing up the order of variables
3. They make your code look professional:
- This is how real programmers write Python today
- Much cleaner than the old methods
Let’s see the difference:
# The OLD way (confusing and error-prone):
player_name = "Dragon Slayer"
current_level = 5
next_level = current_level + 1
print("Congratulations " + player_name + "!")
print("You are level " + str(current_level)) # Had to convert number to string!
print("Only " + str(next_level - current_level) + " more level to go!")
# The NEW way with f-strings (clean and clear):
print(f"Congratulations {player_name}!")
print(f"You are level {current_level}")
print(f"Only {next_level - current_level} more level to go!")
Notice how the f-string version:
- Is easier to read and understand
- Doesn’t require converting numbers to strings
- Shows exactly what the output will look like
- Has fewer chances for typos and errors
🎮 Hands-On Activity: Design Your Game Character
Now it’s your turn to create a character using all the variable types we just learned!
Step 1: Analyze the Example: Look at the character code above and answer:
- What type of character is Sir Galahad? ________________
- How much gold does he start with? ________________
- Which variables are strings (text)? Which are integers (numbers)?
- Why do you think they chose these specific numbers?
Step 2: Create YOUR Character: Use this template to design your own unique character:
# My character design
player_name = "________________"
health = _____
gold = _____
level = _____
location = "________________"
class_type = "________________"
Character Design Tips:
- Name: Choose something that fits their personality
- Health: What number makes sense for your character type?
- Gold: Should they be rich, poor, or middle-class?
- Location: Where’s an interesting place to start their adventure?
Step 3: Add 3 Custom Stats (5 minutes) Make your character unique! Choose from these or create your own: magic_power, strength, stealth, intelligence, luck, charisma, speed, wisdom.
# My additional stats
_______ = _____
_______ = _____
_______ = _____
Step 4: Display Your Character Write code to show all your character’s information:
print("=== My Character ===")
print(f"Name: {player_name}")
print(f"Class: {class_type}")
print(f"Location: {location}")
print(f"Health: {health}")
print(f"Gold: {gold}")
print(f"Level: {level}")
# Add print statements for your custom stats
Partner Share: Explain your character choices to someone next to you – why did you pick these stats? Test Your Code: Make sure everything runs without errors Save to Trinket: Keep your character – we’ll use it later!
Decision Making – If/Else Statements
Activity: “Choose Your Path – How Computers Make Decisions”
What are If/Else Statements?
- If/Else statements let programs make decisions
- Just like humans: “IF it’s raining, THEN take an umbrella, ELSE wear sunglasses”
- The computer checks if something is true, then chooses what to do
Understanding Comparison Operators
Before we make decisions, we need to compare things:
Equal to: ==
if player_name == "Hero":
print("Welcome back, Hero!")
Not equal to: !=
if health != 0:
print("You're still alive!")
Greater than: >
if gold > 100:
print("You're rich!")
Greater than or equal: >=
if level >= 10:
print("You're a veteran adventurer!")
Less than or equal: <=
if health <= 0:
print("Game Over!")
The Basic If Statement Structure
Simple If Statement:
health = 100
if health > 50:
print("You're in good shape!")
If-Else Statement:
health = 25
if health > 50:
print("You're in good shape!")
else:
print("You need healing!")
If-Elif-Else Statement (Multiple Conditions):
health = 75
if health > 80:
print("You're in excellent condition!")
elif health > 50:
print("You're doing okay.")
elif health > 20:
print("You're badly hurt!")
else:
print("You're near death!")
Game Example: Making Meaningful Choices
Complete Adventure Choice Example:
# Set up the scenario
player_name = "Brave Explorer"
health = 100
gold = 30
has_torch = False
print(f"Welcome, {player_name}!")
print("You stand before a dark cave entrance...")
print(f"Current Health: {health}")
print(f"Current Gold: {gold}")
# Get player choice
choice = input("Do you enter the cave, buy supplies, or rest? (cave/supplies/rest): ")
# Process the choice
if choice == "cave":
print("You bravely enter the dark cave!")
if has_torch == True:
print("Your torch lights the way safely.")
gold = gold + 50 # Find treasure
print(f"You found treasure! Gold: {gold}")
else:
print("Without light, you stumble and get hurt.")
health = health - 20
print(f"Ouch! Health: {health}")
elif choice == "supplies":
if gold >= 25:
print("You buy a torch from the merchant.")
gold = gold - 25
has_torch = True
print(f"Remaining gold: {gold}")
else:
print("You don't have enough gold for supplies!")
elif choice == "rest":
print("You rest and recover your strength.")
health = health + 20
if health > 100: # Cap health at 100
health = 100
print(f"Health restored to: {health}")
else:
print("You're confused and waste time deciding.")
print("A wild animal attacks while you hesitate!")
health = health - 15
print(f"Health: {health}")
# Check final status
print("\n=== Adventure Status ===")
print(f"Health: {health}")
print(f"Gold: {gold}")
print(f"Has Torch: {has_torch}")
if health <= 0:
print("Game Over! Your adventure ends here.")
else:
print("Your adventure continues...")
🗺️ Build Your Own Adventure Activity
Now let’s create your own interactive adventure using if/else statements!
Step 1: Code Detective Work Look at the cave adventure code above and analyze:
- What happens if the player types “cave”? ________________
- What happens if they type “supplies”? ________________
- What happens if they type something completely different? ________________
- Why might health go down in the else section? ________________
Peer Check: Discuss your answers with a neighbor to make sure you understand each path.
Step 2: Plan Your Adventure Before coding, plan your story:
Choose your scenario:
- Lost in a magical forest
- Finding a mysterious door
- Meeting a strange character
- Discovering an ancient artifact
- Or create your own!
Plan your choices:
- What’s the main decision the player has to make?
- What are 2-3 different options they can choose?
- What happens with each choice?
- What happens if they type something unexpected?
Step 3: Build Your Adventure Scene Use this template to create your interactive story:
print("________________") # Describe your scene vividly
choice = input("________________") # Ask for a meaningful choice
if choice == "________________":
print("________________")
# What positive thing happens?
_______ = _______ + _____
elif choice == "________________":
print("________________")
# Different outcome:
_______ = _______ + _____
else:
print("________________")
# Handle unexpected input:
_______ = _______ + _____
Writing Tips:
- Be descriptive: Paint a picture with your words
- Make choices meaningful: Each option should feel different
- Add consequences: Change stats based on choices
- Handle unexpected input: What if they type something random?
Step 4: Test and Share
- Test thoroughly: Try different inputs – does everything work as expected?
- Peer Playtesting: Have a classmate play through your adventure
- Get feedback: Was the story engaging? Were the choices clear?
Advanced Challenge: Can you add a second choice that references what happened in the first choice?
Class Showcase: Be ready to demonstrate your adventure to the class!
Day 3 – Why do we Need Better Code Organization?
Why Do We Need Better Code Organization?
Activity: “Code Chaos Challenge”
Computational Thinking Spotlight: Problem Recognition
Quick Discussion: “Imagine your bedroom is a mess – clothes everywhere, books scattered, games mixed with homework. How do you organize your room to make finding things easier?”
Hands-On Code Analysis:
Your Mission: Look at this messy code and identify the problems:
# This gets messy fast!
player_health = 100
player_gold = 50
player_name = "Hero"
enemy1_health = 30
enemy1_name = "Goblin"
enemy2_health = 60
enemy2_name = "Orc"
def player_attack():
return random.randint(10, 20)
def enemy1_attack():
return random.randint(5, 12)
def enemy2_attack():
return random.randint(8, 18)
def heal_player():
global player_health
player_health += 20
Partner Activity: Work with someone nearby and answer:
- What happens when you want to add a 3rd enemy? List what you’d need to create:
- If you have a bug in enemy attacks, how many places might you need to check? ______
- What would happen if you wanted 10 different enemies? ______
Class Discussion:
- What patterns do you notice in the repetitive code?
- How is this like having an unorganized room?
The Solution: Object-Oriented Programming (OOP)
What is OOP? (Quick explanation – 2 minutes)
- A way to organize code like we organize the real world
- Group related information and actions together
- Create “blueprints” (classes) to make similar things easily
- Like having a filing system instead of a pile of papers
Python Class Basics
Creating a Class (Blueprint):
class Player:
def __init__(self, name):
# __init__ is like the "factory settings" for new objects
self.name = name
self.health = 100
self.gold = 0
def introduce(self):
print(f"Hello! My name is {self.name}")
print(f"I have {self.health} health and {self.gold} gold")
def take_damage(self, damage):
self.health = self.health - damage
print(f"{self.name} takes {damage} damage!")
print(f"Health is now: {self.health}")
Creating Objects (Actual Players):
# Make two different players from the same class
hero = Player("Sir Bravealot")
wizard = Player("Gandalf Jr")
# Each object is independent
hero.introduce()
wizard.introduce()
# They can do different things
hero.take_damage(20)
wizard.take_damage(10)
# Check their health - they're different!
print(f"Hero health: {hero.health}") # 80
print(f"Wizard health: {wizard.health}") # 90
Key Concepts:
1. class Player: – Creates the blueprint
2. def __init__(self, name): – The “constructor” – runs when you create a new object
selfrefers to the specific object being created- Parameters let you customize each object
3. self.name = name – Attributes (variables that belong to the object)
4. def introduce(self): – Methods (functions that belong to the object)
- Always include
selfas the first parameter - Can access the object’s attributes using
self.attribute_name
5. hero = Player("Sir Bravealot") – Creating an object from the class
🔨 Hands-On Activity: Create Your First Class
Goal: Build a simple Enemy class and create different enemies
Step 1: Understand the Pattern Look at this template and fill in what each part does:
class Enemy:
def __init__(self, name, health, damage):
self.name = name # What does this store? ___________
self.health = health # What does this store? ___________
self.damage = damage # What does this store? ___________
def attack(self):
# What should this method do? ___________
pass
def take_damage(self, damage_taken):
# What should this method do? ___________
pass
Step 2: Implement the Methods Complete the Enemy class:
class Enemy:
def __init__(self, name, health, damage):
self.name = name
self.health = health
self.damage = damage
def attack(self):
print(f"{self.name} attacks!")
print(f"It deals {self.damage} damage!")
return self.damage # Return how much damage was dealt
def take_damage(self, damage_taken):
self.health = self.health - damage_taken
print(f"{self.name} takes {damage_taken} damage!")
if self.health <= 0:
print(f"{self.name} has been defeated!")
else:
print(f"{self.name} has {self.health} health remaining")
def is_alive(self):
return self.health > 0
Step 3: Create and Test Your Objects:
# 1. Create 3 different enemies with different stats
enemy1 = Enemy("_______", ___, ___) # Fill in: name, health, damage
enemy2 = Enemy("_______", ___, ___)
enemy3 = Enemy("_______", ___, ___)
# 2. Test your enemies by making them fight each other!
# Make enemy1 attack enemy2
damage_dealt = enemy1.attack()
enemy2.take_damage(damage_dealt)
# 3. Create your own battle sequence
# - Make enemy2 attack enemy3
# - Make enemy3 attack enemy1
# - Check which enemies are still alive
# - Keep fighting until only one survives!
print("=== Battle Results ===")
print(f"Enemy 1 alive: {enemy1.is_alive()}")
print(f"Enemy 2 alive: {enemy2.is_alive()}")
print(f"Enemy 3 alive: {enemy3.is_alive()}")
Extension Challenge (if you finish early): Create a boss_enemy with 100+ health and see how many regular enemies it takes to defeat it!
Computational Thinking Questions:
- How is this different from having separate variables for each enemy?
- What happens when you want to add a 4th enemy? How many lines of code?
- How does the class make your code more organized?
Designing Tic-Tac-Toe with Classes
Activity: “Breaking Down the Game”
Computational Thinking Spotlight: Decomposition
What is Decomposition?
- Breaking big problems into smaller, manageable pieces
- Each piece can be solved separately, then combined
- Makes complex projects much easier to build and debug
Decomposing Tic-Tac-Toe
Big Problem: “Build a Tic-Tac-Toe game”
Decomposition Questions:
- What are the main “things” in Tic-Tac-Toe?
- What information does each “thing” need to remember?
- What actions can each “thing” do?
Brainstorming Session:
Things in Tic-Tac-Toe:
- The game board/grid
- Players (X and O)
- The game itself (rules, turns, winning)
Information each thing needs:
- Board: What’s in each square? Is the game over?
- Player: What symbol do they use? What’s their name?
- Game: Whose turn is it? Has someone won?
Actions each thing can do:
- Board: Display itself, check if a move is valid, check for wins
- Player: Make a move, choose a square
- Game: Start a new game, switch turns, end the game
Designing Our Classes
Class Design Challenge: Sorting the Pieces
Your Mission: We need to organize all the parts of Tic-Tac-Toe into the right classes. Work with a partner to sort these items!
The Mixed-Up List: Here are all the things our Tic-Tac-Toe game needs. Sort them into the three classes:
Items to Sort:
- display the grid to players
- store player name
- the 3x3 grid data
- check if someone won
- get move from player (ask for row/column)
- store player symbol (X or O)
- switch whose turn it is
- check if a square is empty
- place X or O in a square
- run the main game loop
- create the board and players
- check if board is full (tie game)
- keep track of whose turn it is
- show "You won!" or "Tie game!" messages
Sorting Activity:
Class 1: Board (The Grid Manager) What should the Board class be responsible for?
Class 2: Player (The Move Maker)
What should the Player class be responsible for?
Class 3: Game (The Rule Keeper) What should the Game class be responsible for?
Thinking Questions:
- Which class should check for a winner? Why?
- Which class should ask the player for their move? Why?
- Which class should know whose turn it is? Why?
Class Discussion: Compare your sorting with other teams. Did you put anything in different places? Why?
Computational Thinking: Systems Thinking
How do these classes work together?
- The Game class is the “manager” – it controls everything
- The Board class handles the grid and rules
- The Player class handles input and moves
- Each class has a specific job (separation of concerns)
Benefits of this design:
- Easy to find bugs (they’re probably in a specific class)
- Easy to add features (just modify the relevant class)
- Easy to test (test each class separately)
- Easy for teams to work together (different people work on different classes)
Hands-On Activity: Design Your Classes
Goal: Plan what each class needs to do and remember (without worrying about how to code it yet!)
Step 1: Board Class Planning
What does the Board need to REMEMBER?
What does the Board need to DO?
Design Questions:
- How should empty squares look to the player? Numbers 1-9? Spaces? Dashes?
- What should happen when someone tries to move to a taken square?
- How will you show the board? Draw a quick sketch.
Step 2: Player Class Planning (5 minutes)
What does a Player need to REMEMBER?
What does a Player need to DO?
Design Questions:
- How will players tell you where they want to move? □ Row and column numbers (like “row 1, column 2”) □ Single numbers 1-9 (like a phone keypad) □ Other: ________________________________
- What happens if they type something invalid?
Step 3: Game Class Planning (5 minutes)
What does the Game need to REMEMBER?
What does the Game need to DO?
Game Flow Design: Write the steps for one complete turn:
Design Questions:
- How do you know when the game is over?
- What should happen when someone wins?
- What should happen when it’s a tie?
Activity: “Building the Foundation”
Computational Thinking: Start with the Simplest Piece
Implementation Strategy:
- Start with the easiest class (usually the one with least complexity)
- Test it thoroughly before moving to the next
- Build classes that depend on others last
Quick Implementation: Board Class
Let’s build the Board class together, step by step:
Mini-Tutorial: 2D Lists Before we build the board, let’s understand how to make a grid:
# A list inside a list makes a grid!
# Think of it as 3 rows, each with 3 columns
row1 = [" ", " ", " "]
row2 = [" ", " ", " "]
row3 = [" ", " ", " "]
grid = [row1, row2, row3]
# Or we can write it all at once:
grid = [
[" ", " ", " "], # Row 0
[" ", " ", " "], # Row 1
[" ", " ", " "] # Row 2
]
# How do we access squares?
grid[0][0] = "X" # Row 0, Column 0 (top-left)
grid[1][1] = "O" # Row 1, Column 1 (center)
grid[2][2] = "X" # Row 2, Column 2 (bottom-right)
print(grid[0]) # Shows first row: ['X', ' ', ' ']
print(grid[1][1]) # Shows center square: 'O'
# Practice: How would you put "Z" in the bottom-left corner?
grid[___][___] = "Z" # Fill in the blanks!
Try it: Create a simple 2×2 grid and put your initials in opposite corners.
Mini-Tutorial: F-String Formatting We need to learn how to put variables inside strings nicely:
name = "Alice"
score = 95
row = 1
symbol = "X"
# Old way (harder to read):
print("Player " + name + " scored " + str(score) + " points")
# New way with f-strings (much easier!):
print(f"Player {name} scored {score} points")
print(f"Row {row} has {symbol} in it")
print(f"The score is {score + 5}") # You can even do math inside!
# Practice examples:
health = 85
player_name = "Hero"
print(f"{player_name} has {health} health points")
print(f"Next level at {health + 15} points")
Try it: Create an f-string that shows a tic-tac-toe row like: “1 X | O | “
Mini-Tutorial: Return Values Functions can give back information using return:
def add_numbers(a, b):
result = a + b
return result # Gives back the answer
# When we call the function, we get the result back
answer = add_numbers(5, 3) # answer becomes 8
print(f"5 + 3 = {answer}")
def is_even(number):
if number % 2 == 0:
return True # Give back True if even
else:
return False # Give back False if odd
# We can use the True/False in an if statement
if is_even(6):
print("6 is even!")
def check_password(password):
if len(password) >= 8:
return True # Good password
else:
return False # Too short
# Practice: What does this return?
result = check_password("hello123") # True or False?
Now Apply What You Learned!
Step 1: Create the Board Class
class Board:
def __init__(self):
# YOUR TURN: Create a 3x3 grid filled with spaces
# Use what you learned about 2D lists above
self.grid = _______________
Step 2: Display Method
def display(self):
# YOUR TURN: Make it display like this:
# 0 1 2
# 0 X | | O
# ---------
# 1 | X |
# ---------
# 2 O | | X
# Hints:
# - Use print() for each line
# - Use f-strings to put grid values in: f"0 {self.grid[0][0]} | ..."
# - Remember: self.grid[row][col] gets a square
print("_______________") # Replace with column headers
print("_______________") # Replace with row 0
print("_______________") # Replace with separator
# Add the rest!
Step 3: Making Moves
def make_move(self, row, col, symbol):
# YOUR TURN:
# 1. Check if the move is valid using self.is_valid_move()
# 2. If valid: put the symbol in the grid and return True
# 3. If not valid: return False
if _______________: # Check if move is valid
# Put symbol in the right place
# Return success
else:
# Return failure
def is_valid_move(self, row, col):
# YOUR TURN:
# A move is valid if:
# 1. Row is between 0 and 2 (use: row >= 0 and row <= 2)
# 2. Column is between 0 and 2
# 3. Square is empty (self.grid[row][col] == " ")
# Check all three conditions and return True/False
Testing Your Code: Once you finish, test it like this:
board = Board()
board.display()
print(board.make_move(1, 1, "X")) # Should print True
print(board.make_move(1, 1, "O")) # Should print False (already taken)
board.display()
Now test YOUR Board class implementation:
Challenge 1: Basic Testing
# Create your board and test it
my_board = Board()
# Test these scenarios and see what happens:
my_board.display() # Does it show an empty grid?
my_board.make_move(1, 1, "X") # Put X in center - does it work?
my_board.display() # Do you see the X?
Challenge 2: Edge Case Testing Test these scenarios and predict what should happen:
# Test invalid moves - what SHOULD each of these return?
print("=== Testing Invalid Moves ===")
result1 = my_board.make_move(1, 1, "O") # Try to put O where X already is
print(f"Move to occupied square: {result1}") # Should this be True or False?
result2 = my_board.make_move(5, 5, "O") # Try to move outside the board
print(f"Move outside board: {result2}") # Should this be True or False?
result3 = my_board.make_move(-1, 0, "O") # Try negative coordinates
print(f"Move to negative position: {result3}") # Should this be True or False?
Challenge 3: Build a Game Scenario – Create a mini tic-tac-toe scenario:
# YOUR TURN: Create a game situation
# Make moves for X and O to create this pattern:
# 0 1 2
# 0 X | | O
# 1 | X |
# 2 O | |
game_board = Board()
# Add your moves here:
game_board.make_move(___, ___, "X") # Fill in coordinates
game_board.make_move(___, ___, "O") # Fill in coordinates
# Add more moves...
game_board.display() # Does it match the target pattern?
Debugging Questions:
- Does the board display correctly?
- Do valid moves work as expected?
- Are invalid moves properly rejected?
- What happens if you try to move outside the 3×3 grid?
- Can you place multiple symbols and see them all?