Computing 8.
Testing conditions
Developing games
Introduction
• Computer games are made of many parts.
• A team of developers codes different components.
• Writing a game = complex task
• Break big problems → smaller sub-tasks (easier to plan + code).
• In this unit: Learn coding with Python (a text-based programming language).
Think About Games
Questions to discuss:
• Does the player control a character? How?
• Are there other icons on the screen? What do they do?
• Does the game have levels? What must the player do to move up?
What You Will Learn
• Follow and understand algorithms (step-by-step rules).
• Predict outcomes → check if results are correct.
• Break big problems into small sub-problems.
• Learn why programming uses libraries (ready-made code collections).
Python Skills
• Use library functions in Python.
• Work with different data types (numbers, text, true/false).
• Create programs with IF–ELSE (conditional statements).
• Combine AND, OR, NOT (logic rules) in programs.
Programming Practice
• Build Python programs step by step (iterative process ).
• Write programs with different data types.
• Apply rules (AND, OR, NOT) in algorithms.
• Use selection and libraries to solve problems.
Testing Programs
• Create and follow a test plan.
• Make sure the program works correctly.
• Use different test data (inputs) to check accuracy.
• Understand why many test cases are important.
KEYWORD
Text-based programming: Programmer types text to code (e.g., Python).
Warm-Up
1️⃣ What is the aim of the game?
To complete challenges or reach the end successfully.
2️⃣ What might prevent the player from completing the game?
Obstacles, wrong moves, time limits, or losing lives.
3️⃣ How could you make this game easier/harder?
Easier: Fewer obstacles, more time, hints.
Harder: More obstacles, less time, tricky puzzles.
4️⃣ What methods of scoring could the game use?
Points for completing levels, collecting items, solving puzzles, or speed bonus.
Note: By doing this, you start breaking a big task into smaller elements.
Scenario – Quiz Game Idea
• Your school wants a text-based quiz game for students aged 8+
• Players solve puzzles to generate a code
• The code unlocks a digital treasure chest
Puzzle areas:
• Anagrams
• Capital cities of the world
• Mental arithmetic
How the Game Works
• Collect player’s name and age first.
• Only players 8 years or older can play
• Player chooses a puzzle room
• Each correct answer gives:
• Points
• Letters to form the code
• High score → unlock treasure chest
Developing the Game
• Game released in stages (because team is behind schedule)
• Your task: Develop different parts of the game
• You will:
• Use sample code
• Create new code
• Edit and test code to make it work
Keywords & Fun Fact
• Text-based quiz game: Player types answers to questions or puzzles.
Did you know?
• Early computer adventure games were text-based (no graphics).
• Example: Zork (1980s) – still playable online today!
• Graphics were limited because computers were not powerful.
Before You Start
You should already be able to:
• Identify different data types in Python
• Create programs using different data types
• Use input and output in programs
• Use variables to perform calculations
• Apply a test plan to check programs
• Identify errors and debug programs
• Create flowcharts with selection statements
• Use different arithmetic operators
• Identify sequence and selection constructs in problem-solving
• Follow, understand, edit, and correct algorithms with sub-routines
Using Python – IDLE Setup
Python IDLE = environment to create, edit, and run Python programs
Steps to install:
1️⃣ Go to [Link]/downloads
2️⃣ Click Download Python
3️⃣ Open the downloaded file
4️⃣ Choose Install Now
After installation, IDLE appears in your Start menu
Breaking Things Down
• In everyday life, we solve problems step by step.
• Example: Getting to school in the morning
• Main task = getting to school
• Smaller sub-tasks help complete the main task:
• Get out of bed
• Get washed/showered
• Get dressed
• Eat breakfast
• Travel to school
Breaking Sub-Tasks Further
Example: Making egg on toast
1️⃣ Get a slice of bread.
2️⃣ Put bread in toaster & turn it on.
3️⃣ Get a frying pan & add oil.
4️⃣ Turn on the stove.
5️⃣ Crack an egg into the pan & cook.
6️⃣ Butter the toast.
7️⃣ Place the egg on toast.
More Real-Life Examples
• Doing laundry: Separate clothes by color before washing
• Decorating a room: Remove pictures, choose paint, prepare tools
• Baking a cake: Choose cake, find recipe, gather ingredients, pick topping
Decomposition in Programming
• Breaking a big problem into smaller tasks = easier to solve
• Example: Creating a computer game
• Programmers use decomposition to plan and code step by step.
Keyword
Decomposition: Breaking a problem into smaller sub-problems to make it
easier to solve.
Football Game Example
A football game can be broken into smaller parts:
Fill-in-the-Gaps
Complete the sentences:
1️⃣ Decomposition is the process of breaking a computing problem down
into smaller sub-problems.
2️⃣ Decomposition makes problems easier to solve and allows multiple
people to work on parts of the same problem.
3️⃣ As each sub-problem is solved, it can be tested independently before
being combined with other code to solve the full problem.
Real-Life Example – Police Officer
When solving a crime, a police officer needs to consider:
• Evidence collection
• Witness statements
• Suspect interrogation
• Crime scene investigation
• Forensic analysis
• Motive and opportunity
Fantasy Adventure Game
• Character completes different levels
• Character can do movements, actions, special powers
• Example decomposition diagram:
Car-Racing Game Example
Break down the game into smaller tasks:
Race tracks: How to win:
• Straight tracks • Finish first
• Curves • Collect points
• Obstacles • Avoid crashes
Cars:
• Speed
• Handling
• Special abilities
Iterative Development
• A way to solve problems step by step
• Break problems into smaller sub-problems (decomposition)
• Develop and test in repeated cycles
• Add new features slowly each time
• Popular method in computing
Stages of Iterative Development
1️⃣ Plan
2️⃣ Design
3️⃣ Develop
4️⃣ Test
5️⃣ Review & Evaluate
Plan Stage
• Decide what you need to do before starting
• Identify requirements to measure success
• Example: Football game
• Characters & icons
• Movements and actions
• Player objectives
• Decide order to complete sub-tasks
• Stadium/backdrop first or
• Players and controls first
Design Stage
• Map out a solution using algorithms
• Decide requirements for each character and icon
• Plan how players score goals and how teams win
• Example: Create a flowchart for player movement controls
Develop Stage
• Produce the solution step by step
• Write code for each part of the program
• Example: Code to move a football player around the screen
• Add features one at a time to check they work
Player Movement Example
Algorithm for moving a player:
• Is left arrow key pressed?
• Yes → Move 10 steps left
• No → Check next key
• Is right arrow key pressed?
• Yes → Move 10 steps right
• No → Check next key
• Is up arrow key pressed?
• Yes → Move 10 steps up
• No → Check next key
• Is down arrow key pressed?
• Yes → Move 10 steps down
Test Stage
• Test the solution to make sure it works correctly
• Some testing happens during development
• Example: Football game
• Check players move in all directions using keys
• Ensure all features work as designed
Review & Evaluate
• Done at the end of the cycle
• Check if original requirements are met
• Evaluate how successful the iteration was
• May need to reprioritize tasks for next iteration
• Example: Football game
• Decide which new actions to add: jump, kick the ball, etc.
Keywords
• Iterative development / process: How a project develops in stages
• Algorithm: Step-by-step instructions to solve a problem
• Flowchart: Visual diagram of an algorithm
• Software: Programs that tell a computer what to do
• Program: Instructions that tell a computer how to complete a task
• Iteration: Repetition
Practise – Platform Game
Task: Create a decomposition diagram for a basic platform game
• Game requires a character to move and collect items
• Avoid hazards
• Identify main features and sub-tasks:
• Characters
• Collectable items
• Hazards
• Background objects
• Compare your diagram with a partner’s diagram
• Discuss order to complete sub-tasks and why
Making Choices – Selection
• Some actions depend on decisions
• This is called selection
• Ask a TRUE / FALSE question
• Example in games:
• Check if player picked the correct key
• Decide what happens next based on the answer
Selection in MicroPython (micro:bit)
while True:
if button_a.is_pressed():
[Link]([Link])
if button_b.is_pressed():
[Link]([Link])
if → checks condition (TRUE or FALSE)
: → starts the code to run if condition is TRUE
Selection in Standard Python
password = "letmein"
INPUT userPW
if userPW == password:
OUTPUT "Welcome to the program"
else:
OUTPUT "Access denied“
Ask question: Is password correct?
• If TRUE → show welcome message
• If FALSE → show access denied
Conditional Operators
Conditional operators are used to compare values
Common operators:
• < less than
• > greater than
• == equal to
• != not equal to
• <= less than or equal to =
• >= greater than or equal to =
If Statement Example
points = 75
if points > 100:
print("An excellent score")
points variable = 75
• if checks condition (points > 100)
• Indented code runs only if condition is TRUE
• Here, nothing prints because 75 is not > 100
If-Else Statement
points = 75
if points > 100:
print("An excellent score!")
else:
print("Not enough to be excellent.")
else runs code if condition is FALSE
• Output = "Not enough to be excellent"
• Stop indenting to end the if part
• Indent under else for code to run when condition is FALSE
Keywords
• Selection: Choice in a program based on a question
• MicroPython: Programming language for micro:bit
• Condition: Question asked to decide next instruction
• Conditional operator: Symbol like >, <, ==, used for comparisons
• Variable: Named storage in a program; value can change
• Indented: Code moved right to show it runs if condition is TRUE
Pseudocode Example – Ride Height
Pseudocode:
INPUT userHeight
IF userHeight < 130 THEN
OUTPUT "Sorry, you are too short for this ride."
ELSE
OUTPUT "Welcome aboard!"
Keyword:
OUTPUT "Enjoy the ride." • Pseudocode: Text version of an algorithm
ENDIF • Question: What happens if userHeight = 140?
• Output:
• "Welcome aboard!"
• "Enjoy the ride."
Python Practice – [Link]
Steps:
1️⃣ Open Python IDLE → File → New File
2️⃣ Follow the pseudocode to write the program
3️⃣ Save as [Link]
4️⃣ Test:
• Height = 140 → "Welcome aboard!"
• Height = 120 → "Sorry, you are too short for this ride."
Using Elif – Multiple Conditions
Example: Compare two numbers
number1 = int(input("Enter a number: "))
number2 = int(input("Enter another number: "))
if number1 > number2:
print("The first number is bigger.")
elif number2 > number1:
print("The second number is bigger.")
else:
print("Both numbers are the same.")
• elif = else if (check another condition if first is FALSE)
• int() ensures numbers are whole numbers
How the Program Works
1️⃣ Check if number1 > number2 → TRUE → print first number is bigger
2️⃣ If not, check number2 > number1 → TRUE → print second number is bigger
3️⃣ Else → both numbers are the same
Practise Flowchart – What to Wear
Flowchart logic:
• INPUT temperature
• Is temperature < 5?
• YES → "You might need your coat."
• NO → Is temperature > 20?
• YES → "Take your sunhat."
• NO → "Wear your normal clothes."
Discussion:
Temperature < 5 → output "You might need your coat."
Python Practice – [Link]
Steps:
1️⃣ Open Python IDLE → File → New File
2️⃣ Follow flowchart to write program
3️⃣ Save as [Link]
4️⃣ Test cases:
• Temp < 5 → "You might need your coat."
• Temp > 20 → "Take your sunhat."
• Temp = 10 → "Wear your normal clothes."
Keywords
• Integer: Whole number
• Data: Raw facts or figures
• String: Text, numbers, or symbols in quotes " "
Quiz Game – Variables
Variables store different data during the game
Variables needed at the start:
Variable Data type Use / Reason
username String Store player’s name (letters/numbers)
userAge Integer Store age to check if player can play
Other Data Types
• Real: Numbers with decimal points, e.g., 7.68
• Boolean: Stores TRUE or FALSE
• Constant: Value does not change during program
Using a Constant – Minimum Age
Example pseudocode:
minAge = 8
INPUT userAge
IF userAge < minAge THEN
OUTPUT "Sorry, you are too young to play this game."
ELSE
OUTPUT "Let the game begin."
ENDIF
• Constants are usually uppercase in Python
• Using a constant makes it easy to update the value in one place
Stopping the Program
If a player is too young, stop the program
if age < 8:
print("Sorry, you are too young.")
exit()
• Program runs normally up to this point
• Then asks: “Do you want to kill it?”
• Options: Cancel / OK
Keywords
• Data type: Type of data stored (number, string, etc.)
• Real: Numbers with decimal points
• Boolean: TRUE or FALSE
• Constant: Value that does not change
• Assigned: Giving a variable a value when created
Practise – Start Coding Your Quiz Game
Step 1 – Ask for player info
• Welcome the player: "Welcome to the quiz game."
• Ask for username
• Ask for userAge
• Check if player is old enough to play
Pseudocode – Player Age Check
OUTPUT "Welcome to the quiz game."
INPUT username
INPUT userAge
CONST minAge = 8
IF userAge < minAge THEN
OUTPUT "Sorry, you are too young to play this game."
EXIT
ELSE
OUTPUT "Let the game begin."
• Use CONST for minimum age
ENDIF
• Use EXIT to stop the program if too young
Python Implementation
print("Welcome to the quiz game.")
username = input("Enter your username: ")
userAge = int(input("Enter your age: "))
MIN_AGE = 8
if userAge < MIN_AGE:
print("Sorry, you are too young to play this game.")
exit()
else:
print("Let the game begin.")
Make sure data types are correct
• username → String
• userAge → Integer
Save, Test & Review
• Save file as: [Link]
• Test:
• Age ≥ 8 → "Let the game begin."
• Age < 8 → "Sorry, you are too young" + program exits
• Review with your partner to confirm it meets the requirements
• This is the first iteration of your program
Quiz Game – Different Pathways
• The quiz game can be broken into sub-tasks (decomposition)
• Sub-tasks include:
• Age check
• Quiz game start
• Menu for puzzle rooms
• Room 1, Room 2, Room 3
• Bonus question
• Score checked
• Endgame message
Keyword:
Decompose: Break a problem into smaller parts
Second Iteration – Menu System
• Next step: Create a menu for the player
• Player chooses puzzle room: 1, 2, or 3
• Program welcomes the player to the chosen room
• Example message: "Welcome to The Anagram Room"
Flowchart – Menu Choice
OUTPUT "Choose your puzzle room:"
Room 1: The Anagram Room
Room 2: The World Room
Room 3: The Mental Maths Room
INPUT roomChoice
IF roomChoice == 1:
OUTPUT "Welcome to The Anagram Room"
ELIF roomChoice == 2:
OUTPUT "Welcome to The World Room" • Ask for roomChoice
ELSE: • Use if, elif, else to check selection
OUTPUT "Welcome to The Mental Maths Room“
Python Example – [Link]
print("Choose your puzzle room:")
print("1. The Anagram Room")
print("2. The World Room")
print("3. The Mental Maths Room")
roomChoice = int(input("Enter your choice 1/2/3 now: "))
if roomChoice == 1:
print("Welcome to The Anagram Room")
elif roomChoice == 2: • Add this code below the first iteration
print("Welcome to The World Room")
• Save as [Link]
else:
• Run to check functionality
print("Welcome to The Mental Maths Room")
Example Program Run
Welcome to the quiz game.
Enter your chosen username: WhlzK1d
Enter your age: 10
Let the game begin.
WhlzK1d please choose a puzzle room:
1. The Anagram Room
2. The World Room
3. The Mental Maths Room
Enter your choice 1/2/3 now: 2
Welcome to The World Room.
Test Plan Template
Test
Data Entered Expected Output Pass / Fail
#
"Sorry, you are too young to play this game"
1 username=Wh1zK1d, age=4
+ exit
2 username=…, age=8, roomChoice=1 "Welcome to The Anagram Room"
username=…, age=10,
3 "Welcome to The World Room"
roomChoice=2
username=…, age=12,
4 "Welcome to The Mental Maths Room"
roomChoice=3
5 … … …
• Check all pathways through the program
• Briefly explain what each test is checking
Using Sub-programs
• Big problems can be broken into sub-programs (mini-programs).
• Sub-programs are defined using def keyword.
• They are written before the main program.
• Main program calls sub-programs when needed.
Example – Sub-program
# Sub-program
def welcome():
print("Welcome to my program.")
# Main program
welcome()
• Sub-program: welcome()
• Prints a message when called
• Indentation shows code belongs to sub-program
Returning Values
# Sub-program
def addition():
number1 = int(input("Enter a number: "))
number2 = int(input("Enter another number: "))
answer = number1 + number2
return answer
# Main program
result = addition()
print("The numbers added together total", result)
• Sub-program can return a value
• Main program stores result in a variable
Applying to QuizGame
Steps for Iteration 3 ([Link]):
• Open [Link].
• Define a new sub-program called puzzleRoom at the top.
• Move menu code into puzzleRoom() (indent properly).
• Add return roomChoice at the end.
• In the main program, call:
• room = puzzleRoom()
• Save as [Link]
# Sub-program
def puzzleRoom():
print("Choose your puzzle room:")
print("1. The Anagram Room") Example – Puzzle Room Sub-program
print("2. The World Room")
print("3. The Mental Maths Room")
roomChoice = int(input("Enter your choice 1/2/3 now: "))
if roomChoice == 1:
print("Welcome to The Anagram Room")
elif roomChoice == 2:
print("Welcome to The World Room")
else:
print("Welcome to The Mental Maths Room")
return roomChoice
# Main program
room = puzzleRoom()
The Anagram Room
• First pathway in the quiz game
• Solve anagrams earn points + secret code letters
• Remember: Enter answers in UPPERCASE
What is an Anagram?
Anagram = word with letters rearranged
Example: PPELA → APPLE
Player must solve 3 anagrams
Score changes based on answers
Points System
Start score = 0
Correct answer → +20 points + secret code letters
Wrong answer → –5 points
Secret code: choose your own word (used in all pathways)
Example Pseudocode
points = 0
OUTPUT "3 anagrams to solve. Use UPPERCASE."
Question1: "What kind of fruit is PPELA?"
INPUT answer1
IF answer1 = "APPLE" THEN
OUTPUT "Well done! +20 points, letters ON"
points = points + 20
ELSE
OUTPUT "Sorry. -5 points"
points = points - 5
ENDIF
Example Run
Game Output:
• Q1: PPELA → APPLE → +20 points, letters ON
• Q2: ORWRAPS → Sparrow → –5 points
• Q3: LURPEP → PURPLE → +20 points, letters PY
Final Score = 35
Task Reminder
Developing the Anagram Room Pathway
• Define 3 anagrams for the player to solve
• Add scoring system (+20 / –5)
• Reveal letters of secret code for correct answers
• Use a sub-program (anagram) for modular design
Test Plan (Template)
Before coding, predict expected outcomes.
Each test = one aspect of the game.
Test # Test Data Expected Outcome Pass/Fail
1 Q1 answered wrong (e.g. "APLE") –5 points, feedback “Sorry”
2 Q1 correct, Q2 wrong, Q3 correct Final score = 35, correct code letters given
3 All 3 correct Final score = 60, full code unlocked
4 All 3 wrong Final score = –15, no code letters
5 Correct but lowercase input (e.g. "apple") Treated as wrong, –5 points
Coding Steps
• Open [Link]
• Define new sub-program:
def anagram():
points = 0
print("Welcome to the Anagram Room.")
print("Solve 3 anagrams. Use UPPERCASE letters.")
# Q1, Q2, Q3 here
return points
Add questions + scoring logic inside
At end of main program:
if room == 1:
score = anagram()
Save as [Link]
Example Anagrams
Suggested set:
• PPELA → APPLE → Code letters: ON
• ORWRAPS → SPARROW → Code letters: TR
• LURPEP → PURPLE → Code letters: PY
Final code = ONTRPY
Testing & Review
• Run game using test data from plan
Check:
Correct score calculation
Correct feedback messages
Secret code letters awarded properly
• Fix any bugs
• Peer review with partner
Combining Conditions
Sometimes we need to check 2 or more conditions in a program.
We use Boolean operators:
• AND → both must be TRUE
• OR → at least one must be TRUE
• NOT → flips the condition (TRUE FALSE)
Example – Treasure Chest
🪙 AND → Needs 3 coins AND 5 stars
if coins == 3 and stars == 5:
print("You can open the treasure chest")
OR → Needs 3 coins OR 5 stars
if coins == 3 or stars == 5:
print("You can open the treasure chest")
NOT → Player does NOT have fewer than 3 coins
if not coins < 3:
print("You can open the treasure chest")
World Room – Game Rules
Player visits different countries
They answer 2 questions per country
Scoring:
Both correct → +30 points & 3 secret code letters
One correct → +15 points (no letters)
Both wrong → –5 points
def worldRoom():
points = 0
correct = 0
World Room – Example Code Idea
# Question 1
# Question 2
if correct == 2:
points += 30
code = "XYZ" # letters from secret code
elif correct == 1:
points += 15
code = ""
else:
points -= 5
code = ""
return points, code
Test plan – World Room
Test No. Answers Given Expected Outcome Points Code letters
1 Both correct +30 Yes
2 One correct +15 No
3 Both wrong –5 No
points = 0
World Room –
OUTPUT "You have been transported to Portugal"
OUTPUT "What is the capital city of Portugal?"
INPUT answer1 Pseudocode
OUTPUT "What is the currency used in Portugal?"
INPUT answer2
IF answer1 == "LISBON" AND answer2 == "EURO" THEN
OUTPUT "Well done. You gained 30 points + letters from code."
points = points + 30
ELSEIF answer1 == "LISBON" OR answer2 == "EURO" THEN
OUTPUT "One answer is correct. You gained 15 points."
points = points + 15
ELSE
OUTPUT "Sorry. Both wrong. Lose 5 points."
points = points - 5
ENDIF
OUTPUT "You have been transported to..."
OUTPUT points
RETURN points
Game Flow Example (Portugal)
Start: "You have been transported to Portugal“
Question 1: Capital city?
Question 2: Currency?
Player answers:
• Both correct → +30 pts, secret code letters
• One correct → +15 pts
• Both wrong → –5 pts
Sample Run (Portugal)
You have been transported to Portugal
1. What is the capital city of Portugal? → MADRID
2. What is the currency used in Portugal? → EURO
Output: One answer is correct. You gained 15 points.
Sample Run (USA)
You have been transported to the USA
1. What is the capital city of the USA? → WASHINGTON
2. What is the currency used in the USA? → DOLLAR
Output: Well done. You gained 30 points and the letters HPY
from the secret code.
Key Concept – Boolean Operators
Boolean Operators (used in decisions):
• AND → both must be TRUE
• OR → at least one must be TRUE
• NOT → inverts the condition
Example in quiz:
if answer1 == "LISBON" and answer2 == "EURO":
# both correct
elif answer1 == "LISBON" or answer2 == "EURO":
# one correct
else:
# both wrong
World Room Requirements
Player transported to a chosen country
Asked two questions (one-word answers work best)
Scoring rules:
Both correct → +30 points & 3 secret code letters
One correct → +15 points (no letters)
Both wrong → –5 points
Task Steps
• Pick two countries and write their questions.
• Complete test plan table to predict outcomes.
• Define sub-program world() under anagram().
Add menu logic:
if room == 1:
score = anagram()
elif room == 2:
score = world()
• Save as [Link]
• Run & test using test plan
• Review with partner
Example Countries & Questions
Portugal
• Q1: Capital city? (Answer: LISBON)
• Q2: Currency? (Answer: EURO)
USA
• Q1: Capital city? (Answer: WASHINGTON)
• Q2: Currency? (Answer: DOLLAR)
(You can pick other countries with one-word answers.)
Test plan (Prediction)
(Last column “Pass/Fail” filled during real testing.)
Test # Test Data Expected Outcome Pass/Fail
1 Portugal: LISBON + EURO +30 pts, code letters ONT
2 Portugal: LISBON + Wrong +15 pts, no letters
3 Portugal: Wrong + EURO +15 pts, no letters
4 Portugal: Wrong + Wrong –5 pts
5 USA: WASHINGTON + DOLLAR +30 pts, code letters HPY
6 USA: WASHINGTON + Wrong +15 pts, no letters
7 USA: Wrong + DOLLAR +15 pts, no letters
8 USA: Wrong + Wrong –5 pts
def world():
points = 0
print("You have been transported to Portugal") Sample Code
ans1 = input("What is the capital of Portugal? ").upper() Structure
ans2 = input("What is the currency of Portugal? ").upper()
if ans1 == "LISBON" and ans2 == "EURO":
print("Well done! +30 points & letters ONT")
points += 30
elif ans1 == "LISBON" or ans2 == "EURO":
print("One answer correct. +15 points")
points += 15
else:
print("Sorry. Both wrong. -5 points")
points -= 5
# Repeat for USA (or your chosen country)
return points
Python Libraries
What is a Python library?
• A library is a collection of functions that you can use in your programs.
• Libraries let you do more things with less code.
• Python has a standard library that includes functions like:
input(), print(), str(), float(), exit()
Importing a library
Use import library_name at the start of your program.
Example:
• import random
• The random library can generate random numbers.
KEYWORD
Library: an additional set of functions that can be imported into Python.
Using functions from a library
Example: generate a number between 1 and 100:
import random
number = [Link](1, 100)
print(number)
[Link](x, y) → random integer between x and y.
Example: between 10 and 30:
[Link](10, 30)
Bonus Round – Extra Points
Purpose:
• Give players a chance to earn more points after completing their puzzle room.
• Player guesses a number between 1 and 30.
• The program generates a random number to compare with the guess.
Rules for scoring:
• Exact match: multiply score by 10
• Within 10 of random number: double the score
• Otherwise: score stays the same
Python Implementation:
1. Import the random library at the top of the program:
import random
2. Create a sub-program called bonus and pass the score:
def bonus(score):
randomNumber = [Link](1,30)
guess = int(input("Enter a number between 1 and 30 for a bonus: "))
minNum = randomNumber - 10
maxNum = randomNumber + 10
if guess == randomNumber:
score = score * 10
elif minNum < guess < maxNum:
score = score * 2
print("Random Number is", randomNumber)
print("Guess is", guess)
print("Final score is", score)
return score
3. Call the bonus sub-program at the end of your main program:
finalScore = bonus(score)
Why use a library?
• The random library is needed to generate a random number automatically.
• Without it, the program couldn’t create unpredictable bonus numbers for the player.
Part 1 – First code snippet
x = int(input("Enter the value for x: "))
y = int(input("Enter the value for y: "))
if x < y:
message = "x is less than y"
Test number x y Expected Output
elif x == y: 1 4 7 x is less than y
message = "x is the same as y" 2 7 7 x is the same as y
else:
3 11 5 x is greater than y
message = "x is greater than y"
print(message)
Explanation: The program compares x and y and prints the corresponding message.
Part 2 – Second code snippet
x = int(input("Enter the value for x: "))
y = int(input("Enter the value for y: "))
z = int(input("Enter the value for z: "))
if x < y and x < z:
message = "Hello world" Test number x y z Expected Output
elif x == y or x == z:
1 3 5 7 Hello world
message = "Good afternoon"
else:
2 7 7 99 Good afternoon
message = "Good morning" 3 12 21 0 Good morning
print(message)
Explanation:
AND requires both conditions TRUE.
OR requires at least one condition TRUE.
If neither AND nor OR conditions are true, the else block executes.
Turtle Library Commands
Command Example What it does
[Link](x) [Link](10) Sets the thickness of the line drawn, where x is the thickness.
[Link](x) [Link]("blue") Sets the color of the line drawn, where x is the color name or a hex code (e.g., #1F51FF).
[Link](x) [Link](1) Sets the speed of the turtle, with x between 1 (slow) and 10 (fast).
[Link]() [Link]() Lifts the pen so the turtle moves without drawing a line.
[Link]() [Link]() Puts the pen down so the turtle draws when it moves.
[Link](x) [Link](50) Moves the turtle forward by x steps in the direction it is facing.
[Link](x) [Link](90) Turns the turtle x degrees to the right.
[Link](x) [Link](90) Turns the turtle x degrees to the left.
Part 3 – Find values for “Hello world”
Condition: x < y AND x < z
Example values:
x = 3, y = 5, z = 10
Explanation: x is less than both y and z, so it triggers "Hello world".
1. Draw a square ([Link])
Turtle drawing exercise
import turtle
# Set up pen
[Link](3)
[Link](1)
# Draw a square
for _ in range(4):
[Link](100)
[Link](90)
[Link]()
for _ in range(4): repeats the commands 4 times (one for each side).
[Link]() ensures the window stays open after drawing.
2. Draw an equilateral triangle ([Link])
import turtle
# Set up pen
[Link](3)
[Link](1)
# Draw a triangle
for _ in range(3):
[Link](100)
[Link](120)
[Link]()
Each turn is 120° because an equilateral triangle’s internal angles are 60°, and turtle turns are external.
3. Draw multiple squares with gaps ([Link])
import turtle
# Set up pen
[Link](3)
[Link](1)
# Draw 3 squares with a gap of 50
for i in range(3):
for _ in range(4): # Draw one square
[Link](100)
[Link](90)
[Link]()
[Link](150) # Move 100 for square + 50 gap
[Link]()
[Link]()
Nested for loop: outer loop draws multiple squares, inner loop draws each square.
[Link]() and [Link]() move the turtle without drawing lines for the gap.