Games, Simulations and the Needs of Society
🎯 (CT5-EVL-01)
📌 Explore how the changing needs of society have influenced the development of games and simulations, including the impact of simulations and games on a range of industries
Games and simulations change as people’s needs change. Early games were simple. Today a game can teach a skill, train a worker or help a player relax. Each new need pushes designers to try new ideas.
A game is a program with rules, goals and a way to win or lose. A simulation is a computer model that copies how a real system behaves, so people can test ideas safely. A model is a simple picture of something real. It leaves out the details that do not matter for the question you are asking.
Games and simulations are used in many industries:
- Training. Pilots practise emergencies in a flight simulator before they fly a real plane.
- Engineering. A water tank with a wave machine lets engineers test how a boat design handles waves. They can change the design and test again without building a new boat each time.
- Health. Medical students practise on simulators before they treat real patients.
- Thinking skills. Strategy games help players plan ahead and weigh options.
Logic: Sequences, Branching and Iteration
🎯 (CT5-THI-01, CT5-OPL-01)
📌 Investigate the representation of logic when designing games and simulations, including sequences, branching and iteration, including logical and relational operators
Game designers use three basic building blocks of logic. Each one takes only a few lines of code.
- Sequence runs steps one after another, from top to bottom.
- Branching picks one path or another by checking a condition, such as “is the score 10 or more?”.
- Iteration repeats a set of steps while a condition is true, or a set number of times. Each repeat is one pass. The whole repeating structure is called a loop.
# Sequence: runs top to bottom
lives = 3
print("Lives:", lives)
# Branching: picks a path with if and else
if lives > 0:
print("Keep playing")
else:
print("Game over")
# Iteration: repeats while true
while lives > 0:
lives = lives - 1
print("Lives left:", lives)Flowchart
Branching: keep playing or end the game
The lives check from the code above, drawn with standard flowchart symbols: rounded START and END, a rectangle for each step and a diamond for the decision.
What to notice
- The diamond asks a question with a True or False answer.
- Both exits from the diamond are labelled Yes and No.
- Only one of the two boxes runs, and then the flowchart reaches END.
Try this Change lives to 0 in your head. Which box does the flowchart reach?
A condition is a question with a True or False answer. Relational operators compare two values:
| Operator | Meaning | Example |
|---|---|---|
== | equal to | score == 10 |
!= | not equal to | lives != 0 |
< | less than | health < 5 |
> | greater than | score > 100 |
<= | less than or equal to | time <= 0 |
>= | greater than or equal to | coins >= 3 |
Use logical operators to join conditions. and needs both conditions to be True. or needs at least one to be True. not turns True into False and False into True.
health = 0
has_shield = True
# Stay in the game if health is above 0 OR a shield is held
if health > 0 or has_shield:
print("Player stays in the game")
else:
print("Game over")and and or.while loop that never stops, explain why, then fix it by changing one line.Inputs, Storage and Outputs in Games
🎯 (CT5-DAT-01, CT5-THI-01)
📌 Describe inputs, storage, transmission, processes and outputs in games and/or simulations
Every game and simulation moves data through the same parts. Here they are, using a made-up maze game called Pet Rescue Maze, where the player guides a lost puppy home.
- Input is data that goes into the game. Example: the player presses the right arrow key.
- Storage is where data is kept for later. Example: the game saves the best time for each level.
- Transmission is data sent between devices, often over a network. Example: the best time is sent to a shared leaderboard on the internet.
- Process is the work the game does with the data. Example: it checks whether the puppy has hit a wall, then moves the puppy or keeps it still.
- Output is what the game shows or plays. Example: the puppy moves one square on screen, and a bark sound plays.
- Input: the player presses the up arrow.
- Process: the game checks the square above the puppy. It is open, so the puppy moves up one row.
- Output: the screen redraws the puppy one square higher.
- Storage: the game records that the puppy has taken 14 steps on this level.
Block diagram
The parts that move data in a game
Four boxes are parts of Pet Rescue Maze, and the Leaderboard is where the best time is sent. The dotted line is Transmission: a network link that carries data between devices.
What to notice
- The boxes show the parts of a game, not steps in order.
- Only the Process box sends data to the Leaderboard, over a network.
- The words under each name are examples from Pet Rescue Maze.
Try this Name one piece of data that would go in the Storage box for a game you know.
A simulation works the same way. A flight simulator takes the pilot’s control inputs, processes them with rules about how the aircraft moves, and outputs the view through the window.
Functional Requirements and Test Cases
🎯 (CT5-DPM-01, CT5-THI-01)
📌 Specify the functional requirements of a game or simulation, including stating the purpose of a system, describing use cases and developing test cases of inputs and expected outputs
A functional requirement says what the game must do. Each one describes one action or result. You can test each one by playing the game and checking what happens.
Follow these four steps to specify functional requirements:
- State the purpose. In one sentence, say why the game exists.
- Describe a use case. A use case is a short story of one player doing one task.
- List the requirements. Number each one, and start each with “The game must”.
- Write test cases. Each test has an input (what the tester does) and an expected output (what should happen).
Purpose: to let young players guide a lost puppy home through a maze.
Use case: the player starts Level 1, uses the arrow keys to guide the puppy through the maze, and reaches the gate.
- FR1: The game must move the puppy one square each time an arrow key is pressed.
- FR2: The game must stop the puppy when it reaches a wall.
- FR3: The game must show “Level complete” when the puppy reaches the gate.
| Test | Input | Expected output |
|---|---|---|
| T1 | Press the right arrow when the square to the right is open. | The puppy moves one square right. |
| T2 | Press the up arrow when a wall is above the puppy. | The puppy stays where it is. |
| T3 | Move the puppy onto the gate. | “Level complete” appears. |
Write each expected output before you run the test. If you decide the answer afterwards, you may accept a bug because it looks right.
Non-Functional Requirements for Games
🎯 (CT5-DPM-01, CT5-DES-01)
📌 Specify the non-functional requirements of a game or simulation
- Age suitability.
- Motivation or immersion.
- Visual appeal of a game world or simulation.
A non-functional requirement describes how well the game works, or what it is like to play. It does not describe one action. It is still a requirement, so it must be specific enough to check.
NESA gives three examples. Here is how each could apply to Pet Rescue Maze:
- Age suitability. The game must suit players aged 8 to 12. It must have no frightening images, and any text must be easy for that age to read.
- Motivation or immersion. Each rescued puppy must earn a reward, so players want to keep going. A short story at the start helps players feel part of the rescue.
- Visual appeal. The puppy must look different from the walls, even on a small tablet screen. Colours should be bright but easy on the eyes.
Some non-functional requirements can be tested. A tester could ask five players aged 8 to 12 to say which shape is the puppy, at a glance, without any help.
Diverse Perspectives in Game Design
🎯 (CT5-DES-01, CT5-SAF-01)
📌 Explore games and simulations considering the perspectives of diverse groups, including Aboriginal and Torres Strait Islander Peoples, culturally and linguistically diverse people, people of different ages and gender, and people with disability
- Permissions and appropriate display of cultural sites or symbols.
- Sensitivity to dress codes in cross-cultural communities.
- Use of augmentative and alternative communication (AAC).
People differ in culture, language, age, gender and ability. A good designer thinks about how each group will see and play the game. This is called considering diverse perspectives.
NESA lists several groups to consider. The examples below are made up for practice:
- Aboriginal and Torres Strait Islander Peoples. If a game uses cultural sites, symbols, art or stories, ask who owns them and whether you have permission to use them. Aboriginal and Torres Strait Islander Peoples hold rights over their cultural knowledge and creations, known as Indigenous Cultural and Intellectual Property (ICIP). Seek guidance from the community or cultural advisers. Do not guess at protocols.
- Culturally and linguistically diverse people. Think about the clothing, food and language in the game. An outfit that suits one community may be disrespectful in another. Check with people from that community.
- Different ages and genders. Avoid stereotypes, such as a girl character who only helps. Test the game with a range of players.
- People with disability. Some players use augmentative and alternative communication (AAC), such as picture boards or speech devices. A game can offer picture-based menus, adjustable text size or subtitles.
Features of Object-Oriented Languages
🎯 (CT5-OPL-01)
📌 Describe the features of an object-oriented programming language
In an object-oriented programming language (OOP for short), code is organised around objects. An object is one thing that holds its own data and can do its own actions. Think of a game character. It has a name and a score, and it can jump or collect coins.
- Class. A blueprint that describes what objects of one kind look like and what they can do.
- Object. One thing made from a class, such as one player in a game.
- Attribute. A piece of data an object holds, such as a name or a score.
- Method. An action an object can do, such as jump or add points.
class Player: # the class is the blueprint
def __init__(self, name):
self.name = name # attribute: data the object holds
self.score = 0 # attribute
def add_points(self, points): # method: an action the object can do
self.score = self.score + points
hero = Player("Ada") # create one object from the class
hero.add_points(5) # call a method on that object
print(hero.name, hero.score) # Ada 5One class can make many objects. Two players in the same game can each have their own name and score, while both use the same blueprint.
How Algorithms and AI Control Components
🎯 (CT5-OPL-01, CT5-EVL-01)
📌 Explore how predefined algorithms and artificial intelligence (AI) control computer components
An algorithm is a step-by-step procedure that solves a problem. A predefined algorithm is one that a programming language or game engine (the software a game is built with) already provides. You can use it without writing it yourself. Examples include routines that sort a list or pick a random number.
Artificial intelligence (AI) is a computer system that does tasks that would usually need human thinking, such as making a choice. In games, AI often controls characters that the player does not run.
Algorithms and AI control many parts of a game. They can decide where an enemy moves, how a ball bounces or when a sound plays. Much game AI is built from simple rules, such as this one:
# A simple rule for a game enemy
player_distance = 4 # squares away from the enemy
if player_distance < 5:
enemy_action = "chase"
else:
enemy_action = "wander"
print("Enemy will", enemy_action)Flowchart
An enemy chases or wanders
The enemy rule from the code above as a flowchart. The decision has a Yes exit and a No exit, and both paths join the same output before END.
What to notice
- The diamond holds the condition from the code: player_distance < 5.
- Each exit from the diamond is labelled Yes or No.
- Both paths meet at the same output, so the last line runs whichever way the enemy goes.
Try this Change player_distance to 6 and follow the flowchart again. Which action does the enemy take?
Each approach has effects. Predefined algorithms save time, but you cannot always see how they work inside. Simple AI rules are easy to understand and test, but players may notice that the enemy is predictable. A designer has to weigh these up.
Simulations of the Real World
🎯 (CT5-EVL-01, CT5-THI-01)
📌 Explore products that simulate the real world and how simulations are used to solve real-world problems
A simulation copies a real system so people can test ideas before using them in the real world. This can save time and money, and it can keep people safe. It is the same idea as the model you met in Part 1.
- Wave tanks. Engineers test a boat design in a water tank with a wave machine. They can see how the hull handles waves before a full-size boat is built.
- Flight simulators. Pilots practise on a copy of an aircraft’s controls and screens. They can rehearse dangerous problems that are not safe to try in a real plane.
- Travel training. A person who needs to learn a route can practise it in a simulated environment first.
- Planning models. A team can model how people move through a building, to test an exit plan without waiting for an emergency.
Simulations have limits. A simulation is only as good as its rules and data. If a rule leaves out something important, the results can mislead people.
AR, MR and VR Immersive Experiences
🎯 (CT5-DES-01, CT5-EVL-01)
📌 Explore how augmented reality (AR), mixed reality (MR) and virtual reality (VR) create immersive experiences
Immersive means you feel you are inside an experience. It comes from what you see and hear, and sometimes from touch or movement.
- Augmented reality (AR) adds computer-made images, sounds or information over the real world. A phone camera view with a virtual character on your desk is one example.
- Mixed reality (MR) mixes real and virtual objects. Virtual objects can respond to real surfaces, such as a virtual ball that bounces off a real table.
- Virtual reality (VR) places you inside a computer-made world. You usually see it through a headset, and the headset usually blocks your view of the room.
Concept diagram
From the real world to the virtual world
A spectrum, not a flowchart. Each technology sits at a point on a line that runs from the real world on the left to the virtual world on the right.
What to notice
- AR adds computer-made images on top of the real world.
- MR mixes real and virtual objects, and the virtual objects can respond to real surfaces.
- VR places you inside a computer-made world, and a headset usually blocks your view of the room.
Try this Think of a phone game that puts a character in your room. Which point on the line is it nearest to, and why?
Immersive experiences can help people. NESA gives an example. A VR game could include sign language, so a player who uses Auslan (Australian Sign Language) can see it as part of the game world.
Games Addressing Real-World Challenges
🎯 (CT5-EVL-01, CT5-SAF-01)
📌 Explore how games and simulations address environmental, lifestyle, societal and economic challenges including cyber safety
- Improved efficiencies, such as wave tanks to test boat designs.
- Impact on sustainability, such as virtual testing of engineering designs.
- Changes to privacy, such as sharing of personal data without user knowledge.
- Development of abstract reasoning with strategy games.
- Accessibility for people with disability, such as use of VR to incorporate sign language into a game.
- Travel training with simulated environments.
A challenge is a problem that affects many people or the planet. Games and simulations can help people understand a challenge, practise solutions and talk about them. Here are some examples from NESA’s list, each with a second view:
- Efficiency (economic). Testing a boat design in a wave tank can save materials and time. But the tank cannot show every real sea.
- Sustainability (environmental). Engineers can test a design virtually before they build it, which can reduce waste. But a virtual test is only as good as its inputs.
- Thinking skills (lifestyle). Strategy games build abstract reasoning, as players plan ahead and look for patterns. But a player can get very absorbed, so breaks matter.
- Accessibility (societal). A VR game can include sign language for players with disability. But the feature only helps if the game is designed for that player from the start.
- Privacy (societal). Some games share personal data without the player knowing.
- Travel training (societal). A person can practise a route in a simulated environment before they travel it. A simulated route cannot show every real hazard, so real practice is still needed.
Cyber safety means taking care with personal information online. In a game, that includes using a strong password, checking privacy settings and not sharing your address or school. If something online worries you, tell a trusted adult. The eSafety Commissioner also has guidance for young people.
Design Principles for Games
🎯 (CT5-DES-01, CT5-THI-01)
📌 Explore design principles and issues relevant to game design
A design principle is a guideline that helps a designer make good choices. Many game designers use ideas like these four:
- Clear goals. Players should know what they are trying to do, and why it matters.
- Feedback. The game should show what happened after each action, such as a sound when the puppy reaches the gate.
- Balanced challenge. A game that is too hard frustrates players. One that is too easy bores them. Players should be able to improve with practice.
- Consistent rules. If a red square is a trap once, it should be a trap every time.
Designers also face issues. One is fairness: players should not lose because of something they could not see. Another is pressure. Timers, and offers to pay for extra lives, can push players to act fast and spend money. Designers should think about who might feel that pressure, and how much.
Reviewing Mechanics, Aesthetics and Usability
🎯 (CT5-DES-01, CT5-DPM-01)
📌 Evaluate an existing game or simulation in terms of its mechanics, aesthetics and usability
To evaluate a game, look at three areas:
- Mechanics are the rules and actions. What can the player do, and what happens when they do it?
- Aesthetics are how the game looks, sounds and feels. Do the colours, music and style fit together?
- Usability is how easy the game is to use. Can a new player learn the controls quickly and find the menus?
| Area | Question to ask | Evidence from Harbour Hop (made up) |
|---|---|---|
| Mechanics | Are the rules clear, and does each action have a result? | A boat docks only at a green pier, and each dock earns points. |
| Aesthetics | Do the colours, sounds and style suit the game’s mood? | Calm blue water and soft music suit a relaxing game. |
| Usability | Can a new player learn the controls in a minute or two? | A help screen names every key, but the pause button is hidden in a sub-menu. |
Write each finding as a claim with evidence, then give a judgement. For example: “The pause button is hard to find, because it sits in a sub-menu. Move it to the main screen.”
Comparing Alternative Game Designs
🎯 (CT5-DPM-01, CT5-THI-01)
📌 Generate alternative designs and evaluate them against the requirements to select a preferred design
Good designers do not stop at their first idea. They create two or more options, check each one against the requirements, and choose the best. Here is a worked example.
- R1: The game must let the player serve one order at a time.
- R2: A round must last about five minutes.
- R3: The game must suit players aged 10 to 14.
Design A (calm). The player taps a customer, then picks the food from a menu. Customers wait patiently.
Design B (fast). Orders arrive every few seconds, and the player must serve each one in time.
| Requirement | Design A | Design B |
|---|---|---|
| R1: one order at a time | Yes | Yes |
| R2: about five minutes | Yes: the number of customers is set to fit | Yes: a timer sets the length |
| R3: suits ages 10 to 14 | Yes: low pressure | Partly: fast pressure may stress some players |
Design A meets all three requirements, and Design B meets only part of R3. Choose Design A, but note its weak point. Players may get bored, so test it with real players.
Collecting Data with Privacy in Mind
🎯 (CT5-SAF-01, CT5-DAT-02)
📌 Investigate data collection and interpretation adhering to privacy and cybersecurity principles, including specify what data is collected, who owns it, and how it will be protected
Many games collect data about players, such as scores, play times and sometimes names or email addresses. Some of this data helps the game work. Some of it is personal. A good designer decides what to collect before the game is built.
Use three questions to plan the data:
- What data is collected? List each item and say why the game needs it. Collect only what the game needs.
- Who owns it? Say who controls the data and who can decide what happens to it.
- How will it be protected? Describe the steps, such as storing it securely, limiting who can see it and deleting it when it is no longer needed.
In Australia, the Privacy Act 1988 (Cth) and the Australian Privacy Principles set rules for how many organisations collect and handle personal information. The Office of the Australian Information Commissioner (OAIC) explains these rules.
Interpreting data means working out what it tells you. Suppose a game records that many players quit at the same level. That could mean the level is too hard, or that a bug stopped progress. Check more evidence before you change the game.
Representing Data and Code
🎯 (CT5-DAT-02, CT5-OPL-01)
📌 Represent data and code to facilitate computation, including selecting appropriate data types, understanding data type limitations and structuring code systematically
A computer needs to know what kind of data it is working with. The kind of data is its data type. Choosing the right data type helps the program work correctly.
| Data type | What it holds | Game example |
|---|---|---|
| Integer | whole numbers, positive or negative | a score of 42 |
| Float | numbers with a decimal point | a speed of 2.5 |
| String | text, including digits typed as text | a player’s name |
| Boolean | only True or False | has_key = True |
Each type has limits. An integer cannot hold 2.5. A number stored as text cannot be added to another number until it is converted.
player_name = "Ada" # string (text)
score = 42 # integer (whole number)
speed = 2.5 # float (decimal number)
has_key = True # Boolean (True or False)
print("10" + "5") # joins the text: 105
print(10 + 5) # adds the numbers: 15Structuring code means organising it so it is easy to read. Group related data, give names that say what they hold (lives, not x), and keep each step in its own part of the code.
Algorithms: Flowcharts and Pseudocode
🎯 (CT5-OPL-01, CT5-COM-01)
📌 Represent algorithms using flowcharts and pseudocode
A flowchart shows an algorithm as shapes joined by arrows. Pseudocode is a short, plain-English version of code that people can read without knowing a programming language. Both are useful for planning.
- Rounded box: START and END.
- Rectangle: a process, such as “add 1 to score”.
- Parallelogram: an input or an output.
- Diamond: a decision, with a question and two labelled exits, Yes and No.
- Write the steps in pseudocode:
START
INPUT jump_pressed
INPUT on_ground
IF jump_pressed is True AND on_ground is True THEN
SET speed TO 10
ELSE
SET speed TO 0
END IF
OUTPUT speed
END- Draw the same steps as a flowchart. Start with START and two inputs. Then add a diamond with the question “jump_pressed AND on_ground?”. Its Yes exit goes to “SET speed TO 10” and its No exit goes to “SET speed TO 0”. Finish with an output and END.
Flowchart
The jump check
The jump check from the worked example above, drawn with the flowchart symbols: two inputs, one decision with Yes and No exits, one output and END.
What to notice
- The two inputs come first, so the decision can use both values.
- The diamond asks one question, jump_pressed AND on_ground.
- Each exit sets speed, and both paths then reach the same OUTPUT speed.
Try this Change on_ground to False in your head. Which speed is output?
Designing and Changing Algorithms
🎯 (CT5-OPL-01, CT5-THI-01)
📌 Design and/or modify existing algorithms for games or simulations
You do not always start from nothing. You can modify an existing algorithm, which means changing it to do something new. You can also design a new one when no existing algorithm does what you need.
Follow these four steps to modify an algorithm:
- Read the algorithm and say in one sentence what it does.
- Decide the change, and write it as a requirement.
- Find the lines that need to change. Change as few lines as you can.
- Test the new version with normal and edge inputs, and compare it with the old version.
SET score TO 0
INPUT coin_value
ADD coin_value TO score
OUTPUT scoreThe change: add a bonus of 5 points when the coin is worth 3 or more. Three lines are added and the rest stays the same.
SET score TO 0
INPUT coin_value
ADD coin_value TO score
IF coin_value >= 3 THEN
ADD 5 TO score
END IF
OUTPUT scoreDesk Checking Algorithms by Hand
🎯 (CT5-OPL-01, CT5-DPM-01)
📌 Validate algorithms with desk checking
A desk check tests an algorithm by hand. You follow each line on paper, using sample inputs, and write down each value as it changes. Following an algorithm like this to check its logic is called a trace. It can find logic errors before you write any code.
Follow these four steps:
- Choose a typical input, an edge input (exactly on a boundary, such as a coin worth 3) and a wrong input.
- Draw a trace table with one column for each variable and one for the output.
- Work through the algorithm one line at a time, filling in the table.
- Compare the final output with the expected output, which you decided before you started.
| Line | coin_value | score | Output |
|---|---|---|---|
| 1. SET score TO 0 | (not set) | 0 | (none) |
| 2. INPUT coin_value | 3 | 0 | (none) |
| 3. ADD coin_value TO score | 3 | 3 | (none) |
| 4. IF coin_value >= 3 (True) | 3 | 3 | (none) |
| 5. ADD 5 TO score | 3 | 8 | (none) |
| 6. OUTPUT score | 3 | 8 | 8 |
The output of 8 matches the expected output, so this test passes. Now try coin_value = 2. The trace should show no bonus and an output of 2.
Program-Development Support Tools
🎯 (CT5-DPM-01, CT5-OPL-01)
📌 Use program-development support tools, including Input Process Output (IPO) charts/diagrams, decision trees, flowcharts and structured English/pseudocode, in the development of a game or simulation
Good programmers plan before they type. Planning tools show what a program will do before any code exists. NESA names four: the IPO chart, the decision tree, the flowchart and structured English, which is also called pseudocode.
- IPO chart. IPO stands for input, process and output. It lists what goes in, what the program does and what comes out.
- Decision tree. It shows a choice as a question. Each possible answer is a branch that leads to the next question or to an outcome.
- Flowchart. It draws the steps as shapes joined by arrows. A rectangle is a process, a diamond is a decision, and the rounded shapes mark the start and the end.
- Pseudocode. It is a plain-English list of steps, written in a code-like way. It is not a real language, but it is easy to turn into one.
- Write the IPO chart. Inputs: the player’s guess. Processes: compare the guess with the secret number, and count the guesses. Outputs: “Too high”, “Too low” or “Correct!”, and the number of guesses.
- Draw the decision tree. The first question is: is the guess correct? If yes, say “Correct!”. If no, ask: is the guess higher than the secret number? Each answer leads to one message.
- Write the pseudocode. Put one step on each line, in order.
REPEAT
input a guess
add 1 to the number of guesses
IF guess is higher than the secret number THEN show “Too high”
ELSE IF guess is lower than the secret number THEN show “Too low”
ELSE show “Correct!”
UNTIL guess is correctDecision tree
The guessing game: which message to show
A decision tree for the guessing game. Each question is a rectangle, each branch is labelled Yes or No, and each path ends in a message.
What to notice
- The first question is about the whole guess, so it sits at the top.
- A Yes answer to the first question ends that path straight away with the message “Correct!”.
- The second question is only asked when the guess is wrong.
Try this The secret number is 7. Follow the tree for a guess of 9, then for a guess of 5. Which message does each guess give?
Branching and Iteration in Code
🎯 (CT5-OPL-01, CT5-COM-01)
📌 Create and modify algorithms and code that use branching and iteration, and represent them diagrammatically and in English
Branching means the program chooses a path. Iteration means it repeats steps. A game uses both: it checks whether the player has lives left, and it repeats the turn loop until the game ends.
In Python, an if statement is a branch. A while loop repeats code for as long as its condition is true. The % symbol gives the remainder after division, so 9 % 3 is 0 and 7 % 3 is 1.
turn = 0 # the turn counter starts at zero
lives = 3 # the player starts with 3 lives
while lives > 0: # repeat while the player has lives
turn = turn + 1
if turn % 3 == 0: # branch: every third turn is a trap
lives = lives - 1
print("Turn", turn, "trap! Lives:", lives)
else:
print("Turn", turn, "safe")
print("Game over after", turn, "turns")Turn 1 safe
Turn 2 safe
Turn 3 trap! Lives: 2
Turn 4 safe
Turn 5 safe
Turn 6 trap! Lives: 1
Turn 7 safe
Turn 8 safe
Turn 9 trap! Lives: 0
Game over after 9 turnsIn English: start with 3 lives. While lives are above 0, add 1 to the turn. Every third turn is a trap, which takes a life. Other turns are safe.
Flowchart
The turn loop: traps and safe turns
The turn loop from the code above as a flowchart. The lives decision is the loop check, and both the trap and safe paths return to it.
What to notice
- The lives decision is checked again at the start of every pass round the loop.
- Every third turn takes a life and outputs trap. Other turns output safe.
- The No exit from the lives decision is the only way out, to END.
Try this Trace the first three turns on paper. Write the output of each turn and the number of lives left after it.
and, or and not. The relational operators are ==, !=, <, >, <= and >=. A single = stores a value, while == compares two values. Write one condition that is true only when lives is above 0 and turn is at most 20.Writing Efficient Programs
🎯 (CT5-OPL-01, CT5-DAT-02)
📌 Develop an efficient computer program by selecting appropriate data types and structures
A program is efficient when it uses little time and memory to do its job. You make a program efficient by choosing the right data type for each value. A data type tells the computer what kind of value it is.
- Whole numbers, such as lives or points, use
int. - Decimals, such as speed, use
float. - Text, such as a player’s name, uses
str. - True or False values, such as game over, use
bool.
A data structure holds many values together. A list keeps items in order. A dictionary stores pairs, such as a name and a score, so you can look up a value by its key.
lives = 3 # int: a whole number
speed = 2.5 # float: a decimal
name = "Ava" # str: text
game_over = False # bool: True or False
best = {"Ava": 50, "Ben": 40} # dictionary: name to score
print(best["Ava"]) # look up one name directly
scores = [10, 20, 30] # list: ordered scores
total = sum(scores) # work out the total once, not in the loop
for s in scores:
print(s * 100 // total, "%") # use the saved total each time50
16 %
33 %
50 %The loop uses total, which was worked out once. Writing sum(scores) inside the loop would add up the list again on every pass. With three scores the difference is tiny, but with a very long list it wastes a lot of time.
int.Building Prototypes for End Users
🎯 (CT5-DES-01, CT5-COM-01)
📌 Develop prototypes to communicate design ideas and features to potential end users
A prototype is an early, rough model of a game or simulation. It shows an idea so that people can react to it before much work is done. A prototype does not need to work fully. Its job is to show what a feature is and how a player would use it.
A paper prototype is cheap and fast. Draw each screen on paper or on a card. The tester points at a button, and you move to the next card. It is like a storyboard, but the tester can try it.
A digital prototype can be a few screens made with simple code. This program prints a menu, so testers can see the layout and the words before the real game exists.
# Prototype only: a fake menu to show testers. No game logic yet.
print("=== MAIN MENU ===")
print("1. Play")
print("2. Settings")
print("3. Quit")
print("Tester: which option would you press first, and why?")Storyboard
Three paper screens for a prototype
A storyboard of a prototype. Each numbered screen is one card on paper, and a dot on a button with an arrow shows which button press opens the next screen.
What to notice
- Screen 1 is the main menu, with the same options as the code: Play, Settings and Quit.
- The arrows follow the path a tester takes through the prototype.
- Screen 3 has no arrow, because this prototype ends at the game over card.
Try this Draw a fourth screen, Settings, with an arrow from the Settings button on screen 1. Keep each screen to one idea.
- Sketch the main screens in order.
- Choose one task for a potential end user, such as starting a game.
- Ask the user to try the task while you watch. Do not help unless they are stuck for a long time.
- Write down where they hesitate, what they press and what they say.
- Change the design, then test it again.
Event Loops and Event-Driven Programming
🎯 (CT5-OPL-01, CT5-THI-01)
📌 Implement an event loop in a game or simulation using event-driven programming
Many games do not run their steps in one fixed order. They wait for things to happen, such as a key press, a mouse click or a timer tick. Each of these things is an event. The code that responds to an event is an event handler.
Event-driven programming means writing code that responds to events. The event loop is the loop that keeps taking the next event and running the right handler. A handler is a piece of code that deals with one kind of event, and each if or elif branch below is a handler. In this example, the events wait in a list. A real game fills a list like this as the player presses keys and clicks the mouse.
queue = ["key_right", "key_right", "key_space", "timer", "quit"]
x = 0 # the player's position
score = 0 # the player's score
while True: # the event loop
event = queue.pop(0) # take the oldest event
if event == "key_right":
x = x + 1
elif event == "key_space":
score = score + 10
elif event == "timer":
print("Tick. Position:", x, "Score:", score)
elif event == "quit":
print("Quitting. Final score:", score)
break # leave the loop| Event taken | x after | score after | What the program shows |
|---|---|---|---|
| key_right | 1 | 0 | Nothing |
| key_right | 2 | 0 | Nothing |
| key_space | 2 | 10 | Nothing |
| timer | 2 | 10 | Tick. Position: 2 Score: 10 |
| quit | 2 | 10 | Quitting. Final score: 10, then the loop stops |
Flowchart
The event loop of a game
The loop takes the next event, responds to it and repeats until the event is quit, drawn with standard flowchart symbols.
What to notice
- The decision has two labelled exits, Yes and No.
- The No path goes back to “get the next event”, so the loop repeats.
- Only the quit event leaves the loop. Without it, the loop would never end.
Try this Add a key_left event to the code. Which part of the flowchart changes, and which part stays the same?
Simulating a 2D or 3D Physical World
🎯 (CT5-OPL-01, CT5-THI-01)
📌 Simulate a 2D or 3D physical world using fixed time increments
A simulation is a model of something that changes over time, such as a ball falling. To simulate a 2D world, a program tracks x and y positions on the screen. A 3D world also tracks a z position, for depth.
A simulation moves forward in small, equal steps of time. This fixed amount is the time increment, or time step. Each step, the program moves each object by its speed times the time increment, in the direction it is travelling.
height = 20.0 # metres above the ground (made-up start)
speed = 0.0 # metres per second, downward
gravity = 10.0 # speed rises by 10 every second (a simple value)
dt = 0.5 # the fixed time increment, in seconds
for step in range(1, 4): # run three time steps
speed = speed + gravity * dt # update the speed first
height = height - speed * dt # then move, using the new speed
print("Step", step, "height:", height, "speed:", speed)| Time | Speed (speed + 10 × 0.5) | Height (height − speed × 0.5) |
|---|---|---|
| Start | 0.0 | 20.0 |
| Step 1 | 5.0 | 17.5 |
| Step 2 | 10.0 | 12.5 |
| Step 3 | 15.0 | 5.0 |
Timeline
A ball falling in fixed time steps
Each dot shows the ball’s height after one more time step of 0.5 seconds, using the values from the table above.
What to notice
- The dots are the same distance apart because every step lasts 0.5 seconds.
- The drop between dots grows each step (2.5 m, then 5 m, then 7.5 m), because the speed keeps rising.
- Each height is written beside its dot, and each one matches the table.
Try this Change dt to 0.25 in the code. Predict the height after Step 1 before you run it. Remember that the speed is updated first.
Earth’s gravity is about 9.8 metres per second every second, so this program uses 10 to keep the numbers simple. Keep the time increment fixed for the whole run.
The lab below uses the same rule as the program. One difference: when the ball would end up below the ground, the lab shows its height as 0 m and stops, while the program above would keep counting below zero if you let its loop run on.
Without JavaScript this tool cannot run the fall, but the rule is short. Each time step, the program first adds gravity × dt to the speed, then takes speed × dt off the height. With a start height of 20 m, gravity of 10 and dt of 0.5 s, the ball is at 17.5 m, 12.5 m and 5.0 m after steps 1 to 3. It reaches the ground at step 4, after 2.0 s.
Cell-Based 2D Environment Simulations
🎯 (CT5-OPL-01, CT5-THI-01)
📌 Simulate a 2D environment by updating the state of a cell based on its neighbour
A cell-based simulation uses a grid of squares, like graph paper. Each cell has a state, such as tree, fire or empty. Each step, every cell gets a new state based on its neighbours, the cells that touch it.
This example models fire spreading through a small patch of trees. T is a tree, F is fire and a full stop is empty ground. A tree catches fire if a neighbour above, below, left or right is burning. Fire then burns out.
def step(old):
"""Return the next grid. T = tree, F = fire, . = empty."""
new = [["."] * 3 for _ in range(3)] # start with an empty grid
for r in range(3):
for c in range(3):
if old[r][c] == "T":
new[r][c] = "T"
for nr, nc in [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]:
if 0 <= nr < 3 and 0 <= nc < 3 and old[nr][nc] == "F":
new[r][c] = "F" # a neighbour is burning
return new- Lines 1 to 3 set up a blank 3 by 3 grid of dots.
- Lines 4 and 5 visit every cell.
- Line 6 checks that the cell is a tree.
- Line 7 keeps the cell as a tree, unless line 10 changes it.
- Lines 8 and 9 check the four neighbours, skipping any off the grid.
- Line 10 sets the tree on fire.
- Line 11 gives back the new grid.
grid = [["T", "T", "."], [".", "F", "T"], ["T", ".", "T"]]
for turn in range(3):
grid = step(grid) # update every cell together
for row in grid:
print(" ".join(row))
print()T F .
. . F
T . T
F . .
. . .
T . F
. . .
. . .
T . .
Concept diagram
One step of fire spreading through trees
Two 3 by 3 grids of cells, before and after one step. Each cell takes its new state from the cells that touch it, and the arrows show the fire spreading.
What to notice
- The burning centre cell sets fire to the trees above it and to its right.
- In the new grid, the centre fire has burned out to empty ground.
- The bottom-left tree has no burning neighbour, so it survives.
Try this Draw the grid after one more step. Which trees catch fire, and which tree is still safe?
In step 1, the fire in the centre lights the trees above it and to its right. In step 2, those cells burn out and the next trees catch fire. The bottom-left tree never has a burning neighbour, so it survives.
Documenting Code for Maintenance
🎯 (CT5-COL-01, CT5-OPL-01)
📌 Develop appropriate supporting documentation in a program to ensure it is easy to read, understand and maintain
Documentation is the information that helps other people, and your future self, understand a program. To maintain a program means keeping it working, fixing faults and making changes later. A program is easy to maintain when it can be read and understood without great effort.
Four habits help most:
- A header. A few lines at the top give the program’s name, its purpose, its version and anything it needs.
- Comments. A comment starts with a hash symbol (#). Python ignores it, so comments are for people.
- A docstring. Text in triple quotes under a function’s first line explains what the function does.
- Clear names. Use
coins_collected, notc, so the reader knows what the value means.
"""Coin Collector: a made-up game. The player collects coins for points.
Version 2. Needs only Python 3."""
POINTS_PER_COIN = 10 # points for each coin collected
def coin_score(coins_collected):
"""Return the points for a number of coins collected."""
return coins_collected * POINTS_PER_COIN # multiply coins by the points
print("Score for 3 coins:", coin_score(3))Score for 3 coins: 30x = 1 # set x to 1. That repeats the code and hides the useful notes. Also update a comment when you change the code it describes. An old comment that is wrong is worse than no comment.Observing the Effects of Variables
🎯 (CT5-OPL-01, CT5-THI-01)
📌 Modify existing programming code to observe the effects of changing variables
A variable is a named box that stores a value. When you change a variable, the parts of the program that use it can change too. A good way to learn how code works is to change one thing at a time and watch the result. This is like a fair test in science.
This program works out the score for a level. The values at the top are the variables you can change.
POINTS_PER_COIN = 10 # points for each coin
BONUS = 25 # bonus for collecting every coin
coins = 4 # coins collected this level
total_coins = 4 # coins on the level
score = coins * POINTS_PER_COIN
if coins == total_coins:
score = score + BONUS
print("Final score:", score)| Change made | Final score | What it shows |
|---|---|---|
| None (original) | 65 | 40 from the coins, plus the 25 bonus |
| POINTS_PER_COIN = 20 | 105 | 4 coins × 20, plus the bonus |
| BONUS = 0 | 40 | Without the bonus, only the coins count |
| coins = 3 | 30 | No bonus, because 3 is not equal to 4 |
Observing Changes in Arrays
🎯 (CT5-OPL-01, CT5-DAT-02)
📌 Modify existing code to observe changes in an array
An array stores several values in one named place. Each value has a number called an index. In Python, a list does the job of an array. The first item has index 0, not 1, so a list of four items has indexes 0, 1, 2 and 3.
This program keeps the scores for four players in a turn-based game. Watch how the list changes after each step.
scores = [0, 0, 0, 0] # indexes 0, 1, 2 and 3
print("Start:", scores)
scores[2] = 15 # change the item at index 2 (player three)
print("After player three scores:", scores)
for i in range(4): # visit each index: 0, 1, 2, 3
scores[i] = scores[i] + 5 # add 5 to each score
print("After a bonus round:", scores)Start: [0, 0, 0, 0]
After player three scores: [0, 0, 15, 0]
After a bonus round: [5, 5, 20, 5]| Step | Code | scores |
|---|---|---|
| 1 | Start | [0, 0, 0, 0] |
| 2 | scores[2] = 15 | [0, 0, 15, 0] |
| 3 | Loop adds 5 to each item | [5, 5, 20, 5] |
scores[4] asks for a fifth item that does not exist. Python stops with an error called an IndexError.b = a does not copy a list. It gives the same list two names, so a change made through b also changes a. To make a real copy, use b = a[:] or b = list(a). Predict what the scores would show if the program used b = scores and then changed b[0]. Then test your prediction.Finding and Fixing Errors
🎯 (CT5-OPL-01, CT5-DPM-01)
📌 Identify and correct types of errors, including syntax, logical and run-time
Programs go wrong in three main ways. Each kind needs a different search.
- Syntax error. The code breaks the grammar rules of the language, such as a missing colon. Python will not run the program until you fix it.
- Run-time error. The code is legal but fails while it runs, such as dividing by zero.
- Logical error. The program runs with no error message, but the answer is wrong. These are often the hardest to find.
Here is a syntax error. The if line is missing its colon at the end.
lives = 2
if lives > 0 # SYNTAX ERROR: missing colon at the end of this line
print("Still playing")lives = 2
if lives > 0: # fixed: the colon ends the if line
print("Still playing")Here is a run-time error. The line is legal Python, but it fails when it runs, because Python cannot divide by zero.
score = 10
turns = 0
average = score / turns # RUN-TIME ERROR: Python stops here
print("Average:", average)ZeroDivisionError: division by zeroThe fix is to check the number before you divide by it.
score = 10
turns = 0
if turns > 0: # fixed: check before dividing
average = score / turns
print("Average:", average)
else:
print("No turns yet")No turns yetHere is a logical error. The program runs, but it divides the total by 2 instead of 3.
scores = [10, 20, 30]
total = 0
for s in scores:
total = total + s
average = total / 2 # LOGICAL ERROR: there are 3 scores, not 2
print("Average:", average) # prints 30.0, but the answer is 20.0try and except blocks, so the game keeps going. Should a game show a run-time error to the player, or hide it? Give one reason for your choice.Using Specialist Terminology
🎯 (CT5-COM-01)
📌 Select and use specialist terminology in context
Game developers use precise words so their teams understand each other. Using these terms in the right place shows that you know what you are talking about. Use a term in a full sentence, and check that you could explain it in plain words.
| Plain words | Specialist term | Example in a game |
|---|---|---|
| The number that counts points | Variable | score = 0 |
| A named set of steps you can call again | Function | calculate_damage(7, 3) |
| The same steps run again and again while a condition is true. | Iteration (a loop in code) | while lives > 0: |
| One round of planning, building, testing and reviewing a project. | Iteration (a project cycle) | Iteration 2: coins can be collected |
| Something that happens, such as a key press | Event | The space bar being pressed |
| Everything true about the game right now | Game state | Lives 3, score 40, level 2 |
| A small picture that moves on screen | Sprite | A coin that spins |
Managing an Iterative Game Project
🎯 (CT5-DPM-01, CT5-COL-01)
📌 Plan and manage a project to create a game and/or simulation using an iterative approach
An iterative approach builds a project in short cycles. Each cycle, called an iteration, plans a small goal, builds it, tests it and reviews it. The next iteration builds on what you learned. This is safer than planning every feature at once and hoping it all works at the end.
Plan the project as a table, with one row for each iteration. Keep each row small enough to finish, test and review.
| Iteration | Goal | How you test it | Review question |
|---|---|---|---|
| 1 | A player square moves on a grid | Press each arrow key. The square stops at the edge. | Does it move the right way? |
| 2 | Coins appear and can be collected | Move onto a coin. The score goes up by 10. | Can a player see the coins easily? |
| 3 | Lives and game over | Lose all the lives. The game ends and shows a message. | Is the message clear? |
Managing a project means planning the time, the people and the tasks, then checking progress against the plan. Keep a list of features that are not built yet. Move one into the next iteration only when the current one is finished and tested.
Building Your Preferred Design
🎯 (CT5-OPL-01, CT5-DPM-01)
📌 Implement a game or simulation using the preferred design in a general-purpose or object-oriented programming language
Your preferred design is the design you chose in the earlier parts of this topic. Implementing it means turning each rule in that design into code. A rule is something the game must do, such as ending when the lives run out.
- List the rules. Copy each rule from the design, one per line.
- Make a variable for each number. For example, the starting lives and the points for a coin.
- Code one rule at a time, then test it. Do not move on until that rule works.
# Design: 3 lives; a coin adds 10 points; a trap costs 1 life; game over at 0 lives
lives = 3
score = 0
turns = ["coin", "trap", "coin", "trap", "trap", "coin"]
for turn in turns:
if lives == 0:
break # game over: stop the loop
if turn == "coin":
score = score + 10
elif turn == "trap":
lives = lives - 1
print("Score:", score, "Lives:", lives)| Turn | Event | Lives after | Score after |
|---|---|---|---|
| 1 | coin | 3 | 10 |
| 2 | trap | 2 | 10 |
| 3 | coin | 2 | 20 |
| 4 | trap | 1 | 20 |
| 5 | trap | 0 | 20 |
| 6 | coin (the loop stops first) | 0 | 20 |
Player object would hold the lives and score as attributes, with methods such as collect_coin() and hit_trap(). Explain one advantage and one disadvantage of this compared with the loop, for a game this small.Game Interface and User Experience
🎯 (CT5-DES-01, CT5-OPL-01)
📌 Develop the UI and UX of a game, including using event-driven programming or an event loop to respond to user input
The user interface (UI) is everything the player sees and touches: buttons, menus, text, colours and where things sit on the screen. The user experience (UX) is how the player feels while using it. Is it clear? Is it fair? Is it easy to learn?
Good UX gives feedback. Feedback tells the player what happened after an action. In code, the game waits for the player’s input, such as a typed letter, and shows a message in return.
while True:
choice = input("Press s to start, h for help, q to quit: ")
if choice == "s":
print("Starting the game...")
elif choice == "h":
print("Use the arrow keys to move. Collect coins.")
elif choice == "q":
print("Thanks for playing!")
break
else:
print("That key does nothing. Try s, h or q.") # feedback for an unknown key| Player types | What the program shows |
|---|---|
| x | That key does nothing. Try s, h or q. |
| h | Use the arrow keys to move. Collect coins. |
| q | Thanks for playing! The loop stops. |
Common Game Features and State
🎯 (CT5-OPL-01, CT5-THI-01)
📌 Implement common game features, including the game state
Most games have common features: a score, lives, levels, a timer, a way to win or lose, and a pause button. These features all depend on the game state. The game state is all the information about the game at one moment, such as the score, the lives left and whether the game is over.
Keep the game state in one place. Then every part of the game reads the same values, and you do not end up with an out-of-date score in another part of the code. A dictionary is a good place for this, because each value has a name, called a key.
game = {"score": 0, "lives": 3, "level": 1, "game_over": False}
def hit_trap(state):
"""Take away one life. End the game when no lives are left."""
state["lives"] = state["lives"] - 1
if state["lives"] == 0:
state["game_over"] = True
hit_trap(game)
hit_trap(game)
print("Lives:", game["lives"], "Game over?", game["game_over"])
hit_trap(game)
print("Lives:", game["lives"], "Game over?", game["game_over"])Lives: 1 Game over? False
Lives: 0 Game over? TrueConcept diagram
The states of a game
A state diagram shows the states a game can be in. Each arrow is labelled with the event that causes the change.
What to notice
- The game is in exactly one state at a time.
- Pausing and resuming use two arrows, each with its own event.
- No arrow leaves Game over, so this diagram never moves the game out of it.
Try this Add a Restart arrow from Game over back to Playing. What event would label it?
state["lives"].Reading and Changing Existing Code
🎯 (CT5-OPL-01, CT5-THI-01)
📌 Interpret and modify existing programs (code) for games or simulations
Not every program is written from scratch. Developers often read code that someone else wrote, then change it. To interpret code is to say what it does. To modify code is to change it on purpose.
Use these four steps:
- Read the whole program first. Say what each variable stores.
- Predict the output before you run it.
- Run the program and compare the result with your prediction.
- Make one change. Predict the new result, run the program and explain any difference.
player_one = [3, 5, 2] # three dice rolls for player one
player_two = [4, 1, 6] # three dice rolls for player two
total_one = sum(player_one) # add up the rolls
total_two = sum(player_two)
if total_one > total_two:
print("Player one wins")
elif total_two > total_one:
print("Player two wins")
else:
print("Draw")The totals are 10 and 11, so the program prints “Player two wins”. Now change the last roll of player one from 2 to 3. Predict the result before you run it. The totals become 11 and 11.
Modular Programs with Functions
🎯 (CT5-OPL-01, CT5-THI-01)
📌 Design and implement modular programs (code) with functions for games
A module is a part of a program that does one job. In most programs, a function is the usual way to build a module. A function has a name. It may take parameters, which are the values it is given. It may send a value back with return.
Modular programs are easier to test, fix and reuse. You can test one function on its own, then use it again in another game.
The code below has two modules: calculate_damage and show_status. The lines that are not inside a function make up the main part of the program, which the chart calls Play game.
def calculate_damage(attack, defence):
"""Return the damage. Defence reduces the attack, but damage is never below 0."""
damage = attack - defence
if damage < 0:
damage = 0
return damage
def show_status(name, health):
print(name, "has", health, "health left")
health = 20
health = health - calculate_damage(7, 3) # 7 - 3 = 4 damage
show_status("Knight", health)
print("Damage this turn:", calculate_damage(2, 5))Knight has 16 health left
Damage this turn: 0| Call | Parameters | Value returned |
|---|---|---|
| calculate_damage(7, 3) | attack 7, defence 3 | 4 |
| calculate_damage(2, 5) | attack 2, defence 5 | 0 (-3 is changed to 0) |
Structure chart
Play game and its two modules
A structure chart shows which module is used by which. Read it from top to bottom. The small arrows show the values passed in (down) and returned (up).
What to notice
- Play game is the main part of the program, and each module below it does one job.
- Calculate damage sends a value back to Play game. Show status only displays, so nothing comes back.
- Calculate damage and Show status match the functions in the code: calculate_damage and show_status.
Try this Add a module called Show level under Play game. Decide which values go in, and whether anything comes back.
global keyword. A cleaner design passes the value in and returns the new value, as calculate_damage does. Explain why this design makes testing easier.Programming Algorithms and Data Structures
🎯 (CT5-OPL-01, CT5-DAT-02)
📌 Program selected algorithms and data structures for games or simulations
An algorithm is a set of steps that solves a problem. A data structure is a way of organising data so an algorithm can use it. The best choice depends on what the game does most often.
A high-score table needs one common algorithm: find the largest value. Start by assuming the first score is the best. Then check each of the others in turn. If one is bigger, it becomes the new best.
names = ["Ava", "Ben", "Cy", "Dee"] # parallel lists: same position, same player
scores = [120, 340, 95, 210]
best_score = scores[0] # assume the first score is the best
best_name = names[0]
for i in range(1, len(scores)): # check the rest of the list
if scores[i] > best_score:
best_score = scores[i]
best_name = names[i]
print("Top player:", best_name, "with", best_score)Top player: Ben with 340Parallel lists can get out of step. If you add a name but forget its score, the names and scores no longer match. A dictionary keeps each name and score together:
high_scores = {"Ava": 120, "Ben": 340, "Cy": 95, "Dee": 210}
print(high_scores["Ben"]) # 340sorted(scores, reverse=True) returns a new list from highest to lowest. But the names no longer line up with the sorted scores, so you would need to sort name and score pairs, or use a dictionary. Explain the trade-off between these two approaches.Testing Programs and Debugging
🎯 (CT5-DPM-01, CT5-OPL-01)
📌 Validate programs using test cases and debug a range of errors
Testing runs a program with inputs for which you already know the right answer. Debugging finds and fixes the cause of an error. A test case has an input, an expected output and an actual output. A test passes when the actual output matches the expected output.
def calculate_damage(attack, defence):
damage = attack - defence
if damage > 0: # BUG: this sets positive damage to 0
damage = 0
return damage
print(calculate_damage(7, 3)) # expected 4
print(calculate_damage(2, 5)) # expected 00
-3| Test | Input | Expected | Actual | Result |
|---|---|---|---|---|
| 1 | attack 7, defence 3 | 4 | 0 | Fail |
| 2 | attack 2, defence 5 | 0 | -3 | Fail |
To debug, print the variable just before the suspect line. Adding print("damage is", damage) before the if line shows 4, which is correct. The fault is the if line, because it sets positive damage to 0. Change > to <, then run both tests again. Both now pass.
Extending Object-Oriented Programs
🎯 (CT5-OPL-01, CT5-THI-01)
📌 Interpret and extend or implement an object-oriented program (code)
An object-oriented program is organised around objects. An object bundles data and actions together. The data is stored in attributes, and the actions are called methods. A class is the blueprint that creates objects.
In Python, __init__ sets up the starting attributes of a new object. The word self means “this object”, so self.health is the health of the object that is running the method.
class Enemy:
def __init__(self, name, health):
self.name = name # attribute: the enemy's name
self.health = health # attribute: hits the enemy can take
def take_hit(self, damage): # method: an action the enemy can do
self.health = self.health - damage
print(self.name, "now has", self.health, "health")
def is_defeated(self):
return self.health <= 0
goblin = Enemy("Goblin", 10)
troll = Enemy("Troll", 25) # a second object from the same class
goblin.take_hit(4)
print(goblin.is_defeated())
goblin.take_hit(6)
print(goblin.is_defeated())Goblin now has 6 health
False
Goblin now has 0 health
TrueClass diagram
A class and two objects made from it
A class diagram shows a class as a box in three parts: its name, its attributes and its methods. The objects made from the class sit below it.
What to notice
- The top box is the class, which is the blueprint. The boxes below are objects made from it.
- goblin and troll have the same attributes, but each holds its own values.
- Calling take_hit on the goblin changes only the goblin’s health.
Try this Add a third object called skeleton with health 8. Draw its box and its dashed arrow, then write its name and health inside the box.
This program creates two objects from one class. Each object has its own health. Hitting the goblin does not change the troll.
self, which causes an error, or using one shared variable where each object needs its own attribute.class Boss(Enemy): starts with the name, health and methods of Enemy, and it can add its own methods. Explain why inheritance saves writing the same code twice. Then name one risk of changing the parent class, which affects every class built from it.Keeping a Project Development Record
🎯 (CT5-COL-01, CT5-DPM-01)
📌 Create a record of project development demonstrating iterative design and evaluation
A project record, sometimes called a development log, is a written history of your project. It shows what you planned, what you built, what you tested, what you changed and why. It also shows your evaluation of how well each iteration met the requirements.
The record helps you because you can see your own thinking. It helps your teacher because it shows the work behind the final game. Write it as you go, not all at the end.
| Entry | What I planned | What I built | Test results | What I changed and why |
|---|---|---|---|---|
| Iteration 1 | A player square moves on a grid | Arrow keys move the square | Left and right pass. The square went off the edge: fail. | Added a check so the square stops at the edge. |
| Iteration 2 | Coins appear and can be collected | A coin list. The score rises by 10 when a coin is collected. | Coin collected: pass. Coin counted twice: fail. | Removed the coin from the list once it is collected. |
At the end of each iteration, evaluate. Compare the result with your functional requirements: does it do what they say? Compare it with your non-functional requirements: is it easy to use? Then write one sentence that says what to do next.
Peer and Self Evaluation of Projects
🎯 (CT5-DPM-01, CT5-COL-01)
📌 Evaluate their own project and that of their peers using predetermined functional and non-functional requirements
To evaluate a project, judge how well it meets its requirements. “Predetermined” means the requirements were decided before building started. You cannot change them to suit the finished game.
Use these four steps for your own project and for a peer’s:
- Copy the requirements into a table, keeping their codes such as FR1.
- Test each one and write down what you saw. This record is your evidence.
- Rate each one as met, partly met or not met.
- Write one overall judgement, with reasons.
A Year 8 group made “Recycling Rush”, a game where players drop rubbish into the correct bin. Here is part of their table.
| Requirement | Evidence from testing | Rating |
|---|---|---|
| FR1: The player must be able to drag an item into a bin. | Works with a mouse. Does not work on the touch screen. | Partly met |
| FR2: The score must go up by 1 for each correct item. | Ten items tested. The score went up by 1 each time. | Met |
| NFR1: The game must start within 5 seconds of tapping Play. | Three starts timed at 4, 6 and 5 seconds. | Partly met |
Overall, the game fully meets one requirement and partly meets two. The touch screen needs a fix before sharing, and the start time should be checked on a second computer.
When you review a peer’s project, be specific and kind. Name what works, one unmet requirement and one change. Avoid “it is bad”, which helps nobody.
Responsibilities and Cybersecurity Checks
🎯 (CT5-SAF-01, CT5-DPM-01)
📌 Evaluate whether solutions meet social, ethical and legal responsibilities and cybersecurity principles
Games affect players and makers in three ways. Social effects are about how a game affects people. Ethical choices are about what is fair, honest and respectful. Legal responsibilities are what the law requires.
Ask three questions about any game:
- Does it collect only what it needs? A quiz that asks for a full name, home address and birthday asks for far too much.
- Is it honest? It should say clearly when something costs real money.
- Does it protect accounts and chat? Passwords should be hard to guess, and chat should have a way to report unsafe messages.
The Copyright Act 1968 protects original work, such as music, artwork and code. Using someone else’s music usually needs permission or a licence that allows it. The Privacy Act 1988 (Cth) sets rules for how many organisations handle personal information.
Cybersecurity is protecting computers, software, data and networks. It uses three plain ideas. Confidentiality means only the right people see the data. Integrity means the data stays correct. Availability means the game works when people need it.
Tracing Code and Using Test Cases
🎯 (CT5-OPL-01, CT5-DPM-01)
📌 Validate algorithms and programs through tracing and test cases
To validate a program, show that it does what it should. Use tracing, which follows the code one line at a time, and test cases, which run it with chosen inputs.
Trace on paper before you run the program. This is called a desk check.
This program is for a game with three lives.
# Three lives. Each hit takes one away.
lives = 3
hits = 2
lives = lives - hits
if lives <= 0:
print("Game over")
else:
print("Lives left:", lives)Trace it with hits set to 2.
| Line | lives | hits | What happens |
|---|---|---|---|
| 2 | 3 | not set | lives starts at 3 |
| 3 | 3 | 2 | hits starts at 2 |
| 4 | 1 | 2 | 3 take away 2 leaves 1 |
| 5 | 1 | 2 | 1 is not 0 or less, so line 6 is skipped |
| 8 | 1 | 2 | Output: Lives left: 1 |
Next, write test cases. Each has an input and an expected output. Write the expected output first, so you cannot talk yourself into a wrong result.
| Test | Hits | Expected output |
|---|---|---|
| T1 | 0 | Lives left: 3 |
| T2 | 2 | Lives left: 1 |
| T3 | 3 | Game over |
Flowchart
Tracing the lives check
A flowchart of the lives code above. Each step is a rectangle, each output is a parallelogram, and the diamond is the decision.
What to notice
- The path splits only at the decision, and both exits are labelled.
- Both paths join at END, so the program finishes once.
- The steps lives = 3 and lives = lives − hits (with hits = 2) leave 1 life, the same as the trace table.
Try this Change hits to 3 and trace the flowchart again. Which message is output?
Testing Performance Against Requirements
🎯 (CT5-DPM-01, CT5-THI-01)
📌 Test and evaluate the functionality and performance of a simulation or game for specified requirements
Functionality is what the game does. Does the score change when it should? Performance is how well it does it. Does it respond quickly, and run smoothly on the computers players use? Test both against your requirements.
Here is a made-up “Canteen Queue” simulation. Join adds one student to the queue. Serve removes one from the front. The requirements are:
- FR1: Serve with an empty queue must leave the queue at 0.
- FR2: Each press of Join must add exactly one student.
- NFR1: 50 turns must take less than 10 seconds on a school laptop. This is a made-up limit.
| Test | Action | Expected | Actual | Result |
|---|---|---|---|---|
| T1 (FR1) | Press Serve with an empty queue. | Queue stays at 0. | Queue shows -1. | Fail |
| T2 (FR2) | Press Join three times. | Queue shows 3. | Queue shows 3. | Pass |
| T3 (NFR1) | Run 50 turns three times and time each run. | Each under 10 seconds. | 12 s, 11 s and 12 s. | Fail |
T1 fails because the program takes a student away even when none are waiting. The fix checks that the queue is above 0 first. T3 is slow because the screen updates three times each turn, when once is enough. After both fixes, T1 passes and T3 takes 8, 9 and 8 seconds. Always retest after a fix, and check that nothing else has broken.
Flowchart
The test cycle
The cycle repeats until the actual result matches the expected result. It uses standard flowchart symbols.
What to notice
- A failed test leads to a fix, then to another test run. The cycle only ends when the results match.
- A pass is recorded on the Yes path before the program reaches END.
- Every test starts from a written expected result, so the decision compares two values.
Try this Use this cycle for the failed test T1 in the Canteen Queue example. What would go in the “fix the fault” box?
Careers in Game and Simulation Design
🎯 (CT5-EVL-01)
📌 Explore careers in game and simulation design and development
Games and simulations need many kinds of people. Some design the rules, some write code, and others draw, make sound or test. You do not have to be a programmer to work in this field.
| Role | What the person does | Skills to start now |
|---|---|---|
| Game designer | Plans the rules, levels and goals. | Writing clear instructions. |
| Programmer | Writes the code that makes the game work. | Logic, and practice with a coding tool. |
| Artist or animator | Draws characters and makes them move. | Drawing, colour and timing. |
| Sound designer | Makes music and sound effects. | Listening closely. |
| Tester | Plays in a planned way and records faults. | Careful notes. |
| Simulation developer | Builds simulations for training, science or planning. | Maths, science and coding. |
To explore a career, look at more than one side. Ask what a normal day involves, what people enjoy, what is hard, and whether the work is done alone or in a team.
- Sam matches these interests to animator, game designer and programmer.
- Sam explores animator first and writes down a typical day, two skills and one hard part.
- Sam talks to the school careers adviser and tests a drawing skill with a free tool.
Social, Ethical and Legal Responsibilities
🎯 (CT5-SAF-01)
📌 Consider the social impacts and ethical and legal responsibilities in games or simulations
Games and simulations affect real people, so their designers have social, ethical and legal responsibilities. Social responsibilities are about how a game affects players and their communities. Ethical responsibilities are about being fair and honest, even when no law requires it. Legal responsibilities are about following the law.
If you are unsure about a rule, check the eSafety Commissioner or the Office of the Australian Information Commissioner (OAIC) websites, or ask a teacher.