Python Graphics - Student Booklet
Python Graphics - Student Booklet
Dan Collingbourne
Contents
Skills
Games Difficulty
G1. Bounce 1
G2. Dodge 1
G3. Snake 2
G4. Tic-Tac-Toe 2
G5. Jump 2
G6. Race 3
G7. Invaders 3
G8. Reversi 4
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Getting Started
Your challenge is to create some games using the Python programming language. Although it’s not
Aim: To learn how to
absolutely necessary, it will be helpful if you have some prior coding experience. We will be working create, debug and fork
through the solutions step by step but also progressing quite quickly. The idea is that you select a programs using
game to build then study the associated skills tasks before tackling it. Python (with turtle).
Note: For a gentler introduction to Python programming please see our publication ‘Python Graphics’.
Task 1 – [Link]
We’re going to create our solutions in a free website called [Link]. This site allows you to play around with bits of Python code
without the need to install applications. You may use [Link] for your solutions or you might work in a Python (with Turtle)
package installed on your school computers. The benefit of using [Link] is that you can work at home, school or anywhere else
with an internet connection.
If you are not using [Link] please jump to the next task. For those using [Link], continue below.
a. Navigate to the website [Link] and follow the instructions to set up a free account. We suggest you don’t
add personal information such as your real name. You should definitely avoid posting photographs.
b. Once logged in, click on the Templates link in the menu on the left.
d. Give your new repl the name ‘Test’ and click the Create Repl button. You will be taken to the coding page shown below.
Note: If you have problems with the [Link] template, try using ours as a starting point: [Link]
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Getting Started (page 2)
b. Lines 1 to 7 above are comments; these are ignored when the program is run. Line 9 imports the turtle module, needed for
the rest of the program to work. Line 11 creates a turtle object which will move around the output window.
Study lines 13 to 16 and see if you can work out what each line of code is doing.
Task 3 – Errors
There are two common types of errors that might occur when programming. These are called Semantic errors and Syntax errors.
a. Semantic Errors
‘Problems with the logic. The program will run without an error being reported but the results won’t be as intended.’
e.g. Remove one colour from the list. The program will still
run but the result won’t be the square we were hoping for.
b. Syntax Errors
‘Mistakes in the code; incorrect punctuation or instruction order; inconsistent use of upper-case letters. These errors can
cause the program to crash.’
e.g. Add some extra punctuation to the code such as commas or brackets.
What happens when the program is run now?
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Getting Started (page 3)
Try each of the following edits in turn, running the program and then
undoing the changes using ‘Ctrl + Z’ (‘Command + Z’ on a Mac). What
happens each time?
a. Delete line 1.
Note: We need the turtle module for our program to run.
b. Change the name of the turtle object in line 3 from ‘t’ to ‘T’.
Note: Python is case sensitive; ‘t’ and ‘T’ are different names. ‘t’ is used further down the program.
d. Try and create a pentagon similar in size and colours to ours shown on the right.
If you are using [Link], your program is saved automatically (although there is occasionally a slight
delay). If you are using another platform you will need to make sure that you can save your work.
Task 5 – Forking
To fork a program means to make a copy that you can continue to work in. Forking saves a lot of time and means that you can
try out different ideas without losing earlier ones. We will fork our last program then make further changes to the copy.
Note: If you are not using [Link] you should learn how to fork programs in your development platform.
a. Click on the hamburger menu in the top left (the three horizontal lines) and select
My Repls (as on the right).
b. Click on the hamburger menu alongside your Test repl and select Fork.
d. Make some changes to this version and then return to your list of
repls. You should now have two programs in your list. 1
e. Make sure you know how to create, edit, fork and delete your programs.
You should also be able to create folders to put your different games in. 2
Note: You may also create forks from the editing window as shown.
3
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Getting Started (page 4)
Jargon
When typing the code forward(100) we are sending the value of 100 to the method. The value of 100 is said to be the
argument. The forward method accepts this value and places it in a parameter (a variable used within the method). The effect
of the method is to move the turtle forward 100 pixels. Some methods do not take any parameters; others take one or more.
Create the program on the right, saving as “A1.6 Methods”. Run the program
and answer the questions below.
a. What name has been given to our turtle object in this program?
b. Each purple word from line 5 onwards is a method. List all the different
methods used.
c. The color method takes one parameter. What argument (i.e. colour) has been
passed to the method in this program?
e. What syntax (i.e. punctuation) is used when the arguments are word values
rather than numbers?
Edit the program, testing other arguments such as the colours gold, violet, navy, skyblue, cyan, lightgreen, chocolate, black
and gray, or the shapes circle, square, arrow or classic.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Functions & Controls
In the games created here, the movements of an object will be controlled using the keyboard or
Aim: Learn how to
mouse. Task 1 below is also very important as it shows how to set up and call functions, used in
control the turtle using
all but the simplest of Python programs. the keyboard and
mouse.
a. Functions are separate sections of programming code that perform a specific task. Three functions have been defined at
the start of the program above. One of these is called go_forward. What are the other two called?
b. What name is given to the first Turtle object created in this program?
c. The Screen object must be defined before our keyboard commands can be picked up. What name is given to this object
and on which line is it defined?
d. The listen method tells the program to expect user input (the program is waiting for events). On which line is this
initiated?
e. The program is waiting for events such as the keyboard strokes p, w and q. On which three lines are these events set up?
f. The go_forward function is called in line 23. What event causes this to happen?
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Functions & Controls (page 2)
The arrow keys have the names ‘Up’, ‘Down’, ‘Left’ and ‘Right’. 270°
a. Fork the previous program and save the copy as “A2.2 Arrow Keys”.
b. Edit the program so that it declares four functions for the four
different directions. Draw some patterns.
Note: The ‘ondrag’ event works in the same way as the onclick event, sending the current coordinates of the mouse to the
function as arguments.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Playing Areas
Many simple games have action that takes place inside an enclosed space. Even if you plan to use
Aim: To create a
the whole screen you may still need to prevent things moving off the visible area. confined space for our
Note: Screen sizes differ. If our playing spaces don’t fit your own screen then either try different zoom games.
levels in the browser (‘Ctrl/Command + Scroll’) or adapt the programs to fit your own screen.
Add the code below to create a dashed vertical line down the middle of
the playing space. It uses a for loop to add a short line and space 25
times. Be careful with the indentations; they are vital in Python.
Add further code to create a similar dashed horizontal line across the middle of the playing space.
Task 2 – Scope
Scope is the mechanism by which the access to data, variables and functions is
controlled. If an object is defined inside a function then it is only available for
use within that function. If it is defined outside all the functions then it is
available everywhere (i.e. it is global).
In the edit on the right, we have removed the indentation from the hideturtle
line. Try and explain why this creates an error.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Playing Areas (page 2)
a. Fork your program and save the new copy as “A3.3 Border Control”. Delete the sections of code that create the dashed
lines; they are not needed.
b. In a second browser window, find your solution to the activity “A2.2 Arrow Keys” and copy the code across to your new
program. Delete the duplicate lines which import the turtle module and define the Screen object a second time. You
may also delete any excess comments.
Note: We are using a second turtle object for our player. This one is called ‘scribe’.
c. Test the program. You should have a playing area and a turtle controlled with the arrow
keys. At this point, the boundaries have no actual effect on the turtle.
d. Edit the go_up function so that the turtle cannot leave the top of the playing area. Find the y coordinate of the current
position and use an if statement to limit the movement upwards.
-270°
Task 4 – Bouncing Ball -225° 90° -315°
135° 45°
You may want an object to bounce around within your playing area. Your
object can easily be nudged forward endlessly using an infinite loop. Getting
it to bounce off walls at the correct angle is the difficult part.
-180° 180° 0°
If bouncing off the left or right walls: angle out = 180 - angle in
If bouncing off the top or bottom walls: angle out = - angle in
Have a go at creating a ball that bounces around inside your playing area.
You may start the ball off at a fixed angle of 30°. Fork a suitable program
from earlier and save the new version as “A3.4 Bouncing Ball”. Part of our
solution is shown on the right (we have previously set the angle variable to
30). You should test your program with different starting angles.
Note: The while loop will run indefinitely so stop the program using the Stop
button. You could set a condition that is always true (e.g. ‘while 1==1’)
but the same thing has been achieved here using the code ‘while True’.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Counting & Displays
Many games have some sort of scoring or timing mechanism. This data may be displayed on the
Aim: To create
screen throughout play. Also, you may need to generate some random events such as the direction
random numbers, set
of a ball’s movement at the start of play. If you have chosen a game that requires any of these up loops and display a
functions then work through the set of tasks below. timer.
Similarly, a random angle between 0 and 359 degrees can be created using
[Link](0, 359). We will create a turtle and send it off in a random
direction from the centre.
a. Create the program on the right, named “A4.1 Random”. This time,
our turtle is called Jill.
Note: Before you can use the random function, you must import the
random module. This code has been placed at the start of our
program.
Task 2 – Counting
You may want to count and display the number of times something
specific happens. As an example, we will display the number of lines
created on the screen in our last program.
a. Fork the last program and name the new copy “A4.2 Counting”.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Counting & Displays (page 2)
e. Find out what happens if you omit line 26 and run the program.
a. Fork the program and name the new copy “A4.3 Numbers to String”.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Counting & Displays (page 3)
Note 2: We could add further conditions to our program using the ‘elif’ statement. The syntax would be “if… elif… elif…
else…”.
Task 5 – Timers
a. Fork your last program and save the copy as “A4.5 Timers”.
c. Import the time module at the start of the program. This is needed
for timing applications.
d. Use the code [Link]() to find the exact time when the program
is run.
Note: The time is actually the number of seconds since 1st January
1970 but you don’t need to worry about this.
Extension
The problem with the program above is that it only updates the time displayed at the end of each loop. If this period is
always much less than a second then it is fine. However, if we are relying on an action that doesn’t take place very often
then the timer won’t progress smoothly. Do some research online and see if you can find a solution to this problem.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Inputs & Data Validation
You may want to accept information from the user such as their name or a selected game level.
Aim: To accept user
Once inputted, this information should be validated to see if it will work with your program. input and validate it
If you have chosen a game that requires these tools then work through the activities below. before use.
Task 1 – Inputs
a. Create a new program called “A5.1 Inputs”
and copy the code on the right. It should ask
the user for the number of lines to create
and then draw these as on a clockface.
The problem is to do with data types. Our variable, linesChoice, collects the input and uses this in the for loop; it is the
number of times the loop should run. The value used in the loop must be an integer. However, all information inputted
through the console is considered to be text (i.e. strings). This is the case even if you enter a number such as 5.
Before we can use the input, we must convert the string “5” into the integer 5.
This is achieved using the int function, as below.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Inputs & Data Validation (page 2)
Task 3 – Validation
The last solution was OK but (as you may have worked out) entering anything other than a number crashes the program.
Below is the result of entering the text “one”.
A better solution is to start off assuming that the data is not valid and then repeat the loop until valid data is entered.
a. Fork the last program and name the copy “A5.3 Validation”.
b. Add the code below and test your program with text and numbers under 1, above 12 and then between 1 and 12.
Important: Be extra careful with the indents. There are 3 different levels in this code, achieved using either 1, 2 or 3 tab
spaces (or 2, 4 or 6 normal spaces).
Fail 1
If the input creates an error then the
program continues to cycle the 1st inner
loop.
Pass 1
If the input doesn’t create an error then it
moves on to the next test.
Fail 2
If the input isn’t between 1 and 12 then
the program continues to cycle the inner
loop.
Pass 2
If the conditions are met, the is_validated
variable is set to True and the flow
escapes the main loop.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Lists
A list is an ordered set of data. You can create lists of text strings and numbers but the type used
Aim: To create a list
most in our games is a list of turtles. Any game with several similar objects moving on a screen at and access its
one time will probably use a list of turtles. If you have chosen a game such as this then work through elements.
the activities below.
The following line of code will create a list called my_list. In this case, the list contains integers.
The list has four items known as elements. Each list item can be referred to by its index. Indexes start at 0.
Many games will use a list of turtles. These could be segments of a snake, space invaders or discs in a game of Reversi. A list of
turtles could be set up and accessed using the code below:
However, a better method of achieving this is often to create an empty list and then add turtles to it using the append() method:
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Lists (page 2)
Task 2 – Turtles
The program below creates 5 turtles of different colours and sends
them off in 5 specific directions. Type up the program and name it
“A6.2 Turtles”. Answer the questions below:
• Place the action inside a defined area (see A3. Playing Areas).
• Allow the user to enter the number of turtles to create through the
console e.g. up to 10 (see A5. Inputs & Data Validation).
• Send the turtles off in random directions (see A4. Counting & Displays).
• Make the turtles bounce off the walls (see A3. Playing Areas).
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Bounce
a. Fork your solution to “A3.3 Bouncing Ball” from the Playing Areas
tasks, naming the new copy “G1 Bounce 1”.
b. Change the name of the turtle from scribe to ball in all instances.
Note: You may adjust the argument in the forward method to make
the ball travel faster or slower.
c. Create another turtle called bat. For now, this can be a simple black
square placed just above the bottom border, in the centre horizontally.
d. Add functions to control the left and right movements of the bat,
triggered by pressing the left and right arrow keys. This code can be
typed or copied from your solution to “A2.2 Arrow Keys” (you could
open this program in a second browser window). Remember to
change the name of your turtle to bat in the new code.
f. For the sake of tidiness, move the definitions of the objects window,
bat, ball and angle into the top section.
Note: The turtle that sets up the boundaries is only needed within
the setup function, so it can be defined within the function
itself. It is a local object.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Bounce (page 2)
g. Still tidying up, move the code where the bat and ball are
designed into two new functions. Ours are called design_bat and
design_ball, as on the right.
i. Change the design_ball function so that the pen is actually lifted at the end.
This way, the ball will not leave a trace as it moves.
j. You’ll notice that the bat can travel outside the boundaries. Add some
restrictions to the go_left and go_right functions to limit the bat’s movement.
a. The ball should bounce off the bat. We can use the distance
method to find the distance between the bat and the ball in
pixels. If the distance is less than 20 then bounce the ball
back up. This condition can be added to your while loop.
If the ball hits the bottom boundary, simply hide it for now
(you may do something better later if you wish). Use the
break statement to leave the while loop and end the game.
d. Run the program several times. How many times can you hit
the ball in a single game? What are the issues with the game?
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Bounce (page 3)
Fork the program and name the copy “G1 Bounce 2”.
Try and improve the playability of the game yourself before working through our adaptations below.
b. The sticky bat issue is due to the fact that we are deflecting the
ball if the distance from the bat is less than 20 pixels. However, in
our program we are still only moving the ball forwards 5 pixels at
a time so it is having trouble escaping the bat.
Giving the ball an extra nudge after setting the new direction
should help it escape. It should also prevent it from moving
downwards.
c. Making the bat larger is actually an issue in [Link]. If you are using a
different platform then you may be able to play around with the shapesize
method.
Unfortunately, this method isn’t supported in [Link] but you may instead
register and use a shape as below.
Note: If you make the bat longer, you might notice the ball
seems to pass through the edges of it. This is because the
distance between bat and ball is measured from the
centre (or location) of these two objects. Experimenting
with the distance method and other variables should help
you find a good compromise.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Bounce (page 4)
Start the ball off at a random angle upwards. Considering Python uses the angles as shown 135° 45°
on the right, launching the ball between 45° and 135° should work well to begin with.
180° 0°
a. If you haven’t already, work through the first section of the Counting & Displays resource
looking at random numbers. 225° 315°
270°
b. Import the random module and set the angle variable to a random number between 45 and 135
(in place of 0). Add a print statement so that you can view the generated angle in the console.
c. Run the game a few times. You should notice that angles close to 90°
result in a very boring game. How could this be improved? Have a go at
programming this yourself then view our solutions below.
Our solution generates a first random number between 0 and 30 and a second random number of either 0 or 1. The
first number is then added to either the 30 or 120 depending on the second random number (i.e. if random2 = 0 then
add to 30, else add to 120). Place this code in the main body of the program before it is required by the ball design.
Unless you have changed things around, the following will occur:
1. The angle variable is declared as 0 at the start of the program (i.e. globally).
2. The value of the angle is then changed within a function (i.e. locally).
3. Finally, we want to use the new angle outside the function (i.e. globally).
The problem is that we are trying to change a global variable from inside a function. The prevention of this is part of a
protection mechanism called scope. One solution is to state that you are working with the global variable before trying
to change it. This can be achieved using the code global angle at the start of the function.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Bounce (page 5)
Hit Count
Add a counter that displays the number of times you have hit the ball.
a. Open a second browser window (if using [Link]) and find the solution to
“A4.2 Counting” from the Counting and Displays resource.
b. Copy the section of code that creates the display to your Bounce program. To
improve the tidiness, place this code in a function and call it along with the others.
e. Add 1 to the number of hits each time the ball is hit and rewrite the display.
Levels
Increase the difficulty of the game as time progresses. There are lots of ways of achieving
this but we have chosen to increase the speed of the ball every 5 hits.
a. Create a function to set up the level display, starting off with the text “L1”.
b. Set up 3 more variables to hold the current level, the number of hits since the
level changed and the distance the ball should move each step.
d. Set up the rest of your program to track the variables, reset them to 0 when
required and to display the current level. You will need the str function when
concatenating for your display.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Bounce (page 6)
c. Fork your last solution and name the copy “G1 Breakout”.
d. Have a go at building a game like this. The following tips should help.
• You will probably need a list of turtles for the blocks. Make sure you are familiar with how lists work in Python (look
back through the introductory resource about lists). You might decide to return to this game after completing later,
more difficult projects (the Space Invaders game uses similar ideas).
• Create the turtles using a loop within a loop, moving across the screen a fixed number of steps and then dropping
down a line when you reach the end. Colours could be stored in a second list then accessed one at a time.
• Allow some control over the direction of the bounce depending on the movement of the bat.
• Add scoring and some type of ending to the game. You might introduce levels.
• Look online for help with other methods. [Link] is very useful.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Dodge
a. Fork your solution to “A3.1 Playing Space” from the Playing Areas tasks, naming the new copy “G2 Dodge 1”.
b. Remove the sections of code that create the dashed lines. These are not needed.
c. Define another turtle called ship. This line of code can be placed at
the top of the program so that the ship object can be accessed
everywhere (i.e. it is global).
d. For now, design the ship as a simple black square placed inside the left
border, in the middle vertically. Place this code in its own function.
e. Call the function after you have set up the playing area.
f. Add functions to control the up and down movements, triggered by pressing the
up and down arrow keys. This code can be typed or copied from your solution to
“A2.2 Arrow Keys” (this program could be opened in a second browser window).
Remember to change the name of your turtle to ship in the new code.
Note: Our partially obscured solution is shown on the next page but try this coding for yourself first.
a. If you haven’t already, work through the first section of the Counting & Displays
resource looking at random numbers. Import the random module into your program.
b. At the end of your code, define an empty list for your turtles called turtle_list.
d. Move each new turtle to a random position just inside the right border.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Dodge (page 2)
1. We have used the variable nexti for the next index in the list.
Why is this equal to the number of turtles?
2. Does the program stop running when 20 turtles have been
created?
3. We want the turtles to be formed instantly on the right-hand
side without leaving a trace from the centre. How could this be
achieved?
4. We then want the turtles to gradually move to the left. How
could this be programmed?
a. Creating the turtles instantly without trace is simple. Just use the
speed 0 and lift the pen up. We might need to slow things down
again later.
1. What code adds 1 to the turtle count after a new one has been
created?
2. When moving through the list of turtles, why have we used the
code range(number_of_turtles-1)?
3. How could you hide the turtles when they reach the lefthand wall?
4. How do you think we’ll test to see if our ship has been hit by a
projectile?
Have a go at adding the programming for the last two questions before continuing.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Dodge (page 3)
Test your program, making any changes you think are necessary get it working more smoothly (we will look at some of the
problems in the next task).
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Dodge (page 4)
We found the game worked reasonably well at this point, although we made the following observations:
• The ship could move off the top and bottom of the screen;
• There was a flicker in the centre of the screen when each turtle was created;
• The game was too easy;
Fork the program, name the copy “G2 Dodge 2” and have a go at solving some of these problems yourself. If you need help
then work through the rest of this section.
c. How difficult your game is depends on the platform you are using (i.e. the [Link] website or some other installation).
Even if you are using [Link], there might be huge differences in the speed of movement depending on the template you
started with. Finally, turning off the animation using the tracer method could speed things up tremendously.
The ideas below will help you control how difficult the game is.
• Try changing speed with which the projectiles move across the
screen by editing the forward jump size.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Dodge (page 5)
d. The out of range error is caused by our for loop. The following series of events might occur:
One solution is to assume that one turtle (or perhaps 2 or 3, depending on your other settings) are going to be removed
each time the for loop runs and therefore set a smaller range to begin with. This will have consequences to the movement
of some projectiles but this will be difficult to spot when playing. Try subtracting 2 or 3 from the number_of_turtles
variable when setting up the for loop.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Dodge (page 6)
Start Display
Creating a Start event is a little more difficult. The main program should be
placed inside a function so that it can be called later (this is good practice
anyway).
a. Create a function for your main program. Every line moved into the
function will need one further indent.
Note: You will need to define the turtle globally as it will be needed from
other functions.
d. Your actual program should now set up the page and run the start function.
Timer
Add a timer to your game. If you haven’t already, look through
the resource Counting & Displays and reuse the code from that
program.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Dodge (page 7)
2D Movement
Allow the ship some limited movement to the left and right.
Ship Shape
Design a new ship using code similar to ours below.
• The coordinates are listed as (y,x) pairs with (0,0) being the object’s location.
• When designing a ship, aim to have the (0,0) point roughly in the centre
of your shape. You may otherwise get some strange effects.
Note: Different Python installations work in different ways. If your ship appears upside-down then
reverse the y axis coordinates (turn positive into negative and vice versa).
Levels
Increase the difficulty of the game as time progresses. There are lots of ways of achieving this but we have chosen to increase
the speed (or the jump size) of the projectiles every 10 seconds. You might instead change their direction slightly.
a. Create a function to set up the level display, starting off with the text “L1”.
e. The last problem we dealt with was that with the projectiles making bigger jumps, they could jump straight over the ship.
We solved this problem by
measuring the x and y
distances between projectile
and ship then creating our
own test for the distance
between them.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Dodge (page 8)
When building your game, break the development down into a series of small steps to take. Although this isn’t really how you
would develop a game professionally, it’s a good way for a beginner to learn. You will often find that the solutions are easier
to find than you thought they might be.
Notes:
• If you are using replit, you won’t be able to import images to use in your game. You will therefore need to
create shapes yourself to use. Keep things visually simple and concentrate on the functionality.
• Try and make a scrolling game infinite by generating objects randomly rather than designing them precisely.
• The Defender game has a spaceship that can shoot a laser. Our Space Invaders game will help with this
functionality.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Snake
a. Fork your solution to “A3.1 Playing Space” from the Playing Areas tasks, naming the new copy “G3 Snake 1”.
Note: At the time of writing, this game had serious issues when starting with the [Link] template. We suggest you
fork our plain template and copy your code into this. [Link]
b. Remove the sections of code that create the dashed lines. These are not needed.
c. We will look at our playing space as a set of small squares, each 20 x 20 pixels. The turtle head will move from square to
square and the body will follow.
Edit your playing space so that the x values now range from -310 to 310 and the y values from -270 to 270. The centres of
the squares have coordinates such as those shown below. You might need to adapt this design for a smaller screen size.
x -300 x -280 x -260 x -240 x -220 x -200 x -180 x -160 x -140 x -120 x -100 x -80 x -60
y 260 y 260 y 260 y 260 y 260 y 260 y 260 y 260 y 260 y 260 y 260 y 260 y 260
Corner x -300 x -280 x -260 x -240 x -220 x -200 x -180 x -160 x -140 x -120 x -100 x -80 x -60
x -310, y 270 y 240 y 240 y 240 y 240 y 240 y 240 y 240 y 240 y 240 y 240 y 240 y 240 y 240
x -300 x -280 x -260 x -240 x -220 x -200 x -180 x -160 x -140 x -120 x -100 x -80 x -60
y 220 y 220 y 220 y 220 y 220 y 220 y 220 y 220 y 220 y 220 y 220 y 220 y 220
a. Define another turtle called head. This line of code can be placed at
the top of the program so that the object can be accessed everywhere
(i.e. it is global).
b. Design the snake as a simple square of your chosen colour. By default, it will be
positioned in the centre of the screen. Place this code in its own function.
c. Call the function after you have set up the playing area.
d. Add functions to control the up, down, left and right movements,
triggered by pressing the arrow keys. You only need to set the
direction as the snake will be moving continuously.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Snake (page 2)
a. Create a while loop which moves your snake forward 20 pixels at a time (so that it
jumps between our grid squares). This code can be placed at the end of your program
for now but might be moved into a function later.
b. Use the sleep method to slow the snake down, where the
argument is a number of seconds. Test different values
for the delay. You will need to import the time module
before using the sleep method.
c. Check that the snake can travel just inside all edges. If so,
the grid is set up correctly.
Note: The snake can still pass over the boundaries at this point.
Adding Food
The snake needs to eat; and when it does it grows in length. The food will be placed in random locations on the grid. Our
grid has squares with centres ranging from -300 to 300 horizontally and -260 to 260 vertically. Each square is 20 x 20 pixels.
• Generate an x coordinate from the range -300, -280, … 300 = a random integer -15 to 15 multiplied by 20.
• Generate a y coordinate from the range -260, -240, … 260 = a random integer -13 to 13 multiplied by 20.
a. Look back at the first section of the Counting & Displays resource about random
numbers. Import the random module at the start of your program.
b. Create another turtle called food. This can also be defined at the start of your
program so that it is a global object, available anywhere.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Snake (page 3)
The Tail
The snake’s tail will be a set of turtles stored in a list. Each turtle will be moved
forward in turn.
If we move the head before the tail segments, then this sort of thing will happen.
We therefore move the segments from the end of the tail into the location of the one in front. The snake will appear to
contract then lengthen again repeatedly.
1. Count the segments in the tail (there are 4 in the above example). Subtract one from this = 3. We will use this number.
• Move tail segment with index 3 to the position occupied by tail segment with index 2.
• Move tail segment with index 2 to the position occupied by tail segment with index 1.
• Move tail segment with index 1 to the position occupied by tail segment with index 0.
2. Move tail segment with index 0 to the position occupied by the head.
Have a go at programming this yourself before viewing our solution. You will need to create a list for the tail and add a turtle
to it each time food is eaten. You should then think about how the segments can be moved forward.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Snake (page 4)
b. Create a new tail segment by defining a turtle and adding it to the list, as is
partially shown on the right.
Test your program. It should be a good start but it will only work
for one tail segment at the moment.
d. Before you move the first segment, you will need to move
any other tail segments. The code for this is a little tricky
(although if you have worked out a solution yourself then
use that).
1. The starting number (in this case, the length of the tail at any point minus one i.e. the highest index in the tail list).
2. The finishing number, although the loop stops without using this last one (in this case set as 0 so we finish on index 1).
3. The number of steps to take in the count each time the loop runs (in this case, -1).
In our previous example the snake’s tail is 4 segments long. The range created for the loop will be 3, 2, 1. We move the
segment with index 3 to the position of the segment with index 2 etc.
Add comments explaining what each section of code is doing. Single line comments start with the hash symbol.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Snake (page 5)
The basic game is just about working but we noted the following issues:
• Sometimes the snake would pass right over the food without eating it;
• New segments appear in the centre of the screen before being repositioned at the end of the snake;
• The snake can turn back on itself (i.e. when moving to the right it can turn back to the left). When there are a
couple of segments in the tail this means instant death;
Fork the program and name the copy “G3 Snake 2”. Have a go at solving some of these problems yourself. If you need help,
work through our hints below.
b. The fact that the new segments seem to be stuck in the centre
of the screen for a second is actually a symptom of the delay
that occurs afterwards. However, we can solve this particular
problem by moving the turtle temporarily offscreen after it is
created.
c. The snake slows down as it increases in length. This is because the program is having to carry out more turtle movements
as the number of segments increases. One solution is to reduce the sleep value each time food is eaten.
Create a variable named delay and set it with an initial value of 0.1. Use
the delay variable as the argument in the sleep method.
Note: You could use the shorthand delay -= 0.01 to decrease the value
instead.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Snake (page 6)
d. We will now look at how to prevent the snake turning back on itself.
Adapt the go_left function so that the turtle turns left only if the
heading variable isn’t holding a value of right. The symbol != is the
comparison operator meaning not equal to. Update the heading
variable to reflect the change in direction.
Note: You must state that you are using the global ‘heading’ variable
because you want to change the value of this global variable
from inside a function. What happens if this line is omitted?
e. The game suddenly stopping is a strange one. Our guess was that this was caused by the first body section moving into
the head’s location and the program picking it up. This shouldn’t in theory happen if you work through the code but
sometimes one process can overtake another when a program is running.
We’ll leave this solution for you to find if it is an issue. You can see how we achieved it in our completed program.
Scoring
Basic scoring is easy in this game. Simply start at 0 and add 1
every time a piece of food is eaten.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Snake (page 7)
Start Display
Creating a Start event is a little more difficult. The main program should be placed inside a function so that it can be called
later (this is good practice anyway).
a. Create a function for your main program. Each line moved into the
function will need one further indent. The heading variable must still
be declared outside this function as it is used in the directional code
(the other variables are all exclusively used within this new function).
• Add temporary obstacles to avoid. Make sure they are not on top of the food.
• Create an alternative scoring system that involves calculations based on the time the game has been running.
• Improve the graphics. Create a snake head and maybe a special last tail segment.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Tic-Tac-Toe
c. Write two more functions, one to create a naught and one to create a cross. For
now, position these graphics in the centre of the top left and top right squares (as we
have done). Make each shape 50 pixels high and 50 pixels wide.
Note: Use the ‘circle’ function to create the naught. The argument in the brackets
is the radius of the circle that will be created.
For testing purposes, call each function from your main program. These calls can be removed when you are happy with
how the functions work.
The next step is to position the naughts and crosses in the grid after a click of the mouse. Think about how this might be
achieved yourself before looking at our tips on the next page.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Tic-Tac-Toe (page 2)
Mouse Clicks
Look back at the Mouse Clicks task from the Functions & Controls resource. The onclick
event shown on the right calls the clicking function, sending the x and y coordinates of the
mouse pointer as arguments.
a. Add a global variable to store the player whose turn it is (i.e. naughts or crosses).
We will start this off with the value naughts for now but this can be changed later.
The value will switch between naughts and crosses during gameplay.
b. Tell your window to listen for mouse clicks and run the clicking function when it picks
up an event.
c. To start off with, your clicking function can simply draw the naught and then
the cross when you click anywhere on the screen. Next, we will try and
pinpoint the clicks so that we know which square to create the graphic in.
Make sure you test each piece of code added.
When the player clicks on the screen, the x and y coordinates of the
click are sent to the clicking function. If this function rounds off each
coordinate to the nearest 100 pixels then we should know which
square has been clicked in.
The code below rounds off each of the coordinates and then sends
these rounded values to the draw_naught function as arguments.
The print statement has been used so that we can check the rounded
values in the console.
Complete this coding and then do the same for the draw_crosses
function. More adjustments will be needed to place the cross in
the centre of the clicked square.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Tic-Tac-Toe (page 3)
G D E F
A Box 1 Box 2 Box 3
Box 1 Box 2 Box 3
B Box 4 Box 5 A
C Box 7
F
Box 7 Box 8 Box 9
G Box 5 C
H
H
c. To test that your code works so far, print the winner of the
game to the console if the top line is 000 or XXX.
The if statement on the right says ‘if box 1 is the same as box 2,
and this is the same as box 3, and this is not equal to 0’.
Note: Remember to end the last line with a colon rather than an ‘or \’.
e. Test that your game works and that the winner is displayed
correctly on all 8 possible winning lines. Add comments to
explain what each section of code is doing.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Tic-Tac-Toe (page 4)
The game could do with more functionality but we will fix up some problems
before going further. These are the things we noticed:
• A player can click outside the playing space and create a graphic there;
• You can carry on clicking after the game is won (and even declare a
different winner).
Fork the program and name the copy “G4 TicTacToe 2”. Try
and solve the problems yourself before working through our
hints below.
b. A similar technique can stop further clicks when the game is over.
Although there are many ways of doing this, the easiest is probably to
set a global variable with a value of 0.
Finally, use the return statement to escape the clicking function if the
value of the game_over variable equals 1.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Tic-Tac-Toe (page 5)
Start Display
a. Create a function which displays a start message. Choose a key to run a start_game
function when it is pressed.
b. Clear the start display when the game begins then listen for
the keyboard stokes.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Jump
a. Fork your solution to “A3.1 Playing Space” from the Playing Areas tasks, naming the new copy “G5 Jump 1”. Remove
the sections of code that create the dashed lines. These are not needed.
Note: At the time of writing, this game had serious issues when starting with the [Link] template. We suggest you
fork our plain template and copy your code into this. [Link]
b. Design a player for your game. Ours is shown on the right but you should create
your own design. Make your player 40 pixels high, starting with 0 at the bottom
so that it stands on platforms. Horizontally, it should be roughly centred on 0
using positive and negative values along the x axis. It can be wider than ours if
you wish. It doesn’t need to be symmetrical.
You may generate coordinates for the vertices in any way you like; we designed
ours using the tools in Microsoft Word:
1. Open a new Word document and select ‘Layout / Align / View Gridlines’.
2. Click ‘Layout / Align / Grid Settings’ and choose a horizontal
and vertical spacing of 1cm. Click OK.
3. Select ‘Insert / Shapes / Freeform: Shape’.
4. Click on the grid axes repeatedly to create the shape. Finish
with a double click.
5. To edit the shape, right click on it and select Edit Points. You may
then move the vertices. You may also add and delete points.
c. Once your coordinate pairs are ready, create your player using a
function such as ours on the right. The coordinates are listed in
turn using the form (y,x). Let the coordinates run onto new lines
as you type rather than forcing new lines. The player turtle can
be defined at the start of the program and the function called
from the main program. Position your player at the bottom
centre of the playing area.
Note: Different Python installations work in different ways. If your player appears upside-down then reverse the y axis
coordinates (turn positive into negative and vice versa).
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 2)
Use functions like ours on the right to find the current position and then
move the player 10 pixels if within bounds. You will also need to set up
the onkey functions and tell your window to listen for clicks.
Jumping
The player will be able to jump to the left or right, depending on the direction
of the last movement. Each jump will consist of a number of small steps.
Look at the jump created on the right where each square on the grid is
10 x 10 pixels.
a. The code on the right creates a jump. We have used the spacebar as the
jump key. Make sure you understand how the code works or use your own.
b. The jump should be either to the left or right depending on the player’s last move.
Introduce a global variable called direction that logs the last move (ours is defined
as above).
c. Set the variable as either right or left in the relevant functions. Note that before
trying to change a global variable from within a function, we must tell the program
that it is the global variable we are referring to.
d. Edit the jump function so that the player jumps left or right depending on the
value held in the direction variable.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 3)
Adding Platforms
We are going to put three platforms in place to get things
working. Later, you will need to build on these ideas to
create your own game.
a. Define a global list called platforms. This will contain the coordinates for each block that
makes up the platforms. We will search through this list every time our player jumps in
order to find out if it has landed on something solid.
b. Add a function called create_platforms(). Call the function from your main program.
The function should start by defining a turtle of your choice (our platforms are made
from a row of 5 blue squares) and then add a series of locations to your platforms list.
The two code snippets below show two different methods of creating the list of individual building blocks that make up
the platforms. The code below left simply lists the locations of all 5 squares in each of our 3 platforms. The code below
right uses a list of starting locations and then creates a 5-square long platform to the right of each.
For now, we suggest you use the code above right to create your list
as it makes testing new ideas easier. However, further down the line,
you might create a game that needs detailed, varying designs and
decide on the method above left. Alternatively, you might use a
combination of the two.
c. Once you have created the list, it is easy to transfer this to the screen. Use
code like ours on the right.
The next task is to get your player jumping onto the platforms. Try
programming this yourself before continuing with the next page. The
code on the right should help you check for blocks.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 4)
Jumping on Platforms
It’s not a huge step to make the player jump around on platforms.
The final lines of code on the previous page will help the player jump
up onto higher platforms. However, if you jump off a platform into
empty space, the player won’t fall.
a. Edit your jump function so that the loop is infinite. This loop will
run repeatedly until the player hits a platform. Note that we still
need the count variable, i, so this has been defined before use and
increased by 1 at the end of the loop.
The else statement (line 122 in our example) has been replaced
with an elif (meaning else if). The xpos variable only changes for
the first 16 steps, after which all movement is vertical.
c. Add similar restrictions to the horizontal movement (our lines 120 and 122) so that the player cannot jump out of the
playing space to the left or right.
a. We will use a function called check_fall so that we can use the same
code when walking in either direction rather than repeating
ourselves. Call the check_fall function from within the go_left and
go_right functions.
Note: You should only test for platforms once the player is above
ground otherwise it’ll be falling through the floor again.
c. You might need to shift your platforms a little once this functionality is in
place. The required jumps could be too big for your player.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 5)
Our player is jumping around reasonably well but we still identified the following issues:
• The player falls off a platform before it gets to the edge; its body then passing through the
platform. It may look better if it could take one more step before falling;
• Something odd seems to happen when the player jumps against the righthand wall. It
appears to shake wildly as it rises and falls. This may not be a problem in your program;
• If you jump up through a platform the player can get stuck inside a block (see right);
Fork the program and name the copy “G5 Jump 2”. Try and solve some of the problems yourself before working through our
hints below where necessary.
b. To let the player move further towards the edge of platforms, you could edit the check_fall function as we have below.
It basically checks for a platform 10 pixels either side of the one below the player.
Note: Don’t force a new line in the if statement; just keep on typing and let the page decide how it is displayed.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 6)
d. The next issue was that the player could get stuck within the platforms. We added to the conditions of the if statement
in the jump function so that it only checked for platforms when the player was falling.
e. The last problem we tackled was that if you hold down the spacebar (or press it repeatedly in quick succession) the
player starts to fly. This is due to the fact that the jump function is being called again before the previous call has
finished processing. Basically, the player starts a new jump before finishing the last.
One solution is to stop the window listening until we are ready for
the next jump.
Fork your last solution and name the copy “G5 Jump 3”. Try any of the following that you believe might be useful.
Start Display
Creating a Start event is almost compulsory.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 7)
Fatal Falls
Log the starting height before any jump or fall, then log
the height at the end of the movement. If the
difference between these two heights means a greater
fall than you wish to allow, call a die function and stop
listening for further keyboard commands.
Our die function simply turns the player red but you can
choose your own actions.
Lives
Decide on the number of lives your player will have and display this on the
screen. Below are some hints to get this function working:
a. Create a turtle to display the number of lives. This will need defining
globally so the start of your program is a good place for it. The design
of your turtle can easily be added to the setup function.
b. Add a variable to hold the number of lives left. Place this outside
your functions and decide on a starting value.
c. Edit your die function so that it reduces the number of lives left and
recreates the display. Note the following:
• You will need to declare that you are changing the global lives
variable before doing so.
• After a short delay, you could return the player to its starting design and position. The time module must be
imported at the start of the program if you are going to create a delay using the sleep method.
Game Over
Decide when the game is over and display a
message suggesting this.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 8)
Timing
Although it’s easy in Python (with Turtle) to measure the time a game has been running, it can be problematic keeping a display
up to date.
a. Create a turtle to display the time (this will need defining globally). The design of the turtle can also be added to the
setup function.
b. Add a variable called StartTime to store the time when the game begins. This
should be global and given the initial value 0.
c. Log the start time using the code StartTime = [Link](). Remember that you
must state that you are updating a global variable before doing so from within
a function.
d. Create a function that recalculates the time and updates the display (see ours
below right).
• You are probably best breaking down the development into a series of small steps then tackling them one at a time.
Although there can be issues with this method, it’s generally a great way to learn skills.
• Fork your last solution and name the copy “G5 Jump 4”.
• Create a new fork every now and then in case you need to return to an earlier version for any reason.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 9)
Race
An easy step forward is to make your game a race to the top. Add some
more platforms and test them to make sure the game is challenging but
achievable.
For a more difficult task, make it a 2-player game with two different
coloured players racing to the top at the same time. Select keyboard
controls that allow two people to control their players (this can be a
squeeze).
Avoid
Add some objects to avoid. In the original Donkey Kong game, Mario had
to make his way to the top of the screen whilst avoiding barrels thrown
down the slopes. The game also had ladders to climb which is something
you might consider.
Collect
Add objects to collect. In the classic Jet Set Willy game, the player moves
around from room to room collecting shiny objects. There are lots of
things to avoid as well as the danger of big falls. Having said this, keep
your game simple to begin with and see how you go. Adding a number of
objects to collect and a timer is a great start.
• Choices Allow the player to decide what keys to use. Look back at how to validate user input.
• Moving Platforms Make your platforms move up and down or from side to side. Simply reaching the top
of the screen then becomes much more challenging.
• Locks and Keys Find the key and open the door.
• Surfaces Add ice to make the player slide, mud to slow it down or water to swim through.
• Throwers and Shooters Either your player or some enemies might throw objects or shoot lasers etc.
• Explore Find your way through rooms, possibly answering questions on the way.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Race
a. Fork your solution to “A3.1 Playing Space” from the Playing Areas
tasks, naming the new copy “G6 Race 1”. Remove the sections of
code that create the dashed lines; these are not needed.
Note: At the time of writing, this game had serious issues when starting
with the [Link] template. We suggest you fork our template and
copy your code into this. [Link]
b. Design a racer for your game. We are going to use cars but you can
race whatever you like. Create your racer so that it occupies a space
up to 20 x 20 pixels, centred on (0,0) and pointing to the right.
You may generate coordinates for the vertices any way you like; we
designed our character using the tools in Microsoft Word:
1. Open a new Word document and select ‘Layout / Align / View Gridlines’.
2. Click ‘Layout / Align / Grid Settings’ and choose a
horizontal and vertical spacing of 1cm. Click OK.
3. Select ‘Insert / Shapes / Freeform: Shape’.
4. Click on the grid axes repeatedly to create the shape.
Finish with a double click.
5. To edit the shape, right click on it and select Edit Points. You may
then move the vertices. You may also add and delete points.
The coordinates are listed in turn using the form (y,x), each
separated by a comma. Let the coordinate pairs run onto
new lines as you type rather than forcing new lines. It
doesn’t matter where in your shape you start.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 2)
The Track
It’s time to design your track. In the main area of your program, define a list for the
obstacles. The list should contain a 1 where you want to place a block and a 0 otherwise.
Thankfully, you may use the Enter key within the list without affecting the program,
so make the list 30 items long and 25 items down (as ours below right). You may
need to adapt the track size if you are working on a small screen.
Have a go at printing the track to the screen. There are a few ways of doing
this but we have used a simple loop, part of which is shown on the right.
Our turtle, called obstacle, moves from the left to the right
of the screen, top to bottom. Each jump is 20 pixels. We
are also moving through the track list one step at a time. If
the list element contains a 1 we stamp a square on the
screen.
Continue to the next page when you have had a go at
completing this coding yourself.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 3)
Use the loop on the right to run through the track list and stamp a square
in any place where the associated list item is 1.
We need some code to translate the location of the racer into an index from
our list. We can then check to see if the list contains a 1 at this index.
The code on the right does a fairly good job of finding the index for any
location. It can be added to your go_forward1 function, before the if
statement. You can then add to the if conditions to check for an obstacle.
Use these bits of code to try and get the basics
of the game running. The result won’t be
perfect but it’s a good start.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 4)
• The racers don’t turn very quickly. It might be better to let them turn tighter corners;
• The track is slowly created on the screen; there is quite a delay before the game starts;
• The racers enter the walls before being knocked back. You might be fine with this or you
could prevent them from going this far;
Fork the program and name the copy “G6 Race 2”. Try and solve some of the problems yourself before working through our
hints below.
a. Creating sharper turns is easy; simply change the argument in the left and
right methods for each racer. Even better, replace this value with a variable
and define this in the main part of your program. This will make it quicker to
test changes and will help prevent errors.
b. The track creation is slow. Add the bits of code below and below right to print
the track all at once. We found afterwards that the program sometimes failed
to start so we had to run it again. However, on the
whole it sped up the process massively.
c. The racers entering the walls before being knocked back might or might not be a problem for you; we quite like the
effect. If you do want to prevent the racer entering the wall you need to know where it will end up before you move it on
a step. You can then decide whether to go ahead with the move or not. This will require a little mathematics.
Note: This theory is needed for the next problem, even if not used here.
10 sin h
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 5)
The code on the right can be used to find how many pixels
across the racer will move. This can then be added to the
current position to find the new x location. Similar code will
find the new y location, this time using the sin function.
d. To stop the racers driving over each other, find the current position
of the other racer and prevent the step forward if the racers will
end up too close together after the next move. You will need the
mathematics from the last problem.
e. The issue of passing through obstacles is difficult. The problem is that we are rounding off the car’s location to a point
in the middle of a square in our invisible grid. The car shown below right would be considered outside the purple
obstacle because its centre is in the square below. There are lots of ways of improving this process:
• Make each obstacle a turtle and measure the distance between the car and
each turtle in turn. Unfortunately this would really slow down the game;
• Use a list of coordinates for the obstacles rather than a set of 1s and 0s and
then calculate the distance from each coordinate. This would make the track
design less graphic, however; you would need a long list of coordinates;
• Keeping the list of 1s and 0s but translating them to coordinates for consideration;
• Improve the code that calculates the index for any position; it is flawed.
We are going to leave this problem up to you. If you’d like to try and improve this aspect
of the game then make a copy of your program and have a play around. We will move on
to other functionality rather than overcomplicating things at this point.
If you haven’t already, add comments to your program explaining what the different
sections are doing.
Fork your last solution and name the copy “G6 Race 3”. Try any of the following that you believe might be useful.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 6)
Start-Finish Line
Create a start-finish line and position your racers behind
this at the start of the game.
Lap Counter
Add a lap counter for each racer. The display turtles should be
defined at the start of the main program as you will need to
update them from the go_forward functions.
Checkpoints
We need to make sure that the racers are completing laps properly
and not taking short cuts or moving backwards. For our simple
track, a minimum of 3 checkpoints are needed to ensure laps are
completed. One of these has been created over the start-finish
line. It doesn’t actually matter where the others are, provided they
cross the track completely and have a gap between them bigger
than the steps taken by the racers.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 7)
Checkpoints (cont.)
The crossing of checkpoints can be set up in a similar way to the crossing of the start-finish line. The following logic should be
used:
Start off by declaring some variables in your main program to hold the active checkpoint for each racer. Set these with your
highest checkpoint; ours is 3.
Winning
Create a display for the winner. It’s best to set the number of laps as
a variable in your main program so that it can be easily changed.
Note: The way our program is coded, the racers will have to complete
1 less than the number set. This could easily be amended.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 8)
b. Create one more turtle for the start display, again defined in the main
section of the program. The styles can also be added to your setup function.
The message should tell the players which key to press in order to start the
game.
c. Add an onkey event for the starting key. When this is pressed, launch a
function called countdown that sets the countdown clock into action.
e. The countdown function should set off the countdown. We used a for
loop to count from 3 down to 0. The range function takes 3 arguments:
• The finishing number, although the last isn’t used (we have set to -1);
• The step to take each time the loop runs (set to -1).
Use the sleep method to wait for 1 second between loops. You may then
clear the display and start the race when the count reaches 0. We moved
the keyboard commands into a function called start_race and called this
when required.
CoP058 – Python Games ORB Education. Visit [Link] for a range of quality teaching resources.