0% found this document useful (0 votes)
15 views60 pages

Python Graphics - Student Booklet

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views60 pages

Python Graphics - Student Booklet

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Games

Dan Collingbourne
Contents

Skills

A1. Getting Started


A2. Functions & Controls
A3. Playing Areas
A4. Counting & Displays
A5. Inputs & Data Validation
A6. Lists

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.

c. We want to start with the Python


(with Turtle) template. If the
template is visible, simply select it.
If it is not visible then search for
‘turtle’ and the template should
appear as the only result.

Note: Don’t open a Python


template; we need ‘Python
(with Turtle)’.

d. Give your new repl the name ‘Test’ and click the Create Repl button. You will be taken to the coding page shown below.

The top right section is where


the results are displayed. This
The left half of the is the output.
screen is where you
type your code.
This is the called the
input. The bottom right section is
called the console. It
displays errors and other
messages. You may reduce
Reduce the Console the size of the console by
dragging down the bar
above.

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)

Task 2 – Sample Program


If using [Link], the programming code for the sample program will appear in the input section.

a. Click the Run button and view the resulting output.


Note: Those not using [Link] will need to learn how to create and run programs. Once you know how to do this, type lines
9-16 of the code below into a new file and run the program.

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?

If nothing appears to happen when you run a program then


there may be a syntax error. Look at the console to see where
the error lies. This information will usually help you locate the
problem.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Getting Started (page 3)

Task 4 – Editing the Program


Edit the program so that it is like ours on the right; we have
removed the comments from the opening lines and changed some
of the other code. When run, it should create a triangle as shown.

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.

c. Change the number in line 8 from 120 to 90.


Note: These are turn angles. For a 3-sided shape each turn must be 360° ÷ 3 = 120°.

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.

c. Enter the name Test2 and click Confirm.

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)

Task 6 – Turtle Methods


In the type of programming we are using (known as Object-Oriented Programming or OOP) methods are like hidden
programs that you can make use of. For example, we have used the forward method to draw a straight line. There are some
more complicated things happening behind the scenes but as far as you’re concerned, you type ‘forward’ and the turtle
moves forward.

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?

d. What argument is passed to the forward method on each occasion?

e. What syntax (i.e. punctuation) is used when the arguments are word values
rather than numbers?

f. How are the begin_fill and end_fill methods used?

g. Which methods don’t take any parameters?

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.

Task 7 – Setposition Method


Our turtle is working on a canvas that uses a coordinate
system like the one shown on the right. So far, we have
always started drawing in the centre (a location with the
coordinates (0,0)). In our games, we may want to
position objects elsewhere. This can be achieved with
the setposition method.

Using coordinates, write a program to create the orange


graphic shown (a rectangle with one half diagonal and
circle stamps in the corners). Part of our solution is
shown below. Save your program as “A1.7 Position”.

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.

Task 1 – Keyboard Commands


The program on the right will give you keyboard control
over a Turtle object called scribe. The keyboard
commands are as follows:

p Move forward 10 pixels (hold down to repeat)


w Turn right 10°
q Turn left 10°

Create the program and use the controls to produce a


pattern. Our picture below was an attempt at drawing Calling the
crop circles. Save as “A2.1 Keyboard Commands”. function takes
the program
flow through
Note: You might have to click on the output the function
window to make the controls active. before
returning to
The lines within the original
the function point.
must be
indented. Use
a single Tab
indent or two
spaces.

Questions about the program

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?

Edit the program in order to create some different style patterns.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Functions & Controls (page 2)

Task 2 – Control Using the Arrow Keys


90°
In the activities above, we rotated the turtle and moved it forward to create patterns. In games,
135° 45°
however, you often move your player up, down, left and right. We will learn how to control the
turtle in this way using the arrow keys.
180° 0°
The direction in which the turtle is pointing is dictated by the setheading method. This method
takes one parameter with values such as 0 for pointing right and 270 for pointing down. 225° 315°

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.

Task 3 – Mouse Clicks


It’s easy to get the turtle to follow mouse clicks on the
screen. Type the code shown on the right into a program
saved as “A2.3 Mouse Clicks”. Try clicking around on the
screen to create a picture. Clicking twice quickly in
different places can produce interesting patterns.

Notes: The ‘onclick’ event on line 10 calls the ‘clicking’


function, sending the x and y coordinates of the
mouse as arguments. The actual function places
these values into the parameters, x and y. The
‘goto’ method has the same effect as ‘setposition’.

Task 4 – Mouse Dragging


The use of mouse dragging to move the turtle is also easy. Fork the last program and save as “A2.4 Mouse Dragging”.
In this case, you don’t need to define the Screen object.

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.

Task 1 – Playing Space


Use code like ours on the right to create a playing space. Save as
“A3.1 Playing Space”.

Questions about the program


a. What name is given to the function? On which line is this
called?
b. What do the methods penup, pendown and hideturtle do? Try
removing each of these in turn from your program.
c. Try some different values for the speed argument. How does the
value 1 compare to 10? What do you think the value 0 means?

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.

These lines must start


with the same indent.
We have used two Tab
indents which appear as
4 spaces in the program.
Either method is fine.

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)

Task 3 – Border Control

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.

e. Add similar restrictions to the other three movement functions so that


the turtle can’t leave the playing area.

-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°

In the Python with Turtle programming language, angles are generally


calculated anticlockwise from east as shown in green on the right. Helpfully,
however, you may also use the negative angles calculated clockwise from east 225° 315°
270° -45°
(shown in purple). You therefore only need the following two rules: -135°
-90°

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.

Task 1 – Random Numbers and Count-Controlled Loops


Random numbers can be generated easily in Python. A random integer
between 1 and 10 can be created using the code:

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.

b. Run the program repeatedly. It should send a turtle off in a random


direction each time.

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.

c. Add a count-controlled loop so that the


turtle resets itself each time. A loop
which will run 10 times is created using
the code:
These lines must start
with the same indent.
We have used a single
Tab indent which
appears as 2 spaces in
Note: We have left a stamp after each move.
the 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”.

b. Create a variable to hold the number of lines drawn. Name the


variable NoLines and give it an initial vale of 0. Add 1 to this value
each time the loop runs.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Counting & Displays (page 2)

Task 2 – Counting (cont.)

c. Our program is now counting the lines


created but we need to display the
number on the screen.

Insert the code on the right to create a


display. Notice that the display is actually
just another turtle positioned on the
screen. The initial display is 0.

d. The last step is to display the count


each time a new line is drawn. We
have added two lines as on the
right, although you could test what
happens if you place them
elsewhere in your loop.

e. Find out what happens if you omit line 26 and run the program.

Task 3 – Numbers to String Conversions


Displaying a number for the count is fairly easy. However, there’s a bit of a complication if you want to display something
more detailed, such as the text “7 lines”. One method of achieving this would be to add a second display turtle showing the
text “lines” and placing it alongside the first. We’ll try and display the information as one variable.

a. Fork the program and name the new copy “A4.3 Numbers to String”.

b. Changing the initial display is


easy. See the code on the right.

c. Create a variable that adds the number of


lines to the text “ lines”, as on the right
(notice where we put the space). What
error is created when the program is run?

d. The problem is that we are trying to join a number with some


text. Python does not allow this. Before joining these two
pieces of information we must convert the number data type to
a string (i.e. text). This can be achieved using the str function.
You can then show the new variable in your display turtle.

Note: Joining two strings together like this is called concatenation.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Counting & Displays (page 3)

Task 4 – If…Else Statements


The above code works but unfortunately displays the text “1 lines”. A common easy fix for this type of problem is to add the
‘s’ in brackets e.g. “line(s)”. A better solution would use an if statement to display different things at different times. We
want to display the word “line” if the count is 1 else we should display the word “lines”.

Fork your last program and name the copy


“A4.4 If Else”. Use code like ours on the right
to display grammatically correct information.

Note 1: We have used the comparison


operator ‘==’, meaning ‘is equal to’.
This is different to a single equals sign
which means ‘make equal to’.

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”.

b. Add a turtle to display the number of seconds the program has


been running, starting at 0.

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.

e. At the end of your loop, find the number of


seconds that have passed since you started the
clock. Use the int function to get rid of all the
numbers after the decimal point.

f. Update the display.

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.

Run the program. To enter data, click on the


console in the lower right corner, type a
number and press the Enter key.

b. The program creates an error, as below:

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.

Edit your code and test the program.

Task 2 – Limiting the Input


The clock doesn’t really make sense once you go past 12 so we should limit the input to the numbers 12 and below. The
inputted number should also be 1 or above. The adaptation shown here will help limit the numbers that can be inputted.

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.

my_list[0] This is 12, the first item in the list.


my_list[2] This is 351.

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:

Task 1 – Text and Numbers


Create a new program named “A6.1 Lists” and copy the code below. Try and answer the three questions.

a. Why don’t we need to import the


turtle module in this program?

b. How many times is the loop


successfully executed?

c. Why does an error occur?

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:

a. What is the name of the


function?

b. How many lists are created in


the program?

c. What type of data do each of


these lists contain?

d. On which line is the list of


turtles defined?

e. Which line adds turtles to the


list?

f. What changes would be


needed so that the program
creates 6 turtles?

Make these changes to the


program and check that they
work.

g. Why is the number_of_turtles


variable defined outside the
function?

Hint: Look up scope in


the Playing Areas
resource.

Extension – Extra Practice


Fork the program above and see if you can write a program that meets all
the criteria below. Name the program “A6.E Extension”.

• 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).

• Use a variety of colours.

• 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

Difficulty = 1; Lines of code in solution = 193. Section Req


A1 Getting Started ✓
This is a simple game where you have
to stop a bouncing ball hitting the
A2 Functions & Controls ✓
base of the playing area. Much of the A3 Playing Areas ✓
code can be copied straight from the A4 Counting & Displays ?
introductory sections. You may take A5 Inputs & Data Validation X
things much further if you wish. A6 Lists ?

Required? ✓=yes, X=no, ?=possibly

Task 1 – The Basic Game

Setting up the Screen

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.

e. Running your program


should produce a graphic
something like the one on
the right.

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)

Task 1 – The Basic Game (cont.)

Setting up the Screen (cont.)

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.

h. Call these functions after setting up the screen.

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.

Hitting the Ball

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.

Note: There will be problems with how this code works.


We will look to improve it in the next section.

b. Finally, the ball is still bouncing off the bottom boundary.


Change the single condition that controls the bounce from the
top and bottom surfaces so that it bounces only off the top
boundary.

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.

c. Add comments to explain what each section of code is doing.


Single line comments start with the hash symbol (#).

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)

Task 2 – Fixing the Problems


There are a number of problems with the program. These are the ones that we observed:

• There is a delay every time the ball hits a wall;


• The ball might appear to stick to the bat;
• The ball sometimes moves straight downwards and disappears;

• It is quite hard to hit the ball with such a small bat.

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.

a. The delay can easily be removed by setting to speed of the ball


to zero.

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)

Task 3 – Adding Functionality


You may easily add some bells and whistles to your Bounce game. In a fork your last solution named “G1 Bounce 3”
try some of the following.

Random Angle 90°

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.

Extension 1 – Multiple Ranges


One solution to the last problem is to simply reduce the starting angles to a range such as 30-60°. However, this means
that the first movement is always up and to the right. With a little programming, you may generate a range between
either 30-60° or 120-150°.

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.

Extension 2 – Scope and Return Values


It is good practice to place a section of code (such as that created in Extension 1) in
its own function. However, we have an issue here. Try generating the angle in a
separate function and see what happens when you run the program repeatedly.

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.

A second solution is to define the


angle variable as on the right then
add the return statement to your
function as on the far right. The new
angle will be returned to the main
program and placed in the angle
variable. This is how functions
commonly work in programming.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Bounce (page 5)

Task 3 – Adding Functionality (cont.)

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.

c. Move the line that creates your display turtle to the


start of the program. We will be updating this object
from our main program so the definition must be
global.

d. Define a variable to hold the number of hits. This


should start at 0.

e. Add 1 to the number of hits each time the ball is hit and rewrite the display.

Game Over Display


Display the words “GAME OVER” when the ball hits the bottom border.

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.

c. Move the ball forward by the value stored in the variable.

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)

Extension – Super Challenge


If everything so far has been easy you may want to tackle our super challenge. We do not provide solutions but will
suggest a few things that should help you on your way.

a. Search for the game Breakout. You


should be able to find a website where
you can try the game. There is even one
on Google.

b. Search for breakout game code and look at ideas


for simplified versions.

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.

• Run through the list of turtles each time


the ball moves and see how close each is to
the ball. If it is close, hide the block on the
screen and remove the turtle from the list.

• Getting the ball to bounce over the top of


the blocks is more difficult. Hold the
direction of travel in a variable and adjust
the bounce depending on this.

• 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

Difficulty = 1; Lines of code in solution = 223. Section Req


A1 Getting Started ✓
This game involves dodging objects that
are moving across the screen. The basic A2 Functions & Controls ✓
game is reasonably straightforward but the A3 Playing Areas ✓
possibilities for extension are endless. A4 Counting & Displays ?
A5 Inputs & Data Validation X
A6 Lists ✓

Required? ✓=yes, X=no, ?=possibly


Task 1 – The Basic Game

Setting up the Screen

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.

Adding the Projectiles


It’s now time to add some projectiles that will move along the screen from right to left. Each projectile will be a new turtle,
beginning its journey from a random spot on the right-hand side. The turtles will be stored in a list.

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.

c. Create a loop which will run until we tell it to stop.


Within this loop, create an if statement that adds a
new turtle to the list but only if there are less than 20
already. Use the len function to count the number of
turtles in the list (see below right).

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)

Task 1 – The Basic Game (cont.)

Questions about the Program

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?

Have a go at adding the programming for the last two questions


before continuing.

Moving the Projectiles


You might have created your own solution to the problems above. If so, have a look at ours anyway so that you understand
the differences.

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.

b. Getting the projectiles moving can be achieved with a loop.


Move through each turtle in the list and nudge it forward a
little. You will need the setheading method first to point
the turtles in the right direction.

Test different arguments in the forward method to find a


value that creates a good pace of movement across the
screen.

More Questions about the Program

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)

Task 1 – The Basic Game (cont.)

Hiding the Projectiles


The next step is to hide each turtle when it reaches the
lefthand wall. We have used the code on the right to both
hide the turtle from view and remove it from our list.

a. Try the code for yourself.

b. Remove our lines 90 and 91 in turn (your line numbers


might be different) and run the program each time. Try
and explain what is happening in each case.

Testing for a Collision


Each time a turtle moves, we want to see if it is close to our ship

Try the code on the right. It measures the


distance between the projectile and ship. If this
distance is less than 20 pixels we change the
value of the end_game variable in order to
escape the loop and end the game.

You should find that the ship turns red when a


collision occurs but that the projectiles don’t
stop moving. What is happening?

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).

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.
Dodge (page 4)

Task 2 – Fixing the Problems

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;

• Whilst experimenting with different values to


make the game harder, we experienced the out of
range error shown on the right.

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.

a. Limitations can be put on the ship’s movement using code


such as ours on the right.

b. The flickering might be controlled by changing the


order of events when a new projectile is created.

If the above trick doesn’t work for you, try


the tracer and update methods as used on
the right. These will turn off all animation
whilst the turtle is being created. However,
a side effect of this is that it might also speed
up the game significantly. If so, see the
solutions below.

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)

Task 2 – Fixing the Problems (cont.)

• Change the total number of turtles that can be in


existence at any time.

• Make the game more difficult by increasing the number


of projectiles that are created each time the loop runs.

You might use a for loop to create turtles 2 or 3 at a


time, as we have on the right.

• Add a delay to the loop; this can slow down


proceedings as much as you like. To use the time
functions, you must first import the time module.

You may then use the sleep method to add a delay of a


set number of seconds.

d. The out of range error is caused by our for loop. The following series of events might occur:

1. We count 20 turtles and set up the for loop


with a range of 19 (i.e. indexes 0-19, as they
should be).

2. A turtle is deleted when it hits the left border.

3. The program is still counting to 19 even


though the highest turtle index is now 18.

You may investigate this by printing information to the screen, as above.

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)

Task 3 – Adding Functionality


There are lots of ways you might improve your Dodge game. In a fork your last solution named “G2 Dodge 3” try
some of the following.

Game Over Display


Display the words “GAME OVER” when the
ship is hit by a projectile. We have placed
the code in a function called game_over.

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.

b. Create another function which displays a start message. Choose a key to


run the main function when it is pressed.

Note: You will need to define the turtle globally as it will be needed from
other functions.

c. Hide the start display when the


main program runs.

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.

Find a suitable place in your loop to recalculate and update


the time. This shouldn’t happen too often as it will slow down
the action.

Remember to import the time module and define turtles


globally if they are needed in different functions.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Dodge (page 7)

Task 3 – Adding Functionality (cont.)

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.

• You might decide to change


how your ship moves so that
it is always upright (rather
than rotating and moving
forwards).

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”.

b. Set the level to 1 initially then use an equation such as ours on


the right to work out the current level as an integer and write
this to your display.

c. Move each projectile forward by a multiple of the level.

d. We found out of range errors occurred (and weren’t


always reported in the console) as the jumps increased in
size. Decrease the range checked as the level increases.

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)

Task 3 – Adding Functionality (cont.)

Stopping the Screen Refresh


You might decide that things are still all moving a little too
slowly. The problem is that the screen is refreshing each time
one of the projectiles moves a step to the left; this is slowing
everything down. To speed up the gameplay (and smooth the
visual appearance) we can refresh the display only after all the
projectiles have been moved on a step. Use the code on the
right before and after the loop to put this into place.

Note: We have also shifted the calling of our game_over


function so that the last screen refresh takes place before
everything stops. Without this edit, the ship doesn’t
appear to have been hit by a projectile.

Extension – Super Challenge


Through the years, there have been lots of games that involve objects travelling across the screen that must be avoided.
Develop your game in any way that you choose. There are some ideas below.

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.

Flappy Bird Defender


Car Racing

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

Difficulty = 2; Lines of code in solution = 255. Section Req


A1 Getting Started ✓
This game involves steering a snake
without hitting the walls or its own tail. A2 Functions & Controls ✓
Food items are gathered by the snake, A3 Playing Areas ✓
each making it a little longer. A4 Counting & Displays ?
A5 Inputs & Data Validation X
If you’re not familiar with the game, have a A6 Lists ✓
look for a version online to play. There is
one hidden in Google Search. Required? ✓=yes, X=no, ?=possibly

Task 1 – The Basic Game

Setting up the Playing Area

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

The Snake Head

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)

Task 1 – The Basic Game (cont.)

Moving the Snake


The snake will be continually moving. This will occur with the use of an infinite loop.

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.

Hitting the Boundaries

a. Add lines to your code that check the new location


of the snake after each move.

b. If the snake has travelled out of bounds, escape the


loop by changing the end_game variable away from 0.

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.

These two coordinates will provide a location for the food.

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.

c. Create a function called place_food which generates two


random coordinates and places the food turtle in the location
defined by them. Call this function after setting up the screen.

Note: Our solution is shown on the next page but have a


go at this coding yourself first.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Snake (page 3)

Task 1 – The Basic Game (cont.)

Eating the Food


The food is eaten when the location of the
head is the same as the food. There are lots
of ways of checking for this condition but we
will look for a distance of 0 between the
head and food.

Try this code for yourself. Remember to also call


the place_food function when setting up the
screen.

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 the snake turns a corner, the tail


segments continue to follow the earlier
movements. They do not turn at the
same time.

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.

Tail Tail Tail Tail Head


Index 3 Index 2 Index 1 Index 0

1st 2nd 3rd 4th 5th

The program will work like this:

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.

3. Move the head forward.

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)

Task 1 – The Basic Game (cont.)

The Tail (cont.)

a. Create an empty list called snake_tail. This should be defined globally as we


might need to access it from other functions.

b. Create a new tail segment by defining a turtle and adding it to the list, as is
partially shown on the right.

c. The first segment should


be moved each time the
loop runs but only if there
is a tail present (i.e. this
code will be skipped until
the snake has had its first
meal).

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).

The range function used on the right takes 3 parameters:

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.

Hitting the Tail


After moving the head, you will
need to check that it isn’t
touching any of the tail
segments. A simple for loop
and the distance method will
check this for you.

Test your program and list the problems.

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)

Task 2 – Fixing the Problems

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 moves slowly after a few meals;

• 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;

• The game seems to stop suddenly for no reason at random times.

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.

a. The issue of passing right over the food is easy to solve.


The problem is to do with the fact that the coordinates
used behind the scenes might be something like
40.000001 rather than precisely 40. To solve the
problem, set the distance between food and snake to be
less than 10 rather than equal to 0. The same can be
done for the distance between snake head and tail.

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.

Decrease the delay by 0.01 seconds after food is eaten. Without


additional code, the delay value will be negative after 11 decreases but
this shouldn’t be a problem.

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)

Task 2 – Fixing the Problems (cont.)

d. We will now look at how to prevent the snake turning back on itself.

Create a variable called heading and give it an initial value of right.


This is the direction in which the turtle is travelling at the start of the
game, although you might change it later. This variable must be
global.

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.

Make a similar change to the other directional functions.

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.

Task 3 – Adding Functionality


Fork your last solution and name the copy “G3 Snake 3”. Try some of the following.

Scoring
Basic scoring is easy in this game. Simply start at 0 and add 1
every time a piece of food is eaten.

Game Over Display


Display the words “GAME OVER” when
the snake crashes. We have placed the
code in a function called game_over.

Smaller Playing Area


The game is a bit easy. We decided to reduce the size
of the playing area to make it more difficult.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Snake (page 7)

Task 3 – Adding Functionality (cont.)

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).

b. Create another function which displays a


start message. Choose a key to run the
main function when it is pressed.

Note: You will need to define the


turtle globally as access will
be required from the other
functions.

c. Clear the start display when the game


starts (as on the far right).

d. Your actual program should


now set up the page and run
the start function.

Increasing the Speed


You might decide that things are all still moving a little too slowly. The
problem is that the screen is refreshing each time a segment of the
snake moves; this is slowing everything down. To speed up the
gameplay (and smooth the visual appearance) we can refresh the
display only after all the segments have moved on a step. Use the code
on the right at the start and end of the while loop to set this in place.

Extension – Super Challenge


We have listed some ideas for extending the game below but feel free to come up with your own.

• 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.

• Create a high score display and allow a new game to be started.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Tic-Tac-Toe

Difficulty = 2; Lines of code in solution = 199. Section Req


A1 Getting Started ✓
Tic tac toe is a simple game, often
called naughts and crosses. A search
A2 Functions & Controls ✓
for ‘play tic tac toe’ should locate a A3 Playing Areas ✓
version you can try online. A4 Counting & Displays ?
A5 Inputs & Data Validation ?
A6 Lists X

Required? ✓=yes, X=no, ?=possibly


Task 1 – The Basic Setup

Designing the Graphics

a. You may fork your solution to “A3.1 Playing Space”


from the Playing Areas tasks or start coding from
scratch. Name your new program “G4 TicTacToe 1”.

b. Use the setposition,


penup, pendown
and setheading
methods to create a
playing grid. Base it
on a 300 x 300 pixel
sized square.

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)

Task 1 – The Basic Setup (cont.)

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.

Identifying the Square


We need to work out which square the player has clicked so that we
can decide where to place the naught or cross. The diagram on the
right shows the coordinates of the centres of each of the squares.

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.

The draw_naught function picks


up these values and places them
in the parameters x and y (as on
the far right).

The function uses these values


to decide on the location for the
circle. As the program starts
drawing the circle from its
lowest point, we need to begin
drawing 25 pixels below the
centre of the square.

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)

Task 1 – The Basic Setup (cont.)

Checking for a Winner


The diagram below right shows all the lines which need to be checked to see if there is a winner. List the box numbers for
each row, column and diagonal in the table.

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

D Box 4 Box 5 Box 6


B
E Box 8

F
Box 7 Box 8 Box 9
G Box 5 C
H
H

a. Define global variables (i.e.


outside all the functions) for
the 9 boxes. Give each a
starting value of 0. You may
use the single line shown to do
this quickly.

b. In your clicking function, set up a series of if…elif statements


to record the squares as they are selected by each player.
There should be one if and eight elif statements altogether.

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’.

d. Add to your if statement so that it checks all 8 possible winning


lines. You may use the continuation symbol (a backslash) to tell
the program that the statement continues onto the next line.

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)

Task 2 – Fixing the Problems

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 on a square that is already taken;

• 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.

a. The first two issues can be solved together by


disallowing bad clicks. Declare a variable at the
start of your clicking function called bad_click,
giving it a value of 0.

Add to the conditions in your if and elif statements so


that a click will only be recorded if the associated
variable is still holding a 0. This disallows second
clicks in a square.

Add an else statement that changes the bad_click


variable to 1 if none of the other conditions are met.

Place the calls to the drawing functions inside an if statement so that


they are only called for good clicks. Remember to check your
indentations carefully; you now have an if statement inside an if
statement inside a function.

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.

If the game is won, change the value of this variable to 1.

Finally, use the return statement to escape the clicking function if the
value of the game_over variable equals 1.

Note: We must declare that we are referring to the global game_over


variable before using it within the function.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Tic-Tac-Toe (page 5)

Task 3 – Adding Functionality


With the basics of the game working reasonably well, we can start adding further
functionality. Fork your last solution and name the copy “G4 TicTacToe 3”.

Start Display
a. Create a function which displays a start message. Choose a key to run a start_game
function when it is pressed.

Note: The display turtle should be defined globally as it


will be needed from other functions.

b. Clear the start display when the game begins then listen for
the keyboard stokes.

c. The main program


should now run the
start function.

Game Over Display


It’s easy to add and call a game over display. Create a new function for this and call
it when a line of 3 has been formed.

Extension – Super Challenge


If everything so far has been easy you may want to tackle our super challenge. We do not provide a solution but will suggest
a few things that should help you on your way.

• Let the games restart indefinitely and display a record


of the overall score. You will need some more global
variables to store the number of games won by each
player.

• For a real challenge, develop a computer opponent. At


its most basic this might simply fill in empty squares at
random. A more difficult opponent will have an idea
about how to win the game.

• Taking this a step further, let the player choose which


level of computer opponent they play against.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Jump

Difficulty = 2; Lines of code in solution = 300. Section Req


A1 Getting Started ✓
We will create a jumping character for a
platform game then give you some ideas A2 User Controls ✓
for building this into something bigger. A3 Playing Areas ✓
The choice will be yours. A4 Counting & Displays ?
A5 Inputs & Data Validation ?
A6 Lists ✓

Required? ✓=yes, X=no, ?=possibly


Task 1 – The Basic Setup
Designing your Player

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)

Task 1 – The Basic Setup (cont.)

Moving your Player


You should be able to move your player left and right but only within the
confines of the playing area.

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.

1. How many small steps take place in the jump?


2. How many pixels does the player move up and across in each step of the jump?
3. Have a go at writing code yourself that will produce this movement. Use loops
and if statements to make your code more efficient. Our method is described
below if you need help.

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.

Your player should now jump left and right.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 3)

Task 1 – The Basic Setup (cont.)

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.

Study the two pieces of code and consider the following:

1. Which method seems the most straightforward?


2. If you wanted to move one of the platforms 10 pixels to the left, what edits would you need to make in each case?
3. If you wanted to add a fourth 5-block platform, what edits would you need to make in each case?
4. Which method would you select if your platforms are all very different in shape and style? Which would be best if
you are going to use a large number of similar platforms?

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)

Task 1 – The Basic Setup (cont.)

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.

Note: We have designed our program so that the player falls


vertically down after the initial 16 steps. You may prefer to
have the player moving in some other way as it falls.

b. As things stand, the player will fall through the


floor if you miss a platform. Edit the line of code
that looks for the coordinates in the platform list
(our line 131) so that it also checks that you
haven’t fallen below the base of the playing area.

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.

Falling off Platforms


The last part of our initial setup is to make the player fall off the side of
platforms rather than walk across mid-air. We will need to check that a
platform block is below the player’s feet each time they take a step.

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.

b. The check_fall function is similar to parts of the jump function, so


perhaps start with a copy and paste. Our code is mostly shown on
the right; hopefully you can complete the missing bits.

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)

Task 2 – Fixing the Problems

Our player is jumping around reasonably well but we still identified the following issues:

• The jumps are very quick;

• 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);

• If you hold down the spacebar the player will fly.

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.

a. To slow down the jumps, use the sleep


method to add a short delay to each part of
the jump. You will need to import the time
module before using the time functions.

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.

c. The third problem we had is that the player seemed to shake


when jumping against the righthand wall. We investigated
what was happening by printing the value of the xpos variable
each time the loop ran in the jump function. Sure enough, the
value of the xpos variable switched continuously between 280
and 290. There didn’t appear to be a problem on the lefthand
wall.

The issue was that we had added conditions to


the if statement that resulted in the if and elif
firing in turn repeatedly. Specifying that the elif
was only for when the player is moving to the left
solved the problem. You may have done this
yourself.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 6)

Task 2 – Fixing the Problems (cont.)

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.

Set up functions that start and stop the keyboard actions


having an effect, as on the right. You should then start
listening when you have set up the window, stop listening at
the beginning of the jump function and then start listening
again at the end of the jump function.

Note: We are actually telling the program


to do nothing when a key is pressed
rather than not to listen.

Task 3 – Adding Functionality


Now we have a player jumping around on platforms, it’s time to start thinking about game development. The direction you
take with this is up to you. We have outlined some ideas below that might help with the game you would like to build. You
only need to study the ones that will be of use.

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.

a. Create a function which displays a start


message. Choose a key to run a
start_game function when it is pressed.

Note: The display turtle should be


defined globally as it will be
needed from other functions.

b. Clear the start display when the game


begins then listen for the keyboard stokes.

c. Your main program should now set up the


page and run the start function.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 7)

Task 3 – Adding Functionality (cont.)

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.

• The code lives -= 1 is shorthand for ‘lives = lives-1’.

• Remember that you cannot add a number to a string. The lives


variable should be converted to a string using the str function
before concatenating it.

• 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.

If you are counting lives, you may just add an


if statement to your die function that acts
when the number of lives reaches zero.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Jump (page 8)

Task 3 – Adding Functionality (cont.)

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).

e. Add an infinite loop that runs the update function once a


second. If you haven’t already, you must import the time
module before using the time functions.

Important: Having a loop running continuously like this


can cause problems in Python (with Turtle).
Watch out for unexpected consequences,
especially if you have other loops running
throughout gameplay.

Task 4 – Developing a Game


With the basic movements now in place, you may develop the game in any way that you choose. The ideas that follow could
offer some inspiration but feel free to go your own way.

• 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)

Task 4 – Developing a Game (cont.)

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.

In your game, the dangerous objects could be stationary on the platforms.


Alternatively, they might be falling, flying or moving up and down. Start
with something simple and add to your ideas as you go along.

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.

Extension – Super Challenge


We have mentioned a couple of old platform games, chosen for their simple graphics and gameplay. However, there have
been thousands of more advanced games created since which might have functions you can work with. Here are some
common ideas used in platform games:

• 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

Difficulty = 3; Lines of code in solution = 412. Section Req


A1 Getting Started ✓
Design some racers to race around a track
then take this game forward with your own A2 Functions & Controls ✓
bells and whistles. A3 Playing Areas ✓
A4 Counting & Displays ✓
A5 Inputs & Data Validation ?
A6 Lists ✓
Task 1 – The Basic Setup
Required? ✓=yes, X=no, ?=possibly
Designing your Racer

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.

c. Once you have a set of coordinate pairs ready, create your


first racer using code such as ours on the right. Define
your racer globally (at the top of your program) and place
the rest of the code at the end of your setup function.

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.

The starting position of your racer can be adjusted once


your track is ready.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 2)

Task 1 – The Basic Setup (cont.)

Moving your Racer


Use the code from the Keyboard Commands task in the Functions & Controls resource to
move your racer forwards. You will need to set up the onkey functions and tell your window
to listen for events.

Hitting the Boundaries


Add some if conditions so that the racer can’t leave the boundaries
of the playing area. If it does, then move the racer backwards
(perhaps 30 pixels?).

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.

Note: If using [Link], you may be able to select a


single 1 anywhere in your list and the
webpage will highlight all the others. This
makes track design easy. If this
functionality is not available you may
create the list in MS Word and search for
the ‘1, ’s instead.

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)

Task 1 – The Basic Setup (cont.)

The Track (cont.)


Well done if you managed to print the track to the screen. If not, then follow
these instructions:
a. Go to the top of your code and define a new turtle called obstacle.

b. Set the properties of the turtle at the


end of your setup function.

c. We are working with a grid of squares each


20 x 20 pixels in size. The top left square has
the coordinates (-290, 240). These will make
up the initial x and y coordinates of the
turtle.

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.

d. When you reach the end of the line, return


to the lefthand side of the grid and drop
down a row.

You should be able to drive your racer around the


track. The next step is to actually stop the car driving
through the obstacles.

Hitting the Obstacles


Knowing when our racer has hit an obstacle is a little difficult. We have a
list identifying where the obstacle blocks are. The list has indices
beginning at 0. In our case:
Track[0] = 1 - any location between (-300, 250) and (-280, 230)
Track[1] = 1 - any location between (-280, 250) and (-260, 230)
Track[2] = 1 - any location between (-260, 250) and (-240, 230)
Track[3] = 1, Track[4] = 0, Track[5] = 0 etc

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)

Task 1 – The Basic Setup (cont.)


The Second Racer
Copy, paste and edit the parts of the code required
to set up and move a second racer. Select keys so
that two players can squeeze in around the
keyboard and control a racer each. Set suitable
starting positions for the racers.

Task 2 – Fixing the Problems


You may well have already created a fun racing game but there are lots of ways of making it better. Let’s first look at things
that might be considered problems:

• 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;

• The racers can drive over each other;

• The racers seem to be able to drive through some of the obstacles.

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

To calculate where the racer will be after the next step,


we need to know the angle at which that the racer is h
pointing. This can be found using the heading method.
10 cos h
We will be using the sin and cos functions. You must
import the math module before using these.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 5)

Task 2 – Fixing the Problems (cont.)

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.

The if function can then be adapted so that the


racer only moves forward if the way is clear.

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.

The if functions used to decide whether to move the racers are


getting a bit complex so we have changed the method of dealing
with exceptions. If one racer is too close to the other then we have
simply used the return statement to exit the function without the
move going ahead. The other sections of the go_forward functions
have been tweaked in a similar way. The final if is now not needed;
the racer will move forward if we are still in the function.

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.

Task 3 – Adding Functionality


Now that we have the racers moving within the confines of the track, it’s time to add some other bells and whistles. The
direction you take with this is up to you.

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)

Task 3 – Adding Functionality (cont.)

Start-Finish Line
Create a start-finish line and position your racers behind
this at the start of the game.

We added a turtle to our setup function and ran through


three simple loops to produce our start-finish line. You
might do something better.

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.

Add a condition after moving a racer forward to see if it ends


up in an area around the start-finish line. If so, then add 1 to
your lap count and recreate the display.

The width of the defined area should be greater


than the step your racer takes. If it isn’t, the
racer could step over the area without activating
the lap counter.

Note: The lap counter might trigger multiple


times when the racer passes over them. It
will also trigger when the racer goes over
them in the wrong direction. We will look
at these problems next.

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.

Note: If you have a more complicated track with a choice of routes,


you may need to put in extra checkpoints. This can usually
be avoided.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 7)

Task 3 – Adding Functionality (cont.)

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:

• Checkpoint 2 should only be activated if checkpoint 1 was activated last;


• Checkpoint 3 should only be activated if checkpoint 2 was activated last;
• Checkpoint 1 (i.e. the lap counter) should only be activated if checkpoint 3 was activated last or the
race has just started.

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.

Add code to change the


checkpoint number if the
conditions are met. This
code can run after a racer
has moved on a step.

Print information to the console whenever you need to see what is


happening behind the scenes.

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.

Set up a function called


game_over. The function could
accept a single parameter (in our
case called winner) which is used
to decide what text to display.

Call the function when either


racer reaches the set number of
laps. Remember to pass the
argument to the function so that
it displays the correct text.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.
Race (page 8)

Task 3 – Adding Functionality (cont.)

Starting the Race


Display a message asking for a key to be pressed to begin the game.
This may then start a countdown clock, giving the players a few
seconds to prepare for the race.

a. Create a turtle to display the time. The turtle should be defined


in the main section of the program so that it can be updated from
other functions. Our time is initially set to 3 seconds. The styles
for the turtle can be added to the setup function.

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.

d. The delay will need the time


functions, so import the time module
at the start of your program.

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 starting number (in our case, 3);

• 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.

Extension – Super Challenge

• Timer Add a timer which displays the time the


race has run for. The pieces of code on the
right will help calculate the running time at
any point.
• Obstacles Add more obstacles. They may be temporary and have different effects on the racers.
• Choices Allow the players to decide how many laps the race runs for or what keys to use to control the racers.
Look back at how to validate user input.
• Other Add any other functionality that you think would be fun.

CoP058 – Python Games  ORB Education. Visit [Link] for a range of quality teaching resources.

You might also like