(Smtebooks - Com) Coding Games in Python 1st Edition PDF
(Smtebooks - Com) Coding Games in Python 1st Edition PDF
Games
PYTHON
R
IN
codinG
Games
PYTHON
R
IN
DK UK
Project editor Ben Ffrancon Davies
Senior art editor Sunita Gahir
Consultant editor Craig Steele
Jacket design development manager Sophia MTT
Jacket editor Claire Gell
Producer, pre-production Gillian Reid
Senior Producer Alex Bell
US editors Jill Hamilton, Kayla Dugger
Managing editor Lisa Gillespie
Managing art editor Owen Peyton Jones
Publisher Andrew Macintyre
Associate publishing director Liz Wheeler
Art director Karen Self
Design director Phil Ormerod
Publishing director Jonathan Metcalf
DK INDIA
Senior editor Bharti Bedi
Project art editor Sanjay Chauhan
Editor Tina Jindal
Assistant art editors Rabia Ahmad,
Simar Dhamija, Sonakshi Singh
Jacket designer Juhi Sheth
Jackets editorial coordinator Priyanka Sharma
Managing jackets editor Saloni Singh
DTP designer Sachin Gupta
Senior DTP designer Harish Aggarwal
Senior managing editor Rohan Sinha
Managing art editor Sudakshina Basu
Pre-production manager Balwant Singh
First American Edition, 2018
Published in the United States by DK Publishing
345 Hudson Street, New York, New York 10014
A WORLD OF IDEAS:
SEE ALL THERE IS TO KNOW
www.dk.com
CAROL VORDERMAN MBE is one of Britain’s best-loved TV presenters and is
renowned for her mathematical skills. She has hosted numerous TV shows on
science and technology, from Tomorrow’s World to How 2, and was co-host of
Channel 4’s Countdown for 26 years. A Cambridge University engineering
graduate, she has a passion for communicating science and technology and
is particularly interested in coding.
12 What is Python?
14 Gaming in Python
16 Installing Python
18 Installing Pygame Zero
20 Using IDLE
22 Your first program
28 Creating variables
32 Making decisions
36 Playing with loops
40 Functions
44 Fixing bugs
What is the
capital of France? 7
London Paris
Berlin Tokyo
6 2
Computer programmers are the unsung heroes of the modern world. From smartphones
to laptops, traffic systems to bank cards, their hard work touches almost every aspect
of our lives. Behind each technological advance is a team of creative coders.
Over the past 30 years, computer games have become one of the most exciting and
popular areas of the entertainment industry to work in. Becoming a game programmer
takes creative flair to help create the story, graphics, music, and characters you need
for your games, and the technical know-how to bring them to life. Who knows? This
book may be the very first step on your journey from gamer to game maker.
Learning to code isn’t just for people who want to be professional programmers,
though. Coding skills are useful in lots of different jobs that may seem to have nothing
to do with computers at first. Programming expertise is essential to subject areas as
diverse as science, business, art, and music.
This book uses a programming language called Python®, a fairly simple text-based
language, and is perfect for beginners, or as a step up from Scratch™. However,
unlike Scratch, it was not created especially to teach coding. Python is as popular with
budding coders as it is with professionals, and is one of the most widely used
professional programming languages in the world. It pops up in banking, medicine,
animation, and even space exploration.
The best way to learn any new language is to get immersed in it, and programming
languages are no different. Building your own computer games is a fun way to combine
theory and practice. If you’re a brand-new coder, start off with the basics at the
beginning of this book before moving on to the more complex games as the book
progresses. By following the step-by-step guides, you’ll find out how professional
coders think when they’re building a computer game. Follow those steps carefully and
you’ll have your own games up and running in no time. Then, if you really want to push
yourself, you can try tweaking the code to make your games unique.
Most importantly, have fun! Once you’ve completed the games, you can show them off
to your friends and family—they’ll be amazed by what you’ve managed to make. This
book is packed with games to suit every audience, and we hope you enjoy building and
playing them as much as we enjoyed creating them for you.
1+1=2
◁ Diverse applications
Python is used to build
△ Easy to understand systems and tools for lots of
Unlike some other programming languages, Python interesting tasks in different
doesn’t use complicated symbols. You type the industries, such as banking,
code using a mixture of English words, characters, and healthcare, the space industry,
numbers, so it’s easy to read and write—just like a book. education, and many others.
print("Hello World!")
when clicked This block displays
the message in a Type your
say Hello World! speech bubble. message here.
Hello World!
The message appears
on the screen like this.
Hello World!
△ Print in Python
△ Print in Scratch In Python, the “print” command displays
In Scratch, the “say” block is used to a message on the screen.
display a message on the screen. This command
is executed if
the condition
after if is True. if a == 2:
if a = 2 then This message is
print("Hello!") displayed if the
This message is else: answer is False.
say Hello!
displayed if the
answer is True. print("Goodbye!")
else
This command
say Goodbye!
is executed if the
This is the end of the condition after
“if-then-else” block. if is False.
Goodbye!
Hello! ? Goodbye!
Gaming in Python
Video games are computer programs that
contain a bunch of instructions. Python can
be used to build lots of different types of
games. With Python, there’s something for
every gamer!
Types of games
There are lots of different categories, or
genres, of computer games. These range
from simple one-button games to more ▷ One button
complex strategy ones. Which genre would With Python, you can build fun,
you like to create first? action-packed games that only
need one button to be played.
These games are so addictive,
you’ll want to play them over
and over again.
◁ Puzzles
Puzzles are a great
way to exercise your
brain or test someone’s
general knowledge.
They come in all shapes
and sizes, from jigsaw △ Platform
puzzles to word and Platform games, such as racing games, create
number games. the illusion of speed by making the background
scroll past the player’s viewpoint. The gameplay
generally involves moving around obstacles or
jumping over them.
◁ Strategy
A strategy game is all
△ Multiplayer about decisions. You
Some games you play by yourself, but others let you need to plan ahead
compete against other players. You can use Python to and make the right
build multiplayer games and challenge your friends. choices to win.
GAMING IN PYTHON 15
Python modules EXPERT TIPS
Python has bundles of code called “modules” Downloading modules
that help you complete common coding
tasks. You can use these modules by Python comes with several built-in modules
for developing games, such as Pyglet. But
importing them into your programs.
some other modules, like Pygame, have to
Here are some Python modules that you be downloaded separately.
might find useful.
▽ Pygame
Pygame is designed for writing games in Python.
With this module, you can easily add and control
game characters, update scores and timers, use ◁ Pygame Zero
special animations and graphics, and use gamepads
Pygame Zero is a great module for
and joysticks with your games. It is not a built-in
beginner game programmers. It’s a
Python module, so it needs to be installed separately.
simplified version of Pygame, which makes
it even easier to get started by hiding some
of Pygame’s more complicated features. It
comes with several tools that are useful for
beginners, but it’s also powerful enough
to build some impressive games.
▷ Random
This module can pick a random
number or shuffle a list into a
random order. It is great for
▷ Math adding an element of chance
to a game. Use it when you
Math is a standard Python
want to simulate rolling dice
module that can be used to
or when choosing a random
perform simple calculations
enemy for the player to face.
in games. However, you might
need to use other modules for
trickier calculations.
◁ Tkinter
This tool is used to build
◁ Time simple graphics in games
This module provides tools to to create Graphical
work with time and dates in User Interfaces (GUIs,
a program. For example, you pronounced “goo-eys”)
might need to calculate how that let users interact
many seconds have passed with, and control,
since a game started. Python programs.
16 G E T T I N G S TA R T E D
The games in this book use Python 3. It’s When you install Python 3, you will
free, and you can download it from the also get another free program called
Python website. Follow the instructions IDLE (short for Integrated Development
Environment). Designed for
that match your computer. Never install beginners, IDLE includes a basic
any program unless you have the computer text editor that allows you to write
owner’s permission. and edit Python code.
Z Z Z
Installing Python on Windows
First you need to find out if your computer uses the
32-bit or 64-bit version of Windows. Go to the Start
menu, then Computer, Properties, and choose
System if the option appears.
1 Download Python
Go to www.python.org and click on Downloads. Click 2 Install Python
Open the installer file, then click Custom
on the latest version of Python for Windows. It should Installation, then Next until you get to Advanced
start with the number 3. Select executable installer Options. Leave the checked boxes as they are, but
from the different installer options that appear. make sure “Install for all users” and “Add Python to
environment variables” are also checked. Then
click Install and Next at each prompt.
The version number might not be
exactly the same as this one—just
make sure it has 3 at the beginning. Click the
installer.
1 Download Python
Go to www.python.org and click on Downloads.
Remember this book uses Python 3, so
make sure you open the right version.
Click on the version of Python 3 that matches your You’ll find Python 3 in the Applications
operating system. The “Python.pkg” file will download menu on your Raspberry Pi. Open it
to your Mac automatically. now and check that it works.
The version number might not be exactly
the same as this one—just make sure it
has a 3 at the beginning.
Where should
I plug this in?
• Python 3.6.2 - 2017-08-15
• Download macOS X 64-bit/32-bit installer
2 Install Python
Double-click the “.pkg” file in the Downloads folder
to start the installation. Select Continue and then
Install to accept the default settings.
3 Start IDLE
Once the installation is complete, check that it was
successful by opening the IDLE program. Search for
it in Spotlight or select the Applications folder, then
the Python folder, and double-click IDLE. A window
like this should appear.
Command Prompt
c:\ python -m pip install -U pip
3 Install Pygame
Once the package manager is installed, 4 Install Pygame Zero
Finally, type this command. When you
type the following command and press press Enter, this will install Pygame Zero,
Enter. This uses pip to install Pygame. also known as pgzero for short.
1 Open Terminal
You’ll need to use the Terminal app to >_
This is what the
Terminal app
thumbnail looks like.
install the modules. You can find it in your
Applications folder, or you can search for
it with Spotlight. Follow the steps below,
making sure all the spellings are correct Type this line carefully in the
and the spaces are in the right place. Terminal window and check for any
spelling errors and extra spaces.
that makes it easier to install Pygame Zero Last login: Thu Sep 14 11:22:51 on ttys000
and other Python modules. Type in the LC-0926:~ rzvz ruby -e "$(curl -fsSL https://raw.git
command at right and press Enter to
install Homebrew. It might ask you to hubusercontent.com/Homebrew/install/master/install)"
enter your password again, and it will take
a short while to install, so don't panic if This should fit
nothing happens right away. on one line when
you type it in.
5 Install Pygame
Now it’s time to install Pygame. Type
pip3 install pygame
Pygame Zero.
20 G E T T I N G S TA R T E D
Shell window
△ Give the shell a test run
Type each of these code snippets into the shell window
Editor window and press Enter after each one. The first line displays a
message and the second line does a calculation. Can you
figure out what the third line does?
USING IDLE 21
The editor window ▽ The editor window
The shell window can’t save your code, so when you To open the editor window
close it, the code you typed is gone forever. When you in IDLE, click on the File menu at
are working on a game, you should use IDLE’s editor the top and choose New File.
An empty editor will then appear.
window. This will let you save your code. It also has You’ll use the editor window to
built-in tools to help you write your programs and write the programs for the games
troubleshoot any errors. in this book.
You type in the code The name of the You can run Python programs from
here. This program file is shown here. this menu, but you will run Pygame
prints a list that tells Zero programs a different way.
you which numbers
are even and which
EvensandOdds.py
ones are odd.
IDLE File Edit Format Run Window Help
The menu bar for
for count in range(10): the editor window is
different from the one
if ((count % 2) == 0):
for the shell window.
print(count)
Anything you tell
Python to print print("is even")
gets displayed in
the shell window. else:
print(count)
print("is odd")
EXPERT TIPS
Colors in the code
IDLE automatically colors Symbols and names Output
the text to highlight Most code text is colored Any text produced when
different parts of the code. black. a program runs is blue.
The colors make it easier to
understand the code, and
they’re useful when you’re Built-in commands Keywords
trying to spot mistakes. Python commands, Certain words, such as if and
such as print(), are else, are special Python keywords.
shown in purple. They are shown in orange.
How it works
This Python program will check if everything Start
1 Set up a folder
Before you start, create a folder called python-games
somewhere easy to find, such as on your Desktop.
Create another folder within your python-games
folder and call it hello. End
2 Start IDLE
Open IDLE on your
File
Hello!
computer. From the New File
File menu, choose
New File to create an Open...
empty editor window
where you can write Open Module...
your program.
Recent Files ▶
Class Browser
YO U R F I R S T P RO G R A M 23
def draw():
def draw():
EXPERT TIPS
Cancel Save
Hey, grab on!
I’ll save you!
EXPERT TIPS
Saving your code
Always save your code before you run it,
especially after you make any changes.
If you don’t, Python will run an out-of-date
version of your code.
24 G E T T I N G S TA R T E D
IMPORTANT!
Fix mistakes
If nothing happens when you run one of your programs, or if you
get an error message—don’t panic! It’s normal to experience I think there’s some bug
errors (these are called “bugs”) when coding a program. If an error spray on pages 44–47!
message appears, ask yourself the following questions:
P Y T H N
O
28 LEARNING THE BASICS
Creating variables
Variables are used to store and label pieces
of information. You’ll use them a lot in your
code—for example, to hold your current score
or keep track of how many lives you have left.
1 Assign a value
Open IDLE’s shell window. Type this line
>>> score = 0
1 A simple calculation
Type this code into the shell window. It 2 Change a value
To change the value of a variable, just assign a
uses two variables, x and y, which store new value to it. In this code, assign the value 5
integers to perform a simple calculation. to x. Print the value assigned to y again. What
Press Enter to see the answer. do you think the result will be?
LINGO
1 Strings in variables
Strings can be assigned to variables. Type this code
>>> name = "Martin"
>>> print(name)
Quotation marks
tell the computer
into the shell window. It assigns the string Martin that it’s a string.
to the name variable and then displays it. Strings Martin
must be written between quotation marks to show
where they start and end. Press Enter to
print the string. Remember the space
after the greeting.
EXPERT TIPS
Length of a string
For some programs, it’s useful to be able to count
the number of characters in a string. You can do
this using the function len(). A function is a useful
operation that contains multiple lines of code,
so you don’t have to enter them manually. To
find out the number of characters in the string
Hello Martin, type this line of code into the shell What’s the weather
after you’ve created the string, then hit Enter. like up there?
The number
>>> len(message)
of characters,
including spaces,
is counted.
!
12
C R E AT I N G VA R I A B L E S 31
Making lists
A list is used to store a collection of data. It can
hold many different values and keep them in order.
For example, a list can store a deck of cards for a
game, such as Snap, so the code knows which card
to deal next. The position of each value in the list
is identified with a number, starting from 0. You
can use these numbers to change list values.
2 List in a variable
It would be much easier to use a list to store all the
values of the cards instead of setting up so many
variables individually. To create a list, surround the The values must be
values you want to store with square brackets. separated by commas.
>>> cards = ["1 hearts", "2 hearts", "3 hearts", "4 hearts", "5 hearts", "6 hearts"]
Making decisions
Playing a game involves making decisions
about what to do next. These are often
based on answers to questions. For
example, “Do I have any lives left?”; “Is
someone chasing me?”; “Have I beaten
the highest score?”
Comparisons
Computers also make decisions about what to Which door should
do next by asking questions. These questions we go through?
△ Boolean values
EXPERT TIPS
The questions that computers ask only
have two possible answers: True or False. Equals signs
Python calls these two values Boolean
values, and they must always start with In Python, there are two types of equals sign: a single equals
a capital letter. You can store a Boolean sign = and a double equals sign ==. These signs have different
value in a variable. meanings. You use a single equals sign when you want to store
a value in a variable. For example, lives = 10 stores the value
10 in the variable lives. However, use a double equals sign
when you want to compare two values.
Symbol Meaning
This sets the
== equal to value of This compares your
the variable. age with the variable.
!= not equal to
< less than >>> age = 10
> greater than
>>> if age == 10:
Level up
Imagine you’re creating a game that has two levels. To get
to Level 2, you need to have at least four magic snails and
a score of more than 100 points. At this point, you have L2
110 points but only three magic snails. Use the shell L1
window to see if you can still get to Level 2. First, create
variables for the score and number of snails collected and
assign the correct values to them. Then type the rules for
getting to Level 2 as a Boolean expression.
Branching
Sometimes you need to make decisions when
playing a game. Should you turn right to
investigate the library or turn left to look at
the kitchen? Computer programs often contain
code that runs only in certain situations. This
means the computer makes decisions about
which parts of the code to run.
Behold! I grant
thee the title... game_over = True
Enchanter!
if game_over:
This block runs
print("Game Over!") if the condition
is False.
else:
print("Keep playing!")
“For” loops
When you know exactly how many times you
Loop variable
want a loop to repeat, you can use a for loop. In
The loop variable keeps track of how many
this example, the code prints “You are the high times the loop has run so far. At the start of the
scorer!” ten times. Try out the code for yourself loop, it’s equal to the first number in the range.
in the shell window. The second time around, it’s equal to the
second number in the range, and so on. Once
>>> for count in range(1, 11): it completes the second-to-last number in the
range, the loop stops.
print("You are the high scorer!")
Loop body
The block of code that gets repeated in a loop is
called the loop body. You must always indent the
commands in the body four spaces from the
beginning of the line that starts the for loop.
P L AY I N G W I T H L O O P S 37
Looping over a list Page 31 will
Gaming programs often use a collection help you out
with lists.
of items grouped together in a list. If you
want to do something with each item
on the list, you can use a for loop.
Listing robots
In this example, there is a list that contains Python will add
the names of three robots that the player one of the robots’
has to escape from in a game. names here.
How it works
>>> robots = ["Bing", "Bleep", "Bloop"] We create a temporary variable called
robot that holds a single item in the
>>> for robot in robots:
list. The value in robot is updated
print("I am a robot. My name is " + robot) each time around the loop, so that it
holds Bing, then Bleep, and finally
robot is a temporary variable Bloop. Once it reaches the end of the
that moves along the robots list, the loop stops.
list each time the loop runs.
How it works
robots[index] and colors[index] both use the value
of index to decide which item in their list to print.
Since index is set to 0 to begin with, both lists will
start with the first item—remember the first position
in Python lists is always 0, not 1. Since Bing is at
position 0 of the list robots and red is at position 0
of the list colors, that means Bing is red. Each time
the loop runs, it adds 1 to index, moving each list
onto the next item, so Bleep will be orange and
Bloop will be purple. The loop will continue until
it reaches the end of the lists.
Loop condition
A while loop includes a question whose answer can either
be True or False. This is called a loop condition. The while
loop will only start if the answer to the loop condition is
True. Imagine you are playing a game where a castle is
guarded by a dragon that checks if you have the magic
key. “Do you have the magic key?” would be the loop EXPERT TIPS
condition and the castle would be the loop body. If you
have the magic key, the loop condition is True and you Indentation error
can enter the castle. But if you don’t have the key, the
loop condition is False, so you can’t get into the loop! Just like the for loop, the code in
the body of a while loop must be
four spaces further in than the line
starting the loop. If you don’t do this,
Python will show an error message
saying “unexpected indent.”
Nobody enters without
the magic key!
SyntaxError
unexpected indent
OK
P L AY I N G W I T H L O O P S 39
Balloon fight This line gets the value of
In this example, the answer (used in loop condition).
program asks if you want
to throw a water balloon. answer = input("Throw a water balloon? (y/n)")
If your answer is y, it prints while answer == "y":
“Splash!!!” and asks if you
want to throw another print("Splash!!!")
balloon. If your answer answer = input("Throw another water balloon? (y/n)")
is n, the program prints
print("Goodbye!")
“Goodbye!” and ends.
Making an escape
If you don’t want to run an infinite loop,
it’s important to make sure the body of a
while loop does something that could make
the loop condition False. But don’t worry if
you accidentally code a program with an
infinite loop—you can escape it by holding
down the Ctrl key and pressing the C key
along with it.
40 LEARNING THE BASICS
Functions LINGO
Function terms
Functions are really handy tools for all coders. Call When you want to use a
They let you name useful chunks of code so function, you “call” it by typing
that you can use them over and over again the name of the function,
followed by parentheses, which
without having to type the whole thing out may contain a parameter.
each time—you just have to type in the name!
Python comes with some built-in functions, Define When you use the
def keyword and write your
but you can also write your own to handle own code for a function, you
tasks specific to your games. are “defining” that function.
Parameter A parameter is
Using functions a piece of data (information)
When you want to use one of Python’s built-in functions, that you give a function to use.
all you need to do is “call” it by typing out its name Return value A return value
followed by a pair of empty parentheses. This tells Python is data that you pass from a
to run the code saved in that function. If you need to function back to the main code
give a function some data to use, it goes inside the by using the keyword return.
parentheses. This is called a “parameter.”
Built-in functions
Python comes with a number of built-in functions.
They allow you to perform a variety of tasks, from
printing messages to converting one type of data
to another.
This calls the print() function
with a string parameter.
△ print()
One of the most commonly used functions is print().
This function lets you display a string (a series of
letters, numbers, or other characters) on the screen.
The string is a parameter in this case.
FUNCTIONS 41
▷ input() This is a variable input() asks the
that will later store user what their
This function lets the player enter information for the
the player’s name. name is.
game to use, rather than the coder putting it in the
original code. For example, imagine you’re creating >>> name = input("What is your name?")
a game and you want to create a variable to store What is your name?Ben
the player’s name, but you don’t know what they’re
called. You can use input() to make the game ask the >>> print(name)
player what their name is. Their answer becomes a You can type your
Ben
own name in here.
return value, which the function will then assign to
the name variable. input() has assigned the
answer to the name variable.
The string fun appears twice. This is the new string, all in capitals.
△ count() △ upper()
This function is used with strings. It is called on one This function takes an existing string and returns a new
string, with another string as a parameter of the string, replacing all the lowercase letters with uppercase
function count(). The return value tells you how many (capital) letters.
times the second string appears in the first string.
The reverse function
A list of numbers is is called on the list
assigned to a variable. of numbers. The function has two parameters,
which are separated by a comma.
>>> countdown = [1, 2, 3]
>>> countdown.reverse() >>> message = "Coding makes me happy"
>>> print(countdown) >>> message.replace("happy", ":D")
[3, 2, 1] 'Coding makes me :D'
△ reverse() △ replace()
You can also call a member function on a variable. For this function, you need two parameters—the first is
In this example, the function reverse() is used the part of a string you want to replace, and the second
to reverse the order of the list of numbers stored is what you want to replace it with. The function returns
in the variable countdown. a new string with the replacement made.
42 LEARNING THE BASICS
return 5
Error... error!
The values are returned for
use later in the code. They
will not appear in the shell.
return 5
apple_score = fruit_score("apple")
orange_score = fruit_score("orange")
15
44 LEARNING THE BASICS
Error alert
In IDLE, both the editor and shell windows ▽ Messages in Command Prompt/Terminal
can display an error message when something Error messages in Pygame Zero are shown in
the Command Prompt or Terminal window.
unexpected happens. This message highlights When an error is discovered, the program will
the error and shows you which line of code stop running and will tell you what the error is
to find it in. and where to look for it in the code.
EXPERT TIPS
Catching bugs
When you see an error in the Command
Prompt (Windows) or Terminal (Mac), look at
the line number. Go back to your code in
IDLE and click anywhere in the file. The line
number will be displayed at the bottom-
right corner of the screen—for example,
Ln: 12. Then use the Up or Down arrow
to find the line with the error in it.
FIXING BUGS 45
Syntax errors
The structure of statements used in a coding
language is known as syntax. A syntax error means
that you’ve typed something wrong. You could have e
missed a part of a statement or misspelled a word.
Syntax errors are the easiest mistakes to fix. Go to the
line with the error and change what you’ve mistyped.
H l l o !
▷ Mistakes to print(score
watch out for The closing
Do your opening and parenthesis is missing.
closing parentheses match?
Are you missing a quotation horse = Actor("horse) The closing quotation
mark? Have you spelled mark is missing.
everything correctly? These This is a spelling mistake. It’s supposed
are the main causes of hrse.draw() to be referencing the variable named
syntax errors. “horse,” so it should be horse.draw().
Type errors
Sigh! I really thought
These errors occur when you put the it would work.
wrong type of data in the code. For
example, if the code is expecting a number
but you give it a string, it won’t work.
?
players = ["Martin", "Craig", "Claire", "Daniel"]
find_highest_score(players)
Name errors
Is this No, it’s
a date? a pear. A name error occurs when you try
to use a variable or function that hasn’t
been created yet. To avoid this, you
must remember to define all variables
and functions before using them.
▷ Fixing logic
Logic errors can be the hardest to find and fix. You can
only get better at it with more experience. To make logic
errors easier to find, run your code frequently to test it.
If you think there is an error, go through each line of
code carefully. For example, when checking the value
assigned to a variable at different stages in the program,
try using a print() statement to spot any errors.
EXPERT TIPS
Bug-busting checklist
Coding can get frustrating Ask yourself...
▪ Have you typed the code exactly as it is in the book? Pay extra
sometimes, and you might feel
as if you’ll never be able to find attention to indentation and spaces.
a solution. But don’t give up! ▪ Is everything spelled correctly?
If you follow the tips in this ▪ Do you have extra spaces at the start of a line?
handy checklist, you’ll be able ▪ Have you confused any numbers for letters, such as 0 and O?
to identify most errors. ▪ Have you used the correct case for all the letters?
▪ Do opening parentheses have a matching closing parenthesis? () [] {}
▪ Does every quotation mark have a matching closing quotation mark?
Should I be ▪ Have you asked someone else to check your code for you and
worried?
compare it with the book?
▪ Have you saved your code since you last made changes?
Shoot
the Fruit
50 SHOOT THE FRUIT
How to build
Shoot the Fruit
This simple shooting game is a fun way to practice
your aim. When the apple appears, click on it to
”shoot” it. Aim carefully though, because if you
miss, the game is over!
What happens
When the game starts, an apple appears on the screen
for you to “shoot.” If you hit it, a “Good shot!” message
pops up, and the apple appears at another point on
the screen. But if you miss, a “You missed!” message is
shown, and the game ends.
◁ Aim... Fire!
You need to stay
alert at all times while
playing this game.
Lose your focus and
you may miss the shot!
HOW TO BUILD SHOOT THE FRUIT 51
How it works Start
The game is constantly checking whether
you’ve clicked the mouse button. Every
time you click on the apple, it needs to be
drawn again somewhere else on the screen.
Draw an apple
If you click and miss, the game will end. on the screen
Oops! I missed
again!
Player clicked
the mouse?
N Y
N Y
▷ Shoot the Display Player clicked Display
Fruit flowchart “You missed!” on the apple? “Good shot!”
This flowchart shows
the logic behind the
game. The main part End
of the code is a loop
that checks if you have
clicked on the apple or not.
Get shooting!
Are you ready to code? In this program,
you’ll start by drawing an apple on the screen,
then you’ll learn to place it at random points before
you start shooting it. Ready? Let’s get coding!
1 Open IDLE
Create an empty file
File
in IDLE by going to New File
the File menu and
choosing New File. Open...
Open Module...
Recent Files ▶
Class Browser
52 SHOOT THE FRUIT
Clean up by ▶
Cancel Save
shoot-the-fruit
This creates
shoot.py a new Actor
This is such
images called apple.
an honor!
apple.png
LINGO
I wish my Actors and Sprites
folders were
more organized. In computer games development,
a sprite is an object, like a coin or an
enemy character, that is controlled by
code. Actors in Python are like Sprites
in Scratch. An Actor can be drawn on
the screen, moved around, and even
interact with other Actors in the
game. Each Actor is given a “script”
(the Python code) to tell it how to
behave in the game.
GAME PROGRESS 53% 53
8 First screen
If your code is working properly, you 9 Placing the apple
At the moment, the apple appears in the
should see this screen. If it’s not, or if top-left corner of the game window. You can
you get an error message, go back and change the code to place the apple exactly
check your code to find any bugs. where you want it on the screen. Write this
function, which will place the apple at the
coordinates (300, 200).
Pygame Zero Game
apple.draw()
A blank game
window with def place_apple( ):
an apple in the The apple will be
top-left corner apple.x = 300 placed 300 pixels
of the screen along the x-axis
apple.y = 200
should appear. (horizontal).
EXPERT TIPS
Graphics in Pygame
Python uses coordinates to identify all the (0, 0) 20 40 60 80 100 120 140
places in a window where an object could be.
20
This means that every place can be identified
by using two numbers. The first number is 40
y getting bigger
the x coordinate, which shows how far to the 60
right an object is. The second number is the
80
y coordinate, which shows how far down
the object is. Coordinates are written in 100
parentheses, with the x coordinate first, like this: 120
(x, y). In math, the coordinate (0, 0) is usually These are the
140 coordinates
at the bottom left, but in computer graphics, (130, 140) of the star
it’s almost always the top left. on screen.
x getting bigger
(300, 200)
GAME PROGRESS 76% 55
This function
checks if the
Make sure the bottom cursor is in the
two lines now start same position
with eight spaces. as the apple.
START
Whoa!
Good shot!
56 SHOOT THE FRUIT
16 Using Random
Change the code you typed in Step 9 to look like 17 Time to shoot!
You did it! Run your program to play the game.
this. The code will now use the randint() function Each time you “shoot” the apple, it will move
to pick a random number between 10 and 800 for to a random place on the screen for you to
the x coordinate and a random number between “shoot” again.
10 and 600 for the y coordinate.
EXPERT TIPS
Random numbers
Rolling a dice, picking a card from a deck,
or tossing a coin are all actions that you Pick a card,
can simulate by generating a random any card.
number. You can read more about how to
use Python’s Random module by going to
the Help menu and clicking Python Docs.
GAME PROGRESS 100% 57
△ Keep on playing
kiwi = Actor("kiwi")
This game is fun for people who want to practice
using a mouse. However, it could get frustrating
△ Fruit salad if the game quits every time you click in the
The Actor doesn’t need to be an apple! Find a picture of wrong place. Can you find the command that
another fruit in the Python Games Resource Pack or create quits the game and remove it to make the game
one using an 8-bit editor online. Make sure you’ve got a easier to play?
suitably sized image before you save it in the images folder.
Then name the image and change the code accordingly to
use the new fruit as an Actor.
SHOOT THE FRUIT
△ Keep count
Change your code so that it can keep count of the number
of times you click successfully. Here are some hints to
help you out.
▪ Store the count in a variable. △ Don’t shoot!
▪ Start by setting the variable to 0. Why not add another Actor to the game to
▪ Increase the count by 1 each time you click on the apple. distract the player in the hope they’ll click on
▪ Use print() to show the score in the Command Prompt that object by mistake? For instance, a red ball
or Terminal window each time the apple is drawn on might look similar enough to an apple to fool
the screen. the player!
Coin
Collector
60 COIN COLLECTOR
Coin Collector
collect some more!
What happens
A fox and a coin appear on the screen. You use the arrow
keys to move the fox toward the coin. When the fox
touches the coin, you get ten points, and another coin
appears somewhere else. The game ends after seven
seconds and the final score is displayed.
Score: 0
The fox can
move up, down,
left, and right.
The coin
can appear
anywhere on
the screen.
▷ Coin Collector N
flowchart
The main loop in this
Is the fox
Y
flowchart checks if the Place the coin
touching the Increase the score
the time is up, whether somewhere else
coin?
any arrow key is being
pressed, or if the fox is
touching a coin. N
Getting started
Follow these steps to build the game. Treasure Hunt
First set up a new file and import the
relevant modules. Then draw the Actors
and define the functions to run the
game. Good luck!
1 Get set up
Create a new folder called coin-collector. Then
Save As:
Tags:
coin.py
Cancel Save
62 COIN COLLECTOR
Clean up by ▶
Sort by ▶
4 Get coding
Now you’re ready to start coding. This game works 5 Setting the score
Now, let’s set the score to zero to begin with.
in a similar way as Shoot the Fruit, so you’ll be able You’ll need to use a variable to do this. Type
to reuse some of the code from that game. Begin the code shown in black below.
by setting the size of the playing area. Type this
code at the top of your file. WIDTH = 400
HEIGHT = 400
WIDTH = 400
score = 0
HEIGHT = 400 This code will make the
game screen 400 pixels This sets up a variable
tall and 400 pixels wide. called score.
LINGO
Patterns
Lots of computer games follow patterns.
Even though two games might have different
characters, power-ups, or levels, their actual
rules may be quite similar. Computer
programmers often look for patterns in
the programs they are building. If they
spot a pattern, they can reuse some code
from an existing program, making it easier
and quicker to build the new program.
This code is also less likely to have bugs
because it will already have been tested.
GAME PROGRESS 48% 63
6 Game over?
You also need a Boolean variable (a variable
WIDTH = 400
HEIGHT = 400
whose value can either be True or False) to tell
Pygame Zero if the game is over or not. At this score = 0
stage, set the variable to False.
game_over = False
8 Time to draw
Now you need to use the draw() function
to display the Actors on the screen, change These lines draw
the background color, and display the the fox and coin
score. Type in this code to do these. on the screen.
def draw():
screen.fill("green")
fox.draw() This line will
display the
coin.draw() score in the
screen.draw.text("Score: " + str(score), color="black", topleft=(10, 10)) top-left corner
of the screen.
10 Did it work?
Did your game run? You should see the fox
and coin on your screen, with the score in
the top-left corner. You can’t actually play the
game yet, but it’s a good idea to run your
code frequently to check for bugs.
64 COIN COLLECTOR
11 Using placeholders
You need to write some more functions in order to The next question
finish the game. You can add function placeholders
without having to define them right away by using
is... What is
a function? ?
the keyword pass. Type in this code to give yourself
a template of the functions you’ll need.
Err... pass!
coin.draw()
screen.draw.text("Score: " + str(score), color="black", topleft=(10, 10))
def place_coin():
pass
def update():
pass
12 Importing randint()
Now it’s time to define these functions. The 13 Placing the coin
Next change the code in your place_coin()
first one will use Python’s built-in randint() function. This function will place the coin
function, so you need to import it into your in a random position on the screen. Delete
program. Type this line at the very top of pass and type in these commands.
your code to import it.
def place_coin():
from random import randint coin.x = randint(20, (WIDTH - 20))
coin.y = randint(20, (HEIGHT - 20))
Make sure you type this before all
the code you’ve written so far.
The coin will be placed at least 20 pixels
in from the sides of the screen.
function; you have to run it, too. Add this line Pass
of code to the very bottom of your game.
In Python, if you’re not sure what code
def update(): This will run the you want inside a function yet, you can
code you’ve saved use the pass keyword in its place, and then
pass in the place_coin() come back to it later. It’s a bit like skipping
function.
a question in a quiz but answering it later.
place_coin()
GAME PROGRESS 86% 65
15 Time’s up!
Now let’s fill in the code for the time_up() function. 16 Set the timer
Now that time_up() is defined, the program needs
In this function, set the game_over Boolean to run it. But it needs to run seven seconds after the
variable to True, which will tell the program to game starts. You can use Pygame Zero’s built-in tool
quit the game when the function is called. Type clock to do this. This tool lets the program call a
in the following code. function after a specified amount of time. Add this
line in the code as shown here.
def time_up():
clock.schedule(time_up, 7.0)
global game_over
place_coin()
game_over = True
def draw():
screen.fill("green")
fox.draw()
coin.draw()
screen.draw.text("Score: " + str(score), color="black", topleft=(10, 10))
if game_over:
screen.fill("pink")
screen.draw.text("Final Score: " + str(score), topleft=(10, 10), fontsize=60)
If the variable game_over The final score is This command sets the size of
is True, this will turn the shown on the screen. the text shown on the screen.
screen pink.
Using update()
18 The final function you need to define is update(). This is
def update():
if keyboard.left:
a built-in Pygame Zero function, which means that unlike
the other functions, you don’t need to worry about when fox.x = fox.x - 2
to run it. Once you’ve defined it, Pygame Zero will run
it automatically—60 times a second! Delete pass under
def update() and add this code. It will move the fox to This moves the fox two pixels to
the left if the left keyboard arrow is pressed. the left if the left arrow is pressed.
66 COIN COLLECTOR
elif keyboard.down:
fox.y = fox.y + 2
21 Game complete!
You’ve written all the code, and your game is now
coin_collected = fox.colliderect(coin)
ready to go! Test your game and see how many
coins you can collect before the game is over.
if coin_collected:
score = score + 10
clock.schedule(time_up, 7.0)
place_coin()
This will
increase the
score by ten.
GAME PROGRESS 100% 67
I think I can
go faster.
if keyboard.left:
fox.x = fox.x - 4
elif keyboard.right:
fox.x = fox.x + 4
elif keyboard.up:
fox.y = fox.y - 4
elif keyboard.down:
fox.y = fox.y + 4
△ Go faster!
You can tweak the code to make the fox move
△ Change the playing area faster. For this, you’ll need to change some of the
You can change the size of the playing area by changing code in the update() function. At the moment, the
the values of WIDTH and HEIGHT. Try using different fox moves two pixels every time the arrows are
numbers for these values and see what happens. Can pressed. Here’s a way to make it move at double
you spot which part of the code you need to update? that speed.
Follow the
Numbers
1
12 2
3 3
70 FOLLOW THE NUMBERS
What happens
At the beginning of the game, ten dots appear
at random positions on the screen, each with a
number next to it. You need to click on the dots in 1
the correct order to connect them. The game will
finish once you’ve connected all the dots together.
But if you make a mistake, all the lines will disappear
and you’ll have to start from the very first dot again.
9
Each dot has a number
label under it.
Y
This is easy... Just
follow the numbers!
Y
Was it the
first dot?
1
12 2
3 3 N
Really? I still
don’t get it! N
▷ Follow the
Numbers flowchart
1 This game checks to see if
31 2 the player has clicked on a
dot and if that dot matches
2 3
the value in the next_dot
variable. The program will
continue to run until there End
are no more dots to connect.
GAME PROGRESS 33% 73
Let’s get started
It’s time to start building the game. Begin by
importing the Python modules required for this game.
Then write the functions to create the dots and the lines.
One piece at a time!
1 Set it up
Open IDLE and create
File
an empty file by going New File
to the File menu and
choosing New File. Open...
Open Module...
Recent Files ▶
Class Browser
dots.append(actor)
def draw():
screen.fill("black")
This creates a variable number = 1 These lines draw
to keep track of the each dot on the
current number label. for dot in dots: screen along with
a number label.
screen.draw.text(str(number), \
(dot.pos[0], dot.pos[1] + 12))
dot.draw()
number = number + 1
number = number + 1
for line in lines:
screen.draw.line(line[0], line[1], (100, 0, 0))
EXPERT TIPS
Line function
This function draws a line between two points
screen.draw.line(x, y, (0, 0, 100))
on the screen—starting at point x and ending
at point y. You can change the color of the line
These numbers can change
to red (R), green (G), blue (B), or even a mix of depending on the color
all three (RGB). Create a color by assigning you choose for the line.
values between 0 (none of the color) and How about royal blue?
255 (the maximum amount of the color). For Or pink? Better check
example, (0, 0, 100) sets the color of the line to pages 114–115 for their
blue. You can use some colors by typing in RGB values.
their names, but RGB values let you use lots of
different shades.
76 FOLLOW THE NUMBERS
7
Oh, I can finally see
them! There are ten
2 3 dots in all.
4
1
6
10 5
The position of the
dots will change
9 each time you run
8 the code.
GAME PROGRESS 100% 77
to the mouse clicks. Add these lines under This line checks if the player has
def on_mouse_down(pos) from Step 13. already clicked on the first dot.
global lines
if dots[next_dot].collidepoint(pos):
if next_dot:
lines.append((dots[next_dot - 1].pos, dots[next_dot].pos))
next_dot = next_dot + 1 This draws a line
between the
else: current dot and
This sets next_dot the previous one.
lines = [] to the next number.
next_dot = 0
dot = Actor("dot")
Here goes...
def on_mouse_down(pos):
if dot.collidepoint(pos):
print("Ouch")
△ No more chances
At the moment, the player has an unlimited
number of attempts to connect the dots
together. Try changing the code so that the
game ends if the player makes a mistake. You
could even add a “Game Over!” message to
your code. If you do this, remember to clear
everything else off the screen first.
△ More dots
You can add more dots to the game to make it
more challenging. Remember the loop in Step 8
that creates ten dots? Can you modify the range
to create some more?
▷ In record time
You can use the system clock to time how long it takes
a player to connect all the dots. You could then try to from time import time
beat your friends’ times! To time the game, you’ll need
to use the time() function. Once the game is complete, Put this code at the top
you can display the final time taken on the screen. Why of your program to use
not try placing the clock in the corner? Remember to the Time module.
use str() to cast the message into a string. You can
check Step 9 of the game if you need to remind yourself def update():
how to do this. At the moment, though, the draw()
function is only called when the player clicks the pass
mouse, so the clock would only update after each
mouse click. To fix this, add this code. This function is You don’t need to replace
called 60 times a second. Each call also calls the draw() pass with any actual code.
function, so the clock stays up to date.
How to build
Red Alert
You’ll need lightning-fast reactions to
beat this game. Click on the red star
Pygame Zero Game
to keep the game moving. Anything
other than red will land you in trouble.
What happens
When the game begins, two stars appear
and start moving down the screen. The
player needs to click on the red star before
the stars reach the bottom of the screen.
Each time the red star is clicked, the game
moves on to the next level. With each level,
more green and blue stars are added and
they move faster than before. If the player
clicks on any star other than the red one, or
if the stars reach the bottom of the screen,
the game ends.
The number of
stars increases
with every level.
◁ Stars
This game uses three colors
for the star Actors—red,
blue, and green.
HOW TO BUILD RED ALERT 83
◁ Shooting stars
The program uses Pygame
Zero’s animate() function to
move the stars down the screen.
You can adjust the duration of
the animation to make the game
more interesting. The stars can
fall as slowly or as quickly as
you like!
84 RED ALERT
N
Y Y
Is this the Has a star been
Is it red?
final level? clicked on?
Y N N
Y N
Has a star reached
End the bottom of the
screen?
File
Save As: red.py
New File
Tags:
Open...
Where: red-alert
Open Module...
Recent Files ▶
Cancel Save
Class Browser
Sort by ▶
86 RED ALERT
5 Import a module
The first thing you need to do is import
import random
Constants
Constants are variables whose
value shouldn’t change after
they are first set. Programmers
use capital letters when naming
them to let other programmers
know not to change their values.
This is known as a “naming
convention”—a rule that most
programmers agree on, so that
everyone’s code looks similar
and is easier to understand.
current_level = 1
These are the global
stars = [] variables used in
animations = [] this function.
def draw():
This adds a
global stars, current_level, game_over, game_complete background
screen.clear() image to the
game window.
screen.blit("space", (0, 0))
if game_over:
display_message("GAME OVER!", "Try again.") When the game is
over or complete,
elif game_complete:
this block displays
display_message("YOU WON!", "Well done.") the relevant message
on the screen.
else:
for star in stars:
This block draws the
star.draw()
stars on the screen.
88 RED ALERT
def make_stars(number_of_extra_stars):
colors_to_create = get_colors_to_create(number_of_extra_stars)
This function uses the list
new_stars = create_stars(colors_to_create) of colors as a parameter
and creates Actors for
layout_stars(new_stars)
each star.
animate_stars(new_stars)
return new_stars
This function puts the stars in This function makes the stars
the right position on the screen. move down the screen.
GAME PROGRESS 54% 89
11 Add placeholders
You’ll need to define all the
return new_stars
def animate_stars(stars_to_animate):
pass
def get_colors_to_create(number_of_extra_stars):
colors_to_create = ["red"] This chooses a
This makes the first random color
star in the list red. for i in range(0, number_of_extra_stars): from the list for
each additional star.
random_color = random.choice(COLORS)
colors_to_create.append(random_color)
i refers to the current This adds the new
number in the range. return colors_to_create color to the list.
90 RED ALERT
14 Create the stars This list will store the new This loops over the
Now you need to create the stars on the screen. stars that are created. colors_to_create list.
Start by making an empty list called new_stars.
Then loop over the colors in the colors_to_create def create_stars(colors_to_create):
list. With each loop, the code will create a new new_stars = []
star Actor for the current color and add it to
for color in colors_to_create:
the new_stars list. Replace return [] under
def create_stars(colors_to_create) star = Actor(color + "-star")
with the code shown in black. new_stars.append(star)
return new_stars
15 Try it out
Check your code to Pygame Zero Game
make sure no bugs
have crawled in. Save
your code and run it
from the command
line. What do you see
on the screen?
17 Test again
Run the program one Pygame Zero Game
more time to see what’s
changed in the code.
bottom-left
anchor
mid-right (0, 0)
anchor
top-left
This works out the duration of the animation by anchor
subtracting the current level from the default
start speed of the star. The higher the level, the
shorter the duration, so the faster the animation.
def animate_stars(stars_to_animate):
for star in stars_to_animate:
duration = START_SPEED - current_level
star.anchor = ("center", "bottom")
animation = animate(star, duration=duration, on_finished=handle_game_over, y=HEIGHT)
animations.append(animation)
19 Game over
Next you need to define the handle_game_over()
function, which will end the game if the player makes Game over?
a mistake. Type the code shown in black after the It can’t be true!
GAME OVER!
code from Step 18.
animations.append(animation)
def handle_game_over():
global game_over
game_over = True
GAME PROGRESS 83% 93
EXPERT TIPS
Animate function
animate() is a very useful function in Pygame ▪ on_finished= This is an optional parameter that
Zero’s library. It makes it really easy to move an allows you to pass a function that you want to call
Actor on the screen. This function takes a once the animation is finished. In Red Alert, you
number of parameters: use this parameter to end the game when the star
reaches the bottom of the screen.
▪ The first parameter is always the Actor that you ▪ The final parameters are the properties of the Actor
want to animate. you want to animate. There can be more than
▪ tween= This optional parameter can be used to one property. For example, if the Actor is at (0, 0)
change the behavior of the animation. coordinates and you want to move it to (100, 0), the
animate() function will move the Actor to the right by
▪ duration= This parameter is the number of seconds
100 pixels. This move will be smooth and will last as
the animation lasts for. many seconds as you set the duration parameter.
(0,0) (100, 0)
handle_game_over()
23 Display messages
Finally, add some code that displays the message you wrote
in Step 8 when the game comes to an end. Add these lines
under the code from Step 22.
animation.stop()
24 Time to play!
That’s it! Save your Pygame Zero Game
program and run the
IDLE file from the
command line to
start playing. How
many levels can you
complete?
96 RED ALERT
Bharti wait!
I can change.
◁ Change the Actor
You can change the way your game
looks by simply changing the star Actor.
Find another image of an Actor in the
Python Games Resource Pack, or create
your own by using an 8-bit editor online.
Don’t forget to update the name of
the Actor in the code.
random_speed_adjustment = random.randint(0,2)
duration = START_SPEED - current_level + random_speed_adjustment
star.x = new_x_pos
◁ Two directions
If you want to keep the players on their toes, you can make the
if index % 2 == 0: stars appear from the opposite direction. First you’ll need to
star.y = 0 add the code shown here to the layout_stars() function. This will
check if the current index number is odd or even. When it’s odd,
else:
the stars will appear at the bottom. Next you’ll need to update the
star.y = HEIGHT animate_stars() function to make the stars move from the bottom
to the top. Remember to update the star’s anchor.
HACKS AND TWEAKS 97
def update():
◁ Try again
At the moment, the player needs to
global stars, game_complete, game_over, current_level quit the game to try again. You can
if len(stars) == 0: add some code to allow the player
to play again by pressing a key.
stars = make_stars(current_level)
Add some code to the update()
if (game_complete or game_over) and keyboard.space: function that will check if the player
stars = [] has pressed the Space bar when
the game is over or complete. If
current_level = 1 they have, the game is reset. You’ll
game_complete = False also need to update the draw()
function to change the message
game_over = False
that is displayed at the end.
▽ Shuffling
You can make the game a bit more fun by adding some code that shuffles the
stars every second. For this, you’ll need to use the shuffle() function. This function
first checks that the stars list isn’t empty. It then uses a Python feature called list
comprehension. This allows you to get each star’s position along the x-axis in the
form of a list. Once you have this list, you can mix up the values in it. Next you’ll
need to loop over the stars list and create an animation for each star to move
them to their new position. Use clock.schedule_interval() to run the shuffle()
function once every second. Add the following code at the end of your IDLE file.
def shuffle():
global stars
if stars:
x_values = [star.x for star in stars] I like the
random.shuffle(x_values) shuffle mode!
clock.schedule_interval(shuffle, 1)
Big Quiz
100 BIG QUIZ
How to build
Big Quiz Each question is
displayed here.
What happens
When the game begins, the first
question is shown on the screen
What is
capital of
along with four possible answers.
The player has ten seconds to click on
an answer box. If they get the right
answer, the game moves on to the
next question. If the player chooses
a wrong answer, or if the time runs
out, the game ends and the final
score is displayed on the screen.
Bring it on!
the
France? 7
The possible answers
Paris
are displayed in orange
boxes. You can change
them to a different color
if you like.
Tokyo
◁ Quiz time!
This program uses a
Graphical User Interface
(GUI, pronounced “goo-ey”),
which is the visible part of a
program that a user interacts
with. In this game, you’ll build
a GUI using Pygame Zero.
102 BIG QUIZ
N Y
Is the player’s Increase score
Display final score
answer correct? by one
End
Umm... I have
a question!
GAME PROGRESS 11% 103
Thinking caps on!
There may be a time limit to answer the
questions, but not to build the game!
Follow these steps carefully to build
your own quiz show to play with your
friends and family.
1 First steps
Create a new folder called big-quiz in your
Save As:
Tags:
quiz.py
def update_time_left():
pass
104 BIG QUIZ
The possible
answers need to be
Answer 3 Answer 4
big enough for the
player to click on
them quickly. There should be enough space between
all the answer options so that the player
doesn’t click a different answer by mistake.
LINGO
Wireframes
Computer game designers can plan their game
interfaces using wireframes. These are diagrams
that show the different parts of an interface that
the player sees on screen. They can be drawn
by hand or made using a simple drawing tool on
a computer. By doing this, the interface can be
tested, and any changes to the design can be
made before writing the code.
GAME PROGRESS 26% 105
answer_box4.move_ip(735, 538)
answer_boxes = [answer_box1, answer_box2, answer_box3, answer_box4]
10 Try it out
Save your file and run it from the command Pygame Zero Game
line in the Command Prompt or Terminal
window. You should be able to see your GUI,
ready to be filled with quiz questions. If your
program fails to run successfully, go back to
your code and try to catch those bugs!
14 More questions
Let’s add some more questions by typing
q1 = ["What is the capital of France?",
"London", "Paris", "Berlin", "Tokyo", 2]
the code shown in black below the lines from
Step 13. Remember, you can create your own
sets of questions if you like. You could base
q2 = ["What is 5+7?",
them on your favorite sports team, or show
off what you know about your favorite "12", "10", "14", "8", 1]
series of books.
? ?
? ?
q4 = ["Which planet is closest to the Sun?",
"Saturn", "Neptune", "Mercury", "Venus", 3]
?
q5 = ["Where are the pyramids?",
"India", "Egypt", "Morocco", "Canada", 2]
108 BIG QUIZ
16 Add a function
In a real-life quiz, the quizmaster begins by
questions = [q1, q2, q3, q4, q5]
question = questions.pop(0)
picking up the first question from the top of
a list. In Python, you can do the same thing
by using the pop() function. This function This gets the first question from
removes the first item from the list, which the questions list and stores it
makes the second item move to the top of in a variable called question.
the list. So in your code, pop() will remove q1,
and q2 will take its place. Type this code next.
EXPERT TIPS
Pop the stack
17 Display the boxes
Now you need to update the draw()
When you place items in a list, Python
stacks them on top of each other. The first
function to display the questions and the
item in the list appears at the top of the
timer on the screen. Use a for loop to draw
the possible answers inside the answer
stack. Using the pop() function removes
boxes. Add this code to the draw() function an item from the top of the stack.
under what you typed in Step 9.
What is the
capital of France? 10
Ah! I knew this was
Berlin Tokyo
def game_over():
Since there’s no
global question, time_left correct answer here,
it’s set to 5, which
message = "Game over. You got %s questions correct" % str(score)
isn’t on the list.
question = [message, "-", "-", "-", "-", 5]
time_left = 0
This sets the time to zero The final message is displayed instead of another
when the game ends. question. This will set all possible answers to a dash
because you don’t want the player to be able to answer.
110 BIG QUIZ
20 Correct answers
Now you need to tell Python
def correct_answer():
global question, score, time_left
This increases
what you want the program the score by one.
to do if the player gets an
answer correct. You need to
score = score + 1
increase the current score,
and then get the next if questions: This gets the
next question
question. If there aren’t any question = questions.pop(0) if there are any-
questions left, the game more questions
should end. Replace pass time_left = 10
left in the list.
under def correct_answer() else:
from Step 3 with this code. This resets the
print("End of questions")
timer back to
game_over() ten seconds.
This block runs if there are no
more questions in the list.
This displays a message
in the Command Prompt
or Terminal window.
21 Answering questions
Next add some code that
def on_mouse_down(pos):
index = 1
will run when the player clicks
on an answer box. This code for box in answer_boxes:
will check to see which box
if box.collidepoint(pos):
has been clicked on, and
then print the result in the print("Clicked on answer " + str(index))
Command Prompt or Terminal index = index + 1
window. Replace pass under
the on_mouse_down(pos)
function from Step 3 with The variable index increases This displays a message
this code. by one and moves to the in the Command Prompt
next answer box in the list. or Terminal window.
def on_mouse_down(pos):
index = 1
for box in answer_boxes:
if box.collidepoint(pos):
print("Clicked on answer " + str(index))
if index == question[5]:
print("You got it correct!") The item at position five
correct_answer() in each question list is the
number that corresponds
index = index + 1 to the correct answer.
def on_mouse_down(pos):
index = 1
for box in answer_boxes:
if box.collidepoint(pos):
print("Clicked on answer " + str(index))
if index == question[5]:
print("You got it correct!")
correct_answer()
else:
game_over()
index = index + 1
def update_time_left():
If there’s still time
left on the timer, global time_left
this decreases
it by one.
if time_left:
time_left = time_left - 1
update_time_left() function so
that it runs automatically once if time_left:
every second. You can use Pygame
time_left = time_left - 1
Zero’s clock tool to do this. Add this
line of code to the very bottom of else:
your program. game_over()
This calls the update_time_left()
function once every second.
clock.schedule_interval(update_time_left, 1.0)
27 Get quizzing!
That’s it! Run your game and try it Pygame Zero Game
out. Hopefully, you’ll be able to
answer all the questions correctly.
7
The player
Remember, if your screen doesn’t What is the needs to click
look right, you’ll have to go back to
your code and debug it. Read every capital of France? on the correct
answer before
line carefully and make sure your the time
code matches the steps exactly. runs out.
Have fun quizzing your friends!
London Paris
Berlin Tokyo
GAME PROGRESS 100% 113
def on_key_up(key):
◁ Skip a question
You could add some
global score more code to the
if key == keys.H: on_key_up(key)
function that allows
print("The correct answer is box number %s " % question[5])
the player to skip a
if key == keys.SPACE: question by pressing
score = score - 1 the Space bar. Skipping
a question means they
correct_answer() move on to the next
question, but without
This block first decreases the player’s score by one scoring a point. Here’s
and then runs the correct_answer() function, which
increases it by one, keeping the score the same.
one way of doing it.
▷ More questions
q6 = ["What is a quarter of 200?",
You can play this game over and over
again, but to keep it interesting, you "50", "100", "25", "150", 1]
can change the questions or even add
some more. Here are a few examples of
q7 = ["Which is the largest state in the USA?",
questions that you might want to use.
You can always add some of your own! "Wyoming", "Alaska", "Florida", "Texas", 2]
If you add extra questions, what else
in the code will you need to update?
q8 = ["How many wives did Henry VIII have?",
"Eight", "Four", "Six", "One", 3]
114 BIG QUIZ
▷ Dash of color
You can make your interface more attractive
by changing the color of the background, the papaya whip plum slate blue
boxes, or the text that appears on screen. (R 255, G 239, B 213) (R 221, G 160, B 221) (R 106, G 90, B 205)
Here are some colors along with their RGB
values that you can play with. Take a look at
page 75 to find out how RGB values work.
moccasin orchid dark slate blue
(R 255, G 228, B 181) (R 218, G 112, B 214) (R 72, G 61, B 139)
light coral medium violet red yellow blue violet dark sea green
(R 240, G 128, B 128) (R 199, G 21, B 133) (R 255, G 255, B 0) (R 138, G 43, B 226) (R 143, G 188, B 143)
fire brick orange red dark khaki dark magenta lawn green
(R 178, G 34, B 34) (R 255, G 69, B 0) (R 189, G 183, B 107) (R 139, G 0, B 139) (R 124, G 252, B 0)
medium aquamarine dodger blue antique white saddle brown slate gray
(R 102, G 205, B 170) (R 30, G 144, B 255) (R 250, G 235, B 215) (R 139, G 69, B 19) (R 112, G 128, B 144)
light sea green steel blue wheat sienna light slate gray
(R 32, G 178, B 170) (R 70, G 130, B 180) (R 245, G 222, B 179) (R 160, G 82, B 45) (R 119, G 136, B 153)
How to build
Balloon Flight A cloudy backdrop
sets the scene.
What happens
When the game starts, a hot-air balloon
appears in the middle of the screen. You
need to use the mouse button to make the
balloon rise or fall. The challenge is to keep
the balloon in the air without hitting any
birds, houses, or trees. For every obstacle
you avoid, you’ll score one point. But as
soon as you hit one, the game is over.
◁ Balloon
The balloon begins to drop
as soon as the game starts.
You can make it rise again
by clicking the mouse.
◁ Obstacles
The obstacles keep appearing
at random positions. The
player needs to avoid all the
obstacles to stay in the game.
HOW TO BUILD BALLOON FLIGHT 119
Score: 0
The clouds are part
of the background,
so you don’t need
to avoid them.
◁ Up in the air
The program creates the
illusion of motion by making
the obstacles appear at
random intervals and moving
them along the x-axis.
120 BALLOON FLIGHT
How it works
First you’ll add the balloon and all the obstacles to the
code. The program will check if the player has pressed
the mouse button to move the balloon up, or hasn’t to let
it fall. Once an obstacle has disappeared off the left edge
of the screen, the program will place a new one up to 800
pixels off the right edge of the screen at a random position
to make the obstacles appear at random intervals. If the
balloon hits any of the obstacles, the game will end and
the top scores will be displayed.
Start
Add balloon
Add obstacles
N
1 First steps
Go to the python-games folder you made 2 Set up an images folder
This game uses six images. Create a
earlier and create a folder called balloon-flight new folder called images within your
inside it. Now open IDLE and create an empty balloon-flight folder. Find the Balloon Flight
file by going to the File menu and choosing images in the Python Games Resource Pack
New File. Save this file as balloon.py in the (dk.com/computercoding) and copy them
balloon-flight folder. into the images folder as shown here.
Tags: balloon.py
images
background.png
Where: balloon-flight
balloon.png
bird-down.png
bird-up.png
Cancel Save house.png
tree.png
code in it. From the File menu, select Save As... and high-scores.txt
save the file as high-scores.txt in the balloon-flight images
folder. Make sure you delete the .py extension.
0 0 0
4 Import a module
Now that your folders are ready, it’s time to
from random import randint
start writing the code. First you need to import This function will be used to
a module that’s used in the program. Type this generate random positions for
line at the top of your balloon.py IDLE file. the obstacles on the screen.
122 BALLOON FLIGHT
EXPERT TIPS
Body of the
function
GAME PROGRESS 31% 123
The position of
This list stores the This variable keeps track of
the house on the
top three high how many times the game
y-axis is fixed at 460.
scores for the game. has been updated to change
the image of the bird.
house.pos = randint(800, 1600), 460
scores = []
I must steer clear of
all these obstacles!
def update_high_scores():
pass
def display_high_scores():
pass
def draw():
screen.blit("background", (0, 0))
if not game_over:
balloon.draw()
bird.draw() This line displays
the score on screen.
house.draw()
tree.draw()
screen.draw.text("Score: " + str(score), (700, 5), color="black")
def on_mouse_down():
I can’t believe this global up
is actually working!
up = True
balloon.y -= 50
def on_mouse_up():
These functions global up
handle the mouse
button presses. up = False
EXPERT TIPS
Shorthand calculations
With Python, you can perform a calculation
?
using a variable and then store the result
in the same variable. For example, to add
1 to a variable called a, you would usually
write: a = a + 1. Quick! What’s 4 + 4?
a = a - 1 is the same as a -= 1
a = a / 1 is the same as a /= 1
a = a * 1 is the same as a *= 1
126 BALLOON FLIGHT
16 Add in gravity
Next add some code to make the balloon
global game_over, score, number_of_updates
if not game_over:
move down when the player isn’t pressing
the mouse button. Add this code to the if not up:
update() function from Step 15.
balloon.y += 1
if bird.x > 0:
bird.x -= 4
if number_of_updates == 9:
flap()
This block of code will
number_of_updates = 0
make the bird flap its
else: wings every tenth time the
update() function is called.
number_of_updates += 1
else:
bird.x = randint(800, 1600)
bird.y = randint(10, 200)
score += 1
number_of_updates = 0
if house.right > 0:
house.x -= 2
else:
If the house disappears off the
house.x = randint(800, 1600)
left edge of the screen, this line
score += 1 places it at a random position
off the right edge.
EXPERT TIPS
Scrolling across the screen
21 Move the tree
Using the same logic as before, add these
Once the obstacles disappear off the screen, you
need to move them back to the right-hand side
lines under the code from Step 20 to make of the screen. This is to create the illusion of motion
the tree move across the screen.
and make it look like lots of obstacles are appearing
Don’t forget to count the on the screen when, in reality, you only use one
number of spaces before Actor for each type of obstacle in your code.
each line of code.
Scrolling the same Actor across the screen means
you don’t have to create new Actors every time one
else:
disappears off the screen.
house.x = randint(400, 800)
score += 1
if tree.right > 0:
tree.x -= 2
else:
tree.x = randint(800, 1600)
score += 1
GAME PROGRESS 83% 129
Keep it steady
22 Your game needs to end if the
score += 1
update_high_scores()
def update_high_scores():
global score, scores
filename = r"/Users/bharti/Desktop/python-games/balloon-flight/high-scores.txt"
scores = []
This resets the list You will need to change this gray bit of code to the high-scores.txt
of high scores. file's location on your own computer. Drag the high-scores.txt file
into the Command Prompt or Terminal window, then copy and
paste the path here and put quotation marks around it. Replace
any backslashes \ that look out of place with a space.
scores = []
with open(filename, "r") as file:
Remember, the high This function splits
line = file.readline() the high scores stored
scores file only has one
line. This reads the single high_scores = line.split() in one line into three
line stored in the file. different strings.
EXPERT TIPS
Splitting strings
In this game, all the high scores are name = "Martin,Craig,Daniel,Claire"
saved in a text file on a single line as a
string. To check if the player has beaten name.split(",")
any of these high scores, you need to
This parameter splits the string at each
split this string into three separate comma. If you don’t provide a parameter,
parts. Python’s split() function can be the function will split the string at the space
used to split a string at a character and character, like in Step 26 of your program.
then store the separate strings in a list.
You can pass a parameter to the split() The list is returned with four separate strings.
function telling it which character you
want to split the string by. ["Martin", "Craig", "Daniel", "Claire"]
GAME PROGRESS 97% 131
EXPERT TIPS
Keeping score
Imagine the current high scores are 12, 10, 8, and a This is an example
player scores 11. If your code just replaced each score 12 10 8 of an existing list
you’ve beaten with the new score, you’d end up with of scores.
12, 11, 11, which wouldn’t be right. To avoid this, your
code needs to compare the player’s score with the top
Once 11 has replaced
score first. 11 is less than 12, so it doesn’t replace it. It 12 11 8 10, you need to
then needs to move on to the second-highest score. check 10, rather
The next one, 11 is greater than 10, so it replaces it. Now than 11, against 8.
that 11 is on the scoreboard, the code needs to check if
10, the score that was just replaced, is greater than the These are the new
12 11 10 three high scores.
score currently in third place. Because 10 is greater than
8, it replaces it, and 8 is removed altogether.
high_scores = line.split()
for high_score in high_scores:
EXPERT TIPS
File handling
In Balloon Flight, you’ve used a .txt file to store
the high scores. A file like this can be opened and
assigned to a variable. The main functions that
you need to handle the file are open(), read(),
and write().
▽ Use the read() function to read an entire file. ▽ You can also just read a single line, rather
than the whole file.
names = file.read()
name = file.readline()
lines = []
▽ Now use the write() function to write to a file.
▽ When you’re finished with a file, you should ▽ If you forget to close a file after using it,
close it to tell the program you are done with it. some of the data may not get written to it.
Use the with statement to stop this from
file.close() happening. This statement opens the file and
automatically closes it when it has finished
running the body of the with statement.
It’s time to close. Are
you sure you’re done? with open("names.txt", "r") as file:
name = file.readline()
def display_high_scores():
screen.draw.text("HIGH SCORES", (350, 150), color="black")
y = 175 This sets the first This line writes
high score’s position HIGH SCORES
position = 1 on the y-axis. on the screen.
for high_score in scores:
screen.draw.text(str(position) + ". " + high_score, (350, y), color="black")
y += 25
position += 1
HIGH SCORES
1. 12
2. 9
3. 8
4. 6
5. 3
lives = 3
△ Lives
Why don’t you give the player some more
△ More high scores chances to complete the game? Introduce a
Right now the game only stores the top three high scores. new variable to keep track of a player’s lives.
Can you change it to store the top five or ten? Remember Reduce the number by one every time the
the text file you created in Step 3 with three zeroes? How player hits an obstacle. When there are no
can you edit this file to store more high scores? more lives left, the game ends.
134 BALLOON FLIGHT
new_high_score = False
>>> print(3 % 2)
1
if bird.x == house.x
Dance
Challenge
138 DANCE CHALLENGE
How to build
Dance Challenge
Get your groove on with this fast-paced
game. Watch the dancer move to the
Pygame Zero Game
music and then put your memory skills
to the test by repeating those moves. Score: 0
How long can you keep going without
making a mistake?
What happens
In this game, the dancer performs a
sequence of moves. You need to remember
this sequence and make him repeat it using
the four arrow keys on the keyboard.
◁ Dancer
The dancer loves showing
off his moves! Follow him
carefully to keep on playing.
◁ Colored squares
One of the squares is
highlighted with a yellow
outline each time the
dancer switches from
one move to another.
HOW TO BUILD DANCE CHALLENGE 139
◁ Ready to rock!
This program uses
different functions to
make the dancer move
and to highlight the
colored squares. You can
also create a countdown
to give the player time to
get ready to memorize
the routine.
140 DANCE CHALLENGE
Show countdown
Y
See which move Did it match
to check next the move?
End
GAME PROGRESS 13% 141
Hit the dance floor 1 Create a file in IDLE
Open IDLE and create an empty
Now that you’ve worked out how the file by going to the File menu and
game will work, it’s time to put your dancing choosing New File.
shoes on and get started! Begin by setting
File
up and saving a new file, and then import
the Python modules you will need in this New File
game. You will then use different Python
Open...
functions to create the game.
Cancel Save
Nice save!
Clean up by ▶
Sort by ▶
7 Import a module
Now that you’re all set up, it’s time to get started
from random import randint
These will
move_list = [] contain lists of
The stage is almost the dance moves.
set. I can’t wait to display_list = []
get started!
score = 0
These variables are
current_move = 0 assigned integer
count = 4 values needed in
the game.
dance_length = 4
say_dance = False
These are flag
show_countdown = True
variables that
moves_complete = False keep track of
what’s happening
game_over = False in the game.
GAME PROGRESS 35% 143
going to look like. You can display global game_over, score, say_dance
your Actors on the screen using global count, show_countdown
Pygame Zero’s built-in draw()
if not game_over:
function. Type this in next. This command is only run
screen.clear() if the game isn’t over.
screen.blit("stage", (0, 0))
This line clears dancer.draw()
previous items drawn.
up.draw() Use this function to
add a background in
down.draw() the game window.
These lines draw all right.draw()
the Actors in their
current positions. left.draw()
screen.draw.text("Score: " +
str(score), color="black",
This prints the
score in the top-left topleft=(10, 10))
corner of the screen.
return
12 First screen
If your code is working properly, your game Pygame Zero Game
screen should look something like this. If not,
Score: 0
there’s no need to worry. Just go back to your
code and use your debugging skills to check
every line for possible errors, such as spellings
and number of spaces.
Take that!
13 Musical statues
You’ve probably spotted a problem with your
def reset_dancer():
pass
This function will set
the Actors back to their
dancer... he’s not moving! Set up placeholders original positions.
for the functions you’re going to use to
change that. Add this code under what you This function updates
def update_dancer(move):
typed in Step 10. the Actors to show a
pass dance move.
def countdown():
This function will display
pass a countdown before each
sequence of moves.
def next_move():
This function will
pass go to the next
move in the list.
REMEMBER
def on_key_up(key):
Placeholders pass
This function will make
the program react when
Using pass is a good way to list all you press a key.
the functions you’ll need so you don’t
def update():
forget anything. This is a built-in
pass Pygame Zero function.
GAME PROGRESS 48% 145
14 Random numbers
Your program needs to generate dance sequences for you 0 0 = Up
to memorize and repeat. The four possible moves are Up,
Down, Left, and Right. You don’t have a function that will
generate random directions, but the randint() function will 3 = Left 3 1 1 = Right
let you generate random numbers. If you assign each of the
four moves a number, starting from 0, you will then be able
to create random dance sequences. Step 15 will show you
how to do this. 2 2 = Down
15 Let’s move!
The first function you need to define properly is update_dancer().
This changes the image of the dancer to match the dance move
he should perform. The colored square that corresponds to
that dance move also changes to become outlined in yellow.
Replace pass under the update_dancer(move) function from This function will tell Don’t forget to save
Step 13 with the code shown below. There’s quite a lot to add, the dancer which your work.
so be extra careful. move to perform.
17 Make a move
Next you need to write a function
def on_key_up(key):
global score, game_over, move_list, current_move
that makes the dancer perform a
move when you press one of the if key == keys.UP:
arrow keys on the keyboard. You
update_dancer(0)
can use Pygame Zero’s built-in tool
on_key_up() to write an event- elif key == keys.RIGHT:
handler function to do this. Replace update_dancer(1)
pass under the on_key_up(key)
function from Step 13 with this code. elif key == keys.DOWN:
update_dancer(2)
elif key == keys.LEFT:
Each time an arrow key is pressed,
the update_dancer() function is update_dancer(3)
called with a parameter to make the return
dancer perform the relevant move.
def display_moves():
global move_list, display_list, dance_length
global say_dance, show_countdown, current_move This line stores the first
move in display_list in
This line if display_list:
the variable this_move.
checks if the this_move = display_list[0]
list of dance
moves has display_list = display_list[1:]
something in it.
if this_move == 0:
This removes the first item
update_dancer(0) from display_list so that
If the value of clock.schedule(display_moves, 1) the second item will now
this_move is 0, be at position 0.
it is passed on elif this_move == 1:
to this function.
update_dancer(1)
clock.schedule(display_moves, 1)
elif this_move == 2:
update_dancer(2)
This line clock.schedule(display_moves, 1)
schedules a call
to the function else:
display_moves() If display_list is empty,
in one second. update_dancer(3)
this line tells the draw()
clock.schedule(display_moves, 1) function to display “Dance!”
else: This line sets the
global variable
say_dance = True show_countdown
show_countdown = False to False.
return
148 DANCE CHALLENGE
20 Counting down
You don’t want your players to be looking away when the next set of
EXPERT TIPS
moves to memorize is displayed. Add a function that displays 3, 2, and Recursive functions
then 1 with a one-second pause between each number. You’ll actually
count down from 4, but because the countdown() function begins by Both display_moves() and
subtracting one from count, the number 4 doesn’t appear on the countdown() are functions
screen long enough to be seen. Replace pass under def countdown() that call themselves. These are
from Step 13 with this code. known as recursive functions.
Because Pygame Zero redraws
def countdown(): the screen thousands of times
global count, game_over, show_countdown every second, you need your
recursive functions to schedule
if count > 1: This updates the a call to themselves one whole
count = count - 1 value in count by second later. Otherwise, the
subtracting one.
clock.schedule(countdown, 1) moves and the countdown
would be displayed too fast
else:
for even the most eagle-eyed
show_countdown = False This line player to see!
schedules
display_moves() another call to
return the countdown()
function in
Can you call me back
one second.
in a second?
This removes the
countdown from the
screen if count is less
than or equal to one.
23 Game over
If the player makes a mistake, you need a “GAME OVER!”
message to pop up. You can do this by adding an else branch
to the if not game_over statement. By doing this, if game_over
becomes True, the dancer and squares will vanish and be replaced
by the “GAME OVER!” message. Add this code to the draw()
function immediately above the return statement.
Don’t forget to save
This code runs if
your work.
game_over is True.
if show_countdown:
screen.draw.text(str(count), color="black",
topleft=(CENTER_X - 8, 150), fontsize=60)
else:
screen.clear()
screen.blit("stage", (0, 0)) This line draws
the score in the
screen.draw.text("Score: " + top-left corner.
str(score), color="black",
topleft=(10, 10))
screen.draw.text("GAME OVER!", color="black",
This line draws “GAME
topleft=(CENTER_X - 130, 220), fontsize=60) OVER!” in black at the
center of the screen.
return
150 DANCE CHALLENGE
24 Generation test
It’s time to test your new functions and see if they are working. Add
generate_moves()
if key == keys.UP:
update_dancer(0) This block runs if the
player presses the
if move_list[current_move] == 0: correct key.
score = score + 1
next_move() If the player
makes a mistake,
else: game_over is set
game_over = True to True.
27 Keep going!
To make the game more challenging, a new set of
I am out of control!
moves needs to be displayed every time the player
successfully completes a dance sequence. Replace
pass in the update() function from Step 13 with
the code below to do this.
def update():
global game_over, current_move, moves_complete
if not game_over: This line runs if you
complete every move
if moves_complete: in the current list.
generate_moves()
This line generates a
moves_complete = False new series of moves
current_move = 0 and displays them.
152 DANCE CHALLENGE
If game_over is True,
this line stops playing
the audio file.
31 Ready to play
Your code is now complete, so get your
dancing shoes on! Save the file, run it
from the command line in Command
Prompt or Terminal window, and see
how long you can keep on dancing!
GAME PROGRESS 100% 153
Shuffle mode is
my favorite!
if (rounds % 3 == 0):
dance_length = dance_length + 1
△ A longer dance
You can make the game more challenging. Each time you
complete three sequences, increase the dance_length by one. △ Change the music
To find out how many rounds have been completed, divide You can change the game music by downloading
the number of sequences danced by three. If the remainder is audio files from www.creativecommons.org.
zero, then three sequences have been successfully completed Remember to look for the .ogg format. You
since the last check, so add 1 to dance_length. You can use don’t have to pay for the music, but you should
Python’s modulo operator to work out the remainder. Modulo acknowledge the creator in your game by adding
is written using the % symbol, so 4 % 3 will give you the a line of code that displays the name of the track
remainder on dividing 4 by 3. and its creators on the “GAME OVER!” screen.
Happy
Garden
156 HAPPY GARDEN
Happy Garden
number of seconds the
garden has been happy for.
What happens
When the game starts, a cow with a watering
can appears in the garden, but there is only
one flower. Every few seconds another flower
appears or an existing flower begins to wilt. Use
the arrow keys to move the cow to the wilted
flowers and press the Space bar to water them.
If any flower remains wilted for more than ten
seconds, the game ends. But if the garden is
happy for more than 15 seconds, one of the
flowers mutates into a fangflower and tries
to zap the cow.
◁ Cow
The cow is the main
character in the game.
Its aim is to keep all
the flowers watered.
◁ Fangflower
This large carnivorous
plant moves around the
garden and tries to zap
the cow.
HOW TO BUILD HAPPY GARDEN 157
If a flower remains
wilted for more than ten
seconds, the game ends.
◁ Keep moo-ving!
There are a lot of different
elements in this game. The
code uses several functions
to keep track of them all.
158 HAPPY GARDEN
End
N
N
Y
Is the arrow key Move cow in the direction
Reset flower if it is wilted
being pressed? of the arrow key
1 Get started
Open IDLE and create an empty file by clicking 2 Save the game
Go to your python-games folder and create
on the File menu and choosing New File. another folder called happy-garden. From the File
menu, choose Save As… and save the program
File as garden.py inside the happy-garden folder.
Open... Tags:
Recent Files ▶
Cancel Save
Class Browser
happy-garden happy-garden
garden.py garden.py
images images
cow-water.png
cow.png
fangflower.png
flower-wilt.png
flower.png
garden.png
zap.png
5 Import modules
It’s time to start coding. Go back to your garden.py
from random import randint
import time
file and start by importing some modules. You’ll
use randint() to randomly choose which flowers
will wilt or mutate. The functions in the Time
module will keep track of how long the garden
This imports Python’s This imports the
has been happy for or how long any flowers Time module. randint() function from
have been wilted. Python’s Random module.
160 HAPPY GARDEN
game_over = False
These are flag variables,
finalized = False
which let you know what’s
happening in the game. garden_happy = True
fangflower_collision = False
time_elapsed = 0
These variables help
keep track of the time. start_time = time.time()
11 Time to test
It’s time to take a look at your garden!
pgzrun
13 Other functions
You’ll use a lot of functions in this
def new_flower():
pass
game. You can list some of them
now and define them later in the
code. Using pass will make sure
def add_flowers():
that Python doesn’t run anything
yet. Type this code under what pass
Don’t forget to save
you added in Step 10. your work.
def check_wilt_times():
pass
def wilt_flower():
pass
I'm going to make
them all bloom.
def check_flower_collision():
pass
def reset_cow():
pass
def update():
pass
15 Another test
Test your newly updated code to make sure
it’s correct. Save your IDLE file and run it from Let’s check pages
the command line. You should now be able to 24–25 to see
move the cow on the screen. how it’s done.
pgzrun
16 Add a flower
In this step, you’ll create a flower Actor for the cow to
water and add it to the end of flower_list. You’ll also add
the value happy to the end of wilted_list, which holds
the amount of time each flower has been wilted for. The
happy value will let the program know that the flower These are the
hasn’t wilted. Replace pass in the new_flower() function global variables
with this code. this function uses. This line creates
a new flower Actor.
def new_flower():
global flower_list, wilted_list
flower_new = Actor("flower")
This line sets the
flower_new.pos = randint(50, WIDTH - 50), randint(150, HEIGHT - 100)
position of
flower_list.append(flower_new) the new flower.
wilted_list.append("happy")
return
This lets the program know This adds the new flower
that the flower is not wilted. to the list of flowers.
def add_flowers():
This line calls the
global game_over new_flower() function
if not game_over: to create a new flower.
new_flower()
clock.schedule(add_flowers, 4) This adds a new
return flower every
four seconds.
164 HAPPY GARDEN
19 Blooming garden
If there are no errors in your code, Pygame Zero Game
you will see a new flower appear on
the screen every four seconds. This Garden happy for: 20 seconds
is what your screen will look like after
20 seconds. Use the arrow keys to
move the cow around.
21 Stop watering
The code from Step 20 uses two functions that you haven’t
written yet—reset_cow() and check_flower_collision(). Let’s
add the code that will change the image of the cow using the
watering can back to the version where it’s just holding it.
Replace the word pass under the reset_cow() function from Uhh... I think that’s
Step 13 with the code in black below. enough water.
add_flowers()
This changes
the cow’s image
back to the
original one.
def wilt_flower():
This line generates
global flower_list, wilted_list, game_over a random index in
if not game_over: the list of flowers.
This line
resets the time if flower_list:
for this flower in
rand_flower = randint(0, len(flower_list) - 1)
wilted_list to This checks if the
the current time. if (flower_list[rand_flower].image == "flower"): flower at this index
is wilted or not.
flower_list[rand_flower].image = "flower-wilt"
wilted_list[rand_flower] = time.time()
This schedules
another call to clock.schedule(wilt_flower, 3)
wilt_flower() in
three seconds. return
24 Unhappy garden!
Next you need to check if any of the flowers have been
wilted for more than ten seconds. If one has, the garden’s This code loops over
unhappy, and it’s game over! Go to def check_wilt_times() each item in the
in Step 13 and replace pass with the code shown here. wilted_list.
def check_wilt_times():
global wilted_list, game_over, garden_happy
25 Start wilting
Now that you’ve added a function
return
cow.image="cow"
else:
if not finalized:
cow.draw()
screen.draw.text(
"Garden happy for: " +
str(time_elapsed) + " seconds",
topleft=(10, 10), color="black"
)
if (not garden_happy):
This displays
a message screen.draw.text(
that tells "GARDEN UNHAPPY—GAME OVER!", color="black",
the player the
game is over. topleft=(10, 50)
)
finalized = True
168 HAPPY GARDEN
28 Test run
Save your IDLE file and run it from the Pygame Zero Game
command line in the Command Prompt
or Terminal window. Try moving the cow Garden happy for: 23 seconds
around and water the wilted flowers.
If a flower remains wilted for more than GARDEN UNHAPPY—GAME OVER!
ten seconds, you will see a screen like
the one shown here.
29 Added menace
So far, keeping the garden happy has been difficult index = index + 1
but not dangerous. What if the flowers start mutating return
into scary fangflowers that move around the garden
trying to zap the cow? Let’s add some functions to
control the fangflower. Use placeholders for now def check_fangflower_collision():
and define them later on. Type this code above pass
the reset_cow() function you defined in Step 21.
def velocity():
Where did these pass
weird flowers
come from?
def mutate():
pass
def update_fangflowers():
pass
def reset_cow():
global game_over
if not game_over:
cow.image = "cow"
GAME PROGRESS 83% 169
30 Mutation 0 1 2 3 index
It’s time for your harmless flowers to turn
into carnivorous fangflowers. Even worse, fangflower_list
the code will change one random flower
into a fangflower every 20 seconds after
the first mutation. Replace pass under
def mutate() with the code below.
There’s a lot of code to add here, so be 2 0 -1 3
extra careful. fangflower_vx_list
If the game is not over and there These are the global
are still flowers left to mutate, variables needed in
this block of code will run. this function.
def mutate():
global flower_list, fangflower_list, fangflower_vy_list
global fangflower_vx_list, game_over
if not game_over and flower_list:
This line picks a
This line rand_flower = randint(0, len(flower_list) - 1) random flower
removes the to mutate.
fangflower_pos_x = flower_list[rand_flower].x
mutated flower
from the list fangflower_pos_y = flower_list[rand_flower].y
of flowers.
del flower_list[rand_flower]
fangflower = Actor("fangflower")
This line sets the
fangflower at the fangflower.pos = fangflower_pos_x, fangflower_pos_y
same position as fangflower_vx = velocity()
the flower it
mutated from. fangflower_vy = velocity() This sets
how fast the
fangflower = fangflower_list.append(fangflower)
fangflower is
fangflower_vx_list.append(fangflower_vx) moving left
This sets
or right on
how fast the fangflower_vy_list.append(fangflower_vy) the screen.
fangflower is
moving up clock.schedule(mutate, 20)
or down on return
the screen.
This adds a new
The fangflower’s This line schedules a call fangflower to the
velocities are to mutate a flower every list of fangflowers.
added to these lists. 20 seconds.
170 HAPPY GARDEN
0 x + Negative y
Negative y velocity
Ne
ga ey
ti v
ex a ti v
eg
+N +N
eg
ati ex
ti v
ve
y P osi
Negative x + 0 y Positive x + 0 y
0 x + Positive y
def update_fangflowers():
global fangflower_list, game_over
if not game_over: This loops over all
the fangflowers
index = 0 in the list.
This variable
for fangflower in fangflower_list:
helps the
program keep fangflower_vx = fangflower_vx_list[index] These get the x
track of which and y velocities
item in the list it’s fangflower_vy = fangflower_vy_list[index]
of the fangflower.
dealing with. fangflower.x = fangflower.x + fangflower_vx
fangflower.y = fangflower.y + fangflower_vy
These get the
if fangflower.left < 0: new position of
fangflower_vx_list[index] = -fangflower_vx the fangflower.
If the fangflower
touches the left if fangflower.right > WIDTH:
edge of the screen,
fangflower_vx_list[index] = -fangflower_vx
this will make it
start moving to if fangflower.top < 150:
the right.
fangflower_vy_list[index] = -fangflower_vy
if fangflower.bottom > HEIGHT:
fangflower_vy_list[index] = -fangflower_vy
index = index + 1
return
def check_fangflower_collision():
This adds an
global cow, fangflower_list, fangflower_collision
image to show
the cow has global game_over
been zapped.
for fangflower in fangflower_list:
if fangflower.colliderect(cow):
cow.image = "zap" This checks if the
This tells the fangflower and
program that game_over = True cow are next to
the game is over. each other.
break
return
34 Drawing results
If a fangflower manages to zap the
cow, it’s game over. Add this code to
the draw() function to display a game Don’t forget to save
over message. your work.
if (not garden_happy):
screen.draw.text(
This block of
code runs if the "GARDEN UNHAPPY—GAME OVER!", color="black",
garden is still
happy but the cow topleft=(10, 100)
has been zapped. )
How to build
Sleeping Dragons
Grab your shield and sword as you go
in search of dragon treasure. Time your
Pygame Zero Game
movements to snatch the eggs from
under the dragons’ noses. But be
careful, brave knight—if they wake
up, you’re in for a nasty surprise!
What happens
In this game, the player controls the hero
using the four arrow keys. The hero must
collect 20 eggs from the dragons’ lair to win
the game. Each dragon sleeps and wakes up
at different times. If the hero is near a dragon
when it’s awake, the player loses a life. The
game ends when the player runs out of lives
or collects enough eggs.
◁ Dragons
The three dragons
are harmless when
they’re asleep.
◁ Eggs
Each dragon has a
different number of eggs.
◁ Hero
The fearless hero has
three lives to collect
20 eggs. 6 2
HOW TO BUILD SLEEPING DRAGONS 179
Because I like to
Why do you sleep fight knights!
during the day?
The dungeon
background sets the
scene for your quest.
◁ Dragons in a dungeon
This game uses built-in
Pygame functions to animate
the Actors and Python’s
dictionaries to keep track of
the dragons and their eggs.
180 SLEEPING DRAGONS
N
Has the player N
N collected enough
Is the hero being
eggs?
attacked by
a dragon?
Y
Y
End
Subtract one from number of
lives, reset hero’s position
Y
Are there any
lives left?
Is the dragon
Y
awake?
N N
Has the dragon Has the dragon been
slept long enough? awake long enough?
Z
Z
Z Y Y
Time to begin
1 Open IDLE and create
File
an empty file by going New File
to the File menu and
selecting New File. Open...
Open Module...
Recent Files ▶
Class Browser
182 SLEEPING DRAGONS
?
I name thee
it. Then go to the File menu and select Save As...
Margaret.
to save the IDLE file as dragons.py in this folder.
Where: sleeping-dragons
Cancel Save
4 Import a module
Now you can start writing the code. Begin by
LINGO
importing Python’s Math module. Type this Constants
at the very top of your IDLE file.
Constants are variables that are used to
This imports the
import math hold values that determine how a game
entire module.
behaves. There is nothing special about
these variables that prevents them from
being changed, but programmers use capital
Check page 15 to
letters when naming them to let the other
find out more about
the Math module. programmers know that they should not
be changed throughout the program.
GAME PROGRESS 19% 183
import math
WIDTH = 800
HEIGHT = 600
These constants
define the size of CENTER_X = WIDTH / 2
the game window. CENTER_Y = HEIGHT / 2 This sets the font
color to black.
CENTER = (CENTER_X, CENTER_Y)
This sets the number FONT_COLOR = (0, 0, 0)
of eggs needed This is the distance in
to win the game. EGG_TARGET = 20 pixels at which a dragon
can attack the hero.
HERO_START = (200, 300)
"egg_hide_counter": 0,
"sleep_length": 10,
"sleep_counter": 0,
"wake_counter": 0 paint bucket trophy
}
8 Medium lair
Next add a dictionary for the lair with medium difficulty. These are the
The code for this is a lot like the code in the previous step, coordinates for the
but some of the values are different. dragon in this lair.
medium_lair = {
"dragon": Actor("dragon-asleep", pos=(600, 300)),
This checks
if the eggs are "eggs": Actor("two-eggs", pos=(400, 300)),
currently hidden.
"egg_count": 2,
"egg_hidden": False, This sets the
This tracks "egg_hide_counter": 0, coordinates
the dragon’s of the eggs.
sleep cycle. "sleep_length": 7,
"sleep_counter": 0,
"wake_counter": 0
}
GAME PROGRESS 34% 185
9 Hard lair
Now you need to add the third
"sleep_length": 7,
"sleep_counter": 0,
and final lair. Add this code
after what you typed in Step 8. "wake_counter": 0
}
11 A hero is born
The final Actor needed for this game
is the hero. It’s the character that the I was born to
player controls to collect the dragon eggs. do this!
def draw():
global lairs, eggs_collected, lives, game_complete
This adds a background
screen.clear() to the game.
screen.blit("dungeon", (0, 0))
if game_over:
screen.draw.text("GAME OVER!", fontsize=60, center=CENTER, color=FONT_COLOR)
elif game_complete:
screen.draw.text("YOU WON!", fontsize=60, center=CENTER, color=FONT_COLOR)
else:
hero.draw()
draw_lairs(lairs)
draw_counters(eggs_collected, lives)
else:
hero.draw()
draw_lairs(lairs)
draw_counters(eggs_collected, lives)
This draws a dragon
Actor for each lair. This loops over
def draw_lairs(lairs_to_draw): each lair.
19 Add a placeholder
This is a good point to run your game and 20 Try it out
Save your IDLE file and run it from the command
check for any bugs. But before you run it, line. If there are no bugs hiding in your code, you’ll
you need to set up a placeholder for the see a screen like the one below. You’ll be able to
check_for_collisions() function. Add make the hero move around the screen, but you
these lines after the code from Step 18. won’t be able to collect any eggs yet.
check_for_collisions()
Pygame Zero Game
def check_for_collisions():
pass
check_for_collisions()
def check_for_collisions():
190 SLEEPING DRAGONS
22 Schedule a call
Next add some code to schedule a call
update_egg(lair)
def update_waking_dragon(lair):
if lair["wake_counter"] >= DRAGON_WAKE_TIME:
This checks if the
dragon has been lair["dragon"].image = "dragon-asleep" This updates the
awake long enough. dragon image.
lair["wake_counter"] = 0
else:
This resets the dragon’s lair["wake_counter"] += 1 This adds one to
wake_counter to 0. the wake_counter.
GAME PROGRESS 81% 191
lair["wake_counter"] += 1
0 3
192 SLEEPING DRAGONS
lair["egg_hide_counter"] += 1
def check_for_collisions():
global lairs, eggs_collected, lives, reset_required, game_complete
for lair in lairs:
if lair["egg_hidden"] is False:
check_for_egg_collision(lair)
if lair["dragon"].image == "dragon-awake" and reset_required is False:
check_for_dragon_collision(lair)
This function is called if This function is called if the This makes sure the
the eggs are not hidden. dragon is awake and the hero’s player doesn’t lose a
position is not being reset. life when the hero is
being moved back to
the start position.
EXPERT TIPS
colliderect()
The colliderect() function gets its name
from a combination of two words—
collide and rectangle. Pygame places an
invisible rectangle around each element
on the screen. If you want to detect a Bounding
rectangle
collision between two objects, you can
check if the rectangles around them are
overlapping with each other. Sometimes
Pygame detects a collision even if two
objects appear to be slightly apart.
This is because even when the objects Area of collision
is where the
are not touching each other, the two bounding
rectangles around them can still overlap. rectangles overlap.
GAME PROGRESS 91% 193
28 Dragon collisions
If the hero gets too close to an awake
dragon, the player will lose a life. You’ll
use the check_for_dragon_collision()
function to calculate this distance.
Add this code under what you typed Don’t forget to save
in Step 27. your work.
check_for_dragon_collision(lair)
This calculates the
horizontal and vertical
def check_for_dragon_collision(lair): distances between the
dragon and the hero.
x_distance = hero.x - lair["dragon"].x
y_distance = hero.y - lair["dragon"].y
distance = math.hypot(x_distance, y_distance) This finds the distance
between the dragon and
if distance < ATTACK_DISTANCE: the hero in a straight line.
handle_dragon_collision()
29 Reset hero
If the player loses a life, the hero’s position needs
to be reset to the starting position. You’ll use the
animate() function to do this. In your game, this
function takes three parameters—the hero Actor,
the hero’s starting position, and the subtract_life()
function. Add the code shown in black here.
def handle_dragon_collision():
global reset_required
reset_required = True
animate(hero, pos=HERO_START, on_finished=subtract_life)
Egg collisions
30 You now need to add a function that will
def check_for_egg_collision(lair):
global eggs_collected, game_complete
check if the hero has touched an egg or
not. This function uses colliderect() to if hero.colliderect(lair["eggs"]):
check this. If the hero touches an
lair["egg_hidden"] = True
egg, the egg_count variable will be
increased by the number of eggs in that eggs_collected += lair["egg_count"]
lair. If the egg count reaches the target, if eggs_collected >= EGG_TARGET:
the game_complete variable will be set to
True and the player will win the game. game_complete = True
Lose a life
31 Lastly, you need to define the
game_complete = True
if keyboard.d:
◁ Add another hero
All this egg collecting can be a lot of work for one
hero2.x += MOVE_DISTANCE hero. You can add another hero to lend a hand. You’ll
if hero2.x > WIDTH: need to add some new code and change some
existing code to do this. Begin by changing the
hero2.x = WIDTH
starting position of the current hero and adding a
elif keyboard.a: different one for the new hero. Then add some code
hero2.x -= MOVE_DISTANCE to the draw() function to draw the second hero on
the screen. Now add the code shown here to the
if hero2.x < 0: update() function, which will make the second
hero2.x = 0 hero move on the screen using a new set of keys—
W, A, S, D. Lastly, remember to add a parameter to
elif keyboard.s:
all the functions that check for collisions so they
hero2.y += MOVE_DISTANCE check the collisions for both heroes.
if hero2.y > HEIGHT:
hero2.y = HEIGHT
elif keyboard.w:
This moves the second
hero2.y -= MOVE_DISTANCE hero down.
if hero2.y < 0:
hero2.y = 0
Project reference
This section contains the complete Python code for
every game in this book, except for the hacks and
tweaks. If your games don’t run properly, check their
scripts carefully against the code shown here.
def draw():
screen.clear()
apple.draw()
def place_apple():
apple.x = randint(10, 800)
apple.y = randint(10, 600)
def on_mouse_down(pos):
if apple.collidepoint(pos):
print("Good shot!")
place_apple()
else:
print("You missed!")
quit()
place_apple()
WIDTH = 400
HEIGHT = 400
score = 0
game_over = False
fox = Actor("fox")
fox.pos = 100, 100
coin = Actor("coin")
coin.pos = 200, 200
PROJECT REFERENCE 199
def draw():
screen.fill("green")
fox.draw()
coin.draw()
screen.draw.text("Score: " + str(score), color="black", topleft=(10, 10))
if game_over:
screen.fill("pink")
screen.draw.text("Final Score: " + str(score), topleft=(10, 10), fontsize=60)
def place_coin():
coin.x = randint(20, (WIDTH - 20))
coin.y = randint(20, (HEIGHT - 20))
def time_up():
global game_over
game_over = True
def update():
global score
if keyboard.left:
fox.x = fox.x - 2
elif keyboard.right:
fox.x = fox.x + 2
elif keyboard.up:
fox.y = fox.y - 2
elif keyboard.down:
fox.y = fox.y + 2
coin_collected = fox.colliderect(coin)
if coin_collected:
score = score + 10
place_coin()
clock.schedule(time_up, 7.0)
place_coin()
WIDTH = 400
HEIGHT = 400
200 REFERENCE
dots = []
lines = []
next_dot = 0
def draw():
screen.fill("black")
number = 1
for dot in dots:
screen.draw.text(str(number), \
(dot.pos[0], dot.pos[1] + 12))
dot.draw()
number = number + 1
for line in lines:
screen.draw.line(line[0], line[1], (100, 0, 0))
def on_mouse_down(pos):
global next_dot
global lines
if dots[next_dot].collidepoint(pos):
if next_dot:
lines.append((dots[next_dot - 1].pos, dots[next_dot].pos))
next_dot = next_dot + 1
else:
lines = []
next_dot = 0
game_over = False
game_complete = False
current_level = 1
stars = []
animations = []
def draw():
global stars, current_level, game_over, game_complete
screen.clear()
screen.blit("space", (0, 0))
if game_over:
display_message("GAME OVER!", "Try again.")
elif game_complete:
display_message("YOU WON!", "Well done.")
else:
for star in stars:
star.draw()
def update():
global stars
if len(stars) == 0:
stars = make_stars(current_level)
def make_stars(number_of_extra_stars):
colors_to_create = get_colors_to_create(number_of_extra_stars)
new_stars = create_stars(colors_to_create)
layout_stars(new_stars)
animate_stars(new_stars)
return new_stars
def get_colors_to_create(number_of_extra_stars):
colors_to_create = ["red"]
for i in range(0, number_of_extra_stars):
random_color = random.choice(COLORS)
colors_to_create.append(random_color)
return colors_to_create
def create_stars(colors_to_create):
new_stars = []
for color in colors_to_create:
star = Actor(color + "-star")
new_stars.append(star)
return new_stars
def layout_stars(stars_to_layout):
number_of_gaps = len(stars_to_layout) + 1
gap_size = WIDTH / number_of_gaps
202 REFERENCE
random.shuffle(stars_to_layout)
for index, star in enumerate(stars_to_layout):
new_x_pos = (index + 1) * gap_size
star.x = new_x_pos
def animate_stars(stars_to_animate):
for star in stars_to_animate:
duration = START_SPEED - current_level
star.anchor = ("center", "bottom")
animation = animate(star, duration=duration, on_finished=handle_game_over, y=HEIGHT)
animations.append(animation)
def handle_game_over():
global game_over
game_over = True
def on_mouse_down(pos):
global stars, current_level
for star in stars:
if star.collidepoint(pos):
if "red" in star.image:
red_star_click()
else:
handle_game_over()
def red_star_click():
global current_level, stars, animations, game_complete
stop_animations(animations)
if current_level == FINAL_LEVEL:
game_complete = True
else:
current_level = current_level + 1
stars = []
animations = []
def stop_animations(animations_to_stop):
for animation in animations_to_stop:
if animation.running:
animation.stop()
main_box.move_ip(50, 40)
timer_box.move_ip(990, 40)
answer_box1.move_ip(50, 358)
answer_box2.move_ip(735, 358)
answer_box3.move_ip(50, 538)
answer_box4.move_ip(735, 538)
answer_boxes = [answer_box1, answer_box2, answer_box3, answer_box4]
score = 0
time_left = 10
q2 = ["What is 5+7?",
"12", "10", "14", "8", 1]
def draw():
screen.fill("dim grey")
screen.draw.filled_rect(main_box, "sky blue")
screen.draw.filled_rect(timer_box, "sky blue")
index = 1
for box in answer_boxes:
screen.draw.textbox(question[index], box, color=("black"))
index = index + 1
def game_over():
global question, time_left
message = "Game over. You got %s questions correct" % str(score)
question = [message, "-", "-", "-", "-", 5]
time_left = 0
def correct_answer():
global question, score, time_left
score = score + 1
if questions:
question = questions.pop(0)
time_left = 10
else:
print("End of questions")
game_over()
def on_mouse_down(pos):
index = 1
for box in answer_boxes:
if box.collidepoint(pos):
print("Clicked on answer " + str(index))
if index == question[5]:
print("You got it correct!")
correct_answer()
else:
game_over()
index = index + 1
def update_time_left():
global time_left
if time_left:
time_left = time_left - 1
else:
game_over()
clock.schedule_interval(update_time_left, 1.0)
PROJECT REFERENCE 205
Balloon Flight (page 116)
from random import randint
WIDTH = 800
HEIGHT = 600
balloon = Actor("balloon")
balloon.pos = 400, 300
bird = Actor("bird-up")
bird.pos = randint(800, 1600), randint(10, 200)
house = Actor("house")
house.pos = randint(800, 1600), 460
tree = Actor("tree")
tree.pos = randint(800, 1600), 450
bird_up = True
up = False
game_over = False
score = 0
number_of_updates = 0
scores = []
def update_high_scores():
global score, scores
filename = r"/Users/bharti/Desktop/python-games/balloon-flight/high-scores.txt"
scores = []
with open(filename, "r") as file:
line = file.readline() Remember, you'll need to change this
gray bit of code to the high-scores.txt
high_scores = line.split()
file's location on your own computer.
for high_score in high_scores:
if(score > int(high_score)):
scores.append(str(score) + " ")
score = int(high_score)
else:
scores.append(str(high_score) + " ")
with open(filename, "w") as file:
for high_score in scores:
file.write(high_score)
def display_high_scores():
screen.draw.text("HIGH SCORES", (350, 150), color="black")
y = 175
position = 1
206 REFERENCE
def draw():
screen.blit("background", (0, 0))
if not game_over:
balloon.draw()
bird.draw()
house.draw()
tree.draw()
screen.draw.text("Score: " + str(score), (700, 5), color="black")
else:
display_high_scores()
def on_mouse_down():
global up
up = True
balloon.y -= 50
def on_mouse_up():
global up
up = False
def flap():
global bird_up
if bird_up:
bird.image = "bird-down"
bird_up = False
else:
bird.image = "bird-up"
bird_up = True
def update():
global game_over, score, number_of_updates
if not game_over:
if not up:
balloon.y += 1
if bird.x > 0:
bird.x -= 4
if number_of_updates == 9:
flap()
number_of_updates = 0
else:
number_of_updates += 1
PROJECT REFERENCE 207
else:
bird.x = randint(800, 1600)
bird.y = randint(10, 200)
score += 1
number_of_updates = 0
if house.right > 0:
house.x -= 2
else:
house.x = randint(800, 1600)
score += 1
if tree.right > 0:
tree.x -= 2
else:
tree.x = randint(800, 1600)
score += 1
if balloon.collidepoint(bird.x, bird.y) or \
balloon.collidepoint(house.x, house.y) or \
balloon.collidepoint(tree.x, tree.y):
game_over = True
update_high_scores()
WIDTH = 800
HEIGHT = 600
CENTER_X = WIDTH / 2
CENTER_Y = HEIGHT / 2
move_list = []
display_list = []
score = 0
current_move = 0
count = 4
dance_length = 4
say_dance = False
show_countdown = True
208 REFERENCE
moves_complete = False
game_over = False
dancer = Actor("dancer-start")
dancer.pos = CENTER_X + 5, CENTER_Y - 40
up = Actor("up")
up.pos = CENTER_X, CENTER_Y + 110
right = Actor("right")
right.pos = CENTER_X + 60, CENTER_Y + 170
down = Actor("down")
down.pos = CENTER_X, CENTER_Y + 230
left = Actor("left")
left.pos = CENTER_X - 60, CENTER_Y + 170
def draw():
global game_over, score, say_dance
global count, show_countdown
if not game_over:
screen.clear()
screen.blit("stage", (0, 0))
dancer.draw()
up.draw()
down.draw()
right.draw()
left.draw()
screen.draw.text("Score: " +
str(score), color="black",
topleft=(10, 10))
if say_dance:
screen.draw.text("Dance!", color="black",
topleft=(CENTER_X - 65, 150), fontsize=60)
if show_countdown:
screen.draw.text(str(count), color="black",
topleft=(CENTER_X - 8, 150), fontsize=60)
else:
screen.clear()
screen.blit("stage", (0, 0))
screen.draw.text("Score: " +
str(score), color="black",
topleft=(10, 10))
screen.draw.text("GAME OVER!", color="black",
topleft=(CENTER_X - 130, 220), fontsize=60)
return
def reset_dancer():
global game_over
PROJECT REFERENCE 209
if not game_over:
dancer.image = "dancer-start"
up.image = "up"
right.image = "right"
down.image = "down"
left.image = "left"
return
def update_dancer(move):
global game_over
if not game_over:
if move == 0:
up.image = "up-lit"
dancer.image = "dancer-up"
clock.schedule(reset_dancer, 0.5)
elif move == 1:
right.image = "right-lit"
dancer.image = "dancer-right"
clock.schedule(reset_dancer, 0.5)
elif move == 2:
down.image = "down-lit"
dancer.image = "dancer-down"
clock.schedule(reset_dancer, 0.5)
else:
left.image = "left-lit"
dancer.image = "dancer-left"
clock.schedule(reset_dancer, 0.5)
return
def display_moves():
global move_list, display_list, dance_length
global say_dance, show_countdown, current_move
if display_list:
this_move = display_list[0]
display_list = display_list[1:]
if this_move == 0:
update_dancer(0)
clock.schedule(display_moves, 1)
elif this_move == 1:
update_dancer(1)
clock.schedule(display_moves, 1)
elif this_move == 2:
update_dancer(2)
clock.schedule(display_moves, 1)
else:
update_dancer(3)
clock.schedule(display_moves, 1)
210 REFERENCE
else:
say_dance = True
show_countdown = False
return
def countdown():
global count, game_over, show_countdown
if count > 1:
count = count - 1
clock.schedule(countdown, 1)
else:
show_countdown = False
display_moves()
return
def generate_moves():
global move_list, dance_length, count
global show_countdown, say_dance
count = 4
move_list = []
say_dance = False
for move in range(0, dance_length):
rand_move = randint(0, 3)
move_list.append(rand_move)
display_list.append(rand_move)
show_countdown = True
countdown()
return
def next_move():
global dance_length, current_move, moves_complete
if current_move < dance_length - 1:
current_move = current_move + 1
else:
moves_complete = True
return
def on_key_up(key):
global score, game_over, move_list, current_move
if key == keys.UP:
update_dancer(0)
if move_list[current_move] == 0:
score = score + 1
next_move()
else:
game_over = True
elif key == keys.RIGHT:
PROJECT REFERENCE 211
update_dancer(1)
if move_list[current_move] == 1:
score = score + 1
next_move()
else:
game_over = True
elif key == keys.DOWN:
update_dancer(2)
if move_list[current_move] == 2:
score = score + 1
next_move()
else:
game_over = True
elif key == keys.LEFT:
update_dancer(3)
if move_list[current_move] == 3:
score = score + 1
next_move()
else:
game_over = True
return
generate_moves()
music.play("vanishing-horizon")
def update():
global game_over, current_move, moves_complete
if not game_over:
if moves_complete:
generate_moves()
moves_complete = False
current_move = 0
else:
music.stop()
WIDTH = 800
HEIGHT = 600
CENTER_X = WIDTH / 2
CENTER_Y = HEIGHT / 2
game_over = False
finalised = False
212 REFERENCE
garden_happy = True
fangflower_collision = False
time_elapsed = 0
start_time = time.time()
cow = Actor("cow")
cow.pos = 100, 500
flower_list = []
wilted_list = []
fangflower_list = []
fangflower_vy_list = []
fangflower_vx_list = []
def draw():
global game_over, time_elapsed, finalized
if not game_over:
screen.clear()
screen.blit("garden", (0, 0))
cow.draw()
for flower in flower_list:
flower.draw()
for fangflower in fangflower_list:
fangflower.draw()
time_elapsed = int(time.time() - start_time)
screen.draw.text(
"Garden happy for: " +
str(time_elapsed) + " seconds",
topleft=(10, 10), color="black"
)
else:
if not finalized:
cow.draw()
screen.draw.text(
"Garden happy for: " +
str(time_elapsed) + " seconds",
topleft=(10, 10), color="black"
)
if (not garden_happy):
screen.draw.text(
"GARDEN UNHAPPY - GAME OVER!", color="black",
topleft=(10, 50)
)
finalized = True
else:
screen.draw.text(
PROJECT REFERENCE 213
def new_flower():
global flower_list, wilted_list
flower_new = Actor("flower")
flower_new.pos = randint(50, WIDTH - 50), randint(150, HEIGHT - 100)
flower_list.append(flower_new)
wilted_list.append("happy")
return
def add_flowers():
global game_over
if not game_over:
new_flower()
clock.schedule(add_flowers, 4)
return
def check_wilt_times():
global wilted_list, game_over, garden_happy
if wilted_list:
for wilted_since in wilted_list:
if (not wilted_since == "happy"):
time_wilted = int(time.time() - wilted_since)
if (time_wilted) > 10.0:
garden_happy = False
game_over = True
break
return
def wilt_flower():
global flower_list, wilted_list, game_over
if not game_over:
if flower_list:
rand_flower = randint(0, len(flower_list) - 1)
if (flower_list[rand_flower].image == "flower"):
flower_list[rand_flower].image = "flower-wilt"
wilted_list[rand_flower] = time.time()
clock.schedule(wilt_flower, 3)
return
def check_flower_collision():
global cow, flower_list, wilted_list
index = 0
214 REFERENCE
def check_fangflower_collision():
global cow, fangflower_list, fangflower_collision
global game_over
for fangflower in fangflower_list:
if fangflower.colliderect(cow):
cow.image = "zap"
game_over = True
break
return
def velocity():
random_dir = randint(0, 1)
random_velocity = randint(2, 3)
if random_dir == 0:
return -random_velocity
else:
return random_velocity
def mutate():
global flower_list, fangflower_list, fangflower_vy_list
global fangflower_vx_list, game_over
if not game_over and flower_list:
rand_flower = randint(0, len(flower_list) - 1)
fangflower_pos_x = flower_list[rand_flower].x
fangflower_pos_y = flower_list[rand_flower].y
del flower_list[rand_flower]
fangflower = Actor("fangflower")
fangflower.pos = fangflower_pos_x, fangflower_pos_y
fangflower_vx = velocity()
fangflower_vy = velocity()
fangflower = fangflower_list.append(fangflower)
fangflower_vx_list.append(fangflower_vx)
fangflower_vy_list.append(fangflower_vy)
clock.schedule(mutate, 20)
return
def update_fangflowers():
global fangflower_list, game_over
PROJECT REFERENCE 215
if not game_over:
index = 0
for fangflower in fangflower_list:
fangflower_vx = fangflower_vx_list[index]
fangflower_vy = fangflower_vy_list[index]
fangflower.x = fangflower.x + fangflower_vx
fangflower.y = fangflower.y + fangflower_vy
if fangflower.left < 0:
fangflower_vx_list[index] = -fangflower_vx
if fangflower.right > WIDTH:
fangflower_vx_list[index] = -fangflower_vx
if fangflower.top < 150:
fangflower_vy_list[index] = -fangflower_vy
if fangflower.bottom > HEIGHT:
fangflower_vy_list[index] = -fangflower_vy
index = index + 1
return
def reset_cow():
global game_over
if not game_over:
cow.image = "cow"
return
add_flowers()
wilt_flower()
def update():
global score, game_over, fangflower_collision
global flower_list, fangflower_list, time_elapsed
fangflower_collision = check_fangflower_collision()
check_wilt_times()
if not game_over:
if keyboard.space:
cow.image = "cow-water"
clock.schedule(reset_cow, 0.5)
check_flower_collision()
if keyboard.left and cow.x > 0:
cow.x -= 5
elif keyboard.right and cow.x < WIDTH:
cow.x += 5
elif keyboard.up and cow.y > 150:
cow.y -= 5
elif keyboard.down and cow.y < HEIGHT:
cow.y += 5
if time_elapsed > 15 and not fangflower_list:
mutate()
update_fangflowers()
216 REFERENCE
WIDTH = 800
HEIGHT = 600
CENTER_X = WIDTH / 2
CENTER_Y = HEIGHT / 2
CENTER = (CENTER_X, CENTER_Y)
FONT_COLOR = (0, 0, 0)
EGG_TARGET = 20
HERO_START = (200, 300)
ATTACK_DISTANCE = 200
DRAGON_WAKE_TIME = 2
EGG_HIDE_TIME = 2
MOVE_DISTANCE = 5
lives = 3
eggs_collected = 0
game_over = False
game_complete = False
reset_required = False
easy_lair = {
"dragon": Actor("dragon-asleep", pos=(600, 100)),
"eggs": Actor("one-egg", pos=(400, 100)),
"egg_count": 1,
"egg_hidden": False,
"egg_hide_counter": 0,
"sleep_length": 10,
"sleep_counter": 0,
"wake_counter": 0
}
medium_lair = {
"dragon": Actor("dragon-asleep", pos=(600, 300)),
"eggs": Actor("two-eggs", pos=(400, 300)),
"egg_count": 2,
"egg_hidden": False,
"egg_hide_counter": 0,
"sleep_length": 7,
"sleep_counter": 0,
"wake_counter": 0
}
hard_lair = {
"dragon": Actor("dragon-asleep", pos=(600, 500)),
"eggs": Actor("three-eggs", pos=(400, 500)),
PROJECT REFERENCE 217
"egg_count": 3,
"egg_hidden": False,
"egg_hide_counter": 0,
"sleep_length": 4,
"sleep_counter": 0,
"wake_counter": 0
}
def draw():
global lairs, eggs_collected, lives, game_complete
screen.clear()
screen.blit("dungeon", (0, 0))
if game_over:
screen.draw.text("GAME OVER!", fontsize=60, center=CENTER, color=FONT_COLOR)
elif game_complete:
screen.draw.text("YOU WON!", fontsize=60, center=CENTER, color=FONT_COLOR)
else:
hero.draw()
draw_lairs(lairs)
draw_counters(eggs_collected, lives)
def draw_lairs(lairs_to_draw):
for lair in lairs_to_draw:
lair["dragon"].draw()
if lair["egg_hidden"] is False:
lair["eggs"].draw()
def update():
if keyboard.right:
hero.x += MOVE_DISTANCE
if hero.x > WIDTH:
hero.x = WIDTH
elif keyboard.left:
hero.x -= MOVE_DISTANCE
if hero.x < 0:
hero.x = 0
elif keyboard.down:
hero.y += MOVE_DISTANCE
if hero.y > HEIGHT:
hero.y = HEIGHT
elif keyboard.up:
hero.y -= MOVE_DISTANCE
if hero.y < 0:
hero.y = 0
check_for_collisions()
def update_lairs():
global lairs, hero, lives
for lair in lairs:
if lair["dragon"].image == "dragon-asleep":
update_sleeping_dragon(lair)
elif lair["dragon"].image == "dragon-awake":
update_waking_dragon(lair)
update_egg(lair)
clock.schedule_interval(update_lairs, 1)
def update_sleeping_dragon(lair):
if lair["sleep_counter"] >= lair["sleep_length"]:
lair["dragon"].image = "dragon-awake"
lair["sleep_counter"] = 0
else:
lair["sleep_counter"] += 1
def update_waking_dragon(lair):
if lair["wake_counter"] >= DRAGON_WAKE_TIME:
lair["dragon"].image = "dragon-asleep"
lair["wake_counter"] = 0
else:
lair["wake_counter"] += 1
def update_egg(lair):
if lair["egg_hidden"] is True:
if lair["egg_hide_counter"] >= EGG_HIDE_TIME:
PROJECT REFERENCE 219
lair["egg_hidden"] = False
lair["egg_hide_counter"] = 0
else:
lair["egg_hide_counter"] += 1
def check_for_collisions():
global lairs, eggs_collected, lives, reset_required, game_complete
for lair in lairs:
if lair["egg_hidden"] is False:
check_for_egg_collision(lair)
if lair["dragon"].image == "dragon-awake" and reset_required is False:
check_for_dragon_collision(lair)
def check_for_dragon_collision(lair):
x_distance = hero.x - lair["dragon"].x
y_distance = hero.y - lair["dragon"].y
distance = math.hypot(x_distance, y_distance)
if distance < ATTACK_DISTANCE:
handle_dragon_collision()
def handle_dragon_collision():
global reset_required
reset_required = True
animate(hero, pos=HERO_START, on_finished=subtract_life)
def check_for_egg_collision(lair):
global eggs_collected, game_complete
if hero.colliderect(lair["eggs"]):
lair["egg_hidden"] = True
eggs_collected += lair["egg_count"]
if eggs_collected >= EGG_TARGET:
game_complete = True
def subtract_life():
global lives, reset_required, game_over
lives -= 1
if lives == 0:
game_over = True
reset_required = False
Glossary
animation condition event GUI
A process in which A “True or False” Something a computer The GUI, or graphical
images are displayed statement used to program can react to, user interface, is the
one after another make a decision in such as a key being name for the buttons
to make it look like a program. See also pressed or the mouse and windows that make
something’s moving. Boolean expression. being clicked. up the part of the
program you can see
Boolean expression constant file and interact with.
A statement that is either A variable whose A collection
True or False, leading to value should stay of data stored hack
two possible outcomes. the same throughout with a name. An ingenious change
a program. Programmers to code that makes
branch use capital letters when flag variable it do something new
A point in a program naming constants to A variable that can or simplifies it. (Also,
where different let other programmers have two states, such accessing a computer
options are available know that their values as True and False. without permission.)
to choose from. should not be changed.
See also variable. float hacker
bug A number A person who breaks
An error in a program’s coordinates with a decimal into a computer system.
code that makes it behave A pair of numbers point in it. “White hat” hackers work
in an unexpected way. that pinpoint an exact for computer security
location. Usually written flowchart companies and look for
call as (x, y). A diagram that problems in order to fix
To use a function shows a program them. “Black hat” hackers
in a program. data as a sequence of break into computer
Information, such steps and decisions. systems to cause harm or
command line as text, symbols, and to make profit from them.
numerical values. function
The screen that lets you
enter commands into the Code that carries out indent
Command Prompt or dictionary a specific task. Also When a block of code
Terminal window. A collection of data called a procedure, is placed farther to the
items stored in pairs, subprogram, or right than the previous
Command Prompt such as countries and subroutine. block. An indent is usually
An application on their capital cities. four spaces. Every line in
global variable a particular block of code
Windows computers
that allows a user to debug A variable that can be must be indented by the
enter and execute To look for and used throughout every same amount.
commands. correct errors part of a program. See
in a program. also local variable. index number
comment A number given to an
encryption graphics item in a list. In Python,
A text note added to a
program that makes the A way of encoding Visual elements the index number of
code easier to understand data so that only on a screen, such as the first item will be
and is ignored by the certain people can text, pictures, icons, 0, the second item 1,
program when it runs. read or access it. and symbols. and so on.
GLOSSARY 221
Index
Page numbers in bold what happens coordinates 125 Shoot the Fruit 53
refer to main entries. 100–101 count() function Sleeping Dragons
birds 126, 127 41 180, 186
body, of function 122 countdown() function
A Boolean expressions 33 148
Actors 52 Boolean values 32 cow 156, 160 E
animations 126, 127 boxes 100–101, editor window 21
admin access 18 105–06, 108 messages in 44
anchor 92 branching 34–35 D eggs 178, 184, 192, 194
animate() function 83, bugs Dance Challenge animation 191
93, 193 bug-busting checklist 136–53 equals signs 32
animations 92, 126, 127, 47 coding 141–52 error messages 44
181, 191 finding 44 defining actors 143 errors, types 45–47
stopping 94 fixing 25, 44–47 flowchart 140 event handling 151
audio files 141–42 see also hacks hacks and tweaks
and tweaks 153
how it works 140 F
B movement 145–51 fangflowers 156, 160,
Balloon Flight 116–35 C music 140, 142, 152, 168–75
coding 121–33 calculations, shorthand 153 file handling 132, 134
flowchart 120 125 project reference floats 29
hacks and tweaks clock tool 112 207–211 flowcharts 22
133–35 code scoring 150 Balloon Flight 120
how it works 120 colors in 19 what happens Big Quiz 102
lives 133 indenting 23, 43, 55 138–39 Coin Collector 61
project reference Coin Collector 58–67 decisions, making 32–35 Dance Challenge 140
205–207 flowchart 61 dictionaries 184 Follow the Numbers
scoring 123, 124, getting started 61–66 dots, connecting 70–71, 72
130–33 hacks and tweaks 67 77 Happy Garden 158
what happens 118–19 how it works 61 dragons 178–81, 184, Red Alert 84
see also obstacles project reference 190, 193, 195 Shoot the Fruit 51
Big Quiz 98–115 198–199 animation 181 Sleeping Dragons
coding 103–12 what happens 60 draw() function 180–81
flowchart 102 collidepoint() function Balloon Flight 124 flowers 163–69, 174
GUI 101 77, 93 Big Quiz 108 folders 52
hacks and tweaks colliderect() function Coin Collector 63, 65 Follow the Numbers
113–15 165, 192, 194 Dance Challenge 68–79
how it works 102 collisions 77, 129, 165, 143 flowchart 72
interface 104–06 172, 192–94 Follow the Numbers getting started
project reference colors 114–15 75, 79 73–77
203–204 conditions 34 Happy Garden 172, hacks and tweaks
scoring 107 constants 86, 87, 182, 175 78–79
timer 107, 112 183 Red Alert 87 how it works 72
INDEX 223
project reference
199–200
Sleeping Dragons
195
lists 31
looping over 37
P
parameters 40
what happens 70–71 Happy Garden 154–75 lives 133, 193–94 “pass” keyword 64, 144
“for” loops 36–37 coding 159–73 local variables 74 patterns 62
functions 30, 40–43, flowchart 158 logic errors 47 placeholders 64, 144
122 hacks and tweaks loop variable 36 pop() function 102, 108
body 122, 122 174–75 loops 36–39 print() function 40
built-in 44–45 how it works 158 escaping 37 programs
calling 40, 41 project reference for 36–37 rerunning 25
header 122 211–215 infinite 39 running 24–25
making 42–43 scoring 165 while 38–39
what happens Pygame
naming 42
156–57 graphics in 54
using 40
installing 18–19
header, of function 122
hero 178, 185, 187, 188,
M Pygame Zero,
Mac computers 17, 19 installing 18–19
G 192–95
modules 15 Python
games, types 14 hints 113
downloading 15 first program 22–23
garden, drawing 161 houses 128
modulo operator 135, installing 16–17
global variables 74, 86, 153
123 Python 3 16
motion, illusion of 119,
graphical user I-J 128
why use 12
interface see GUI IDLE 16
music, adding 140
graphics, in Pygame 54 colors in code 21
gravity 126 editor window 21 Q
GUI 101 shell window 20 questions
Big Quiz 101 using 20–21 N adding 107
indentation errors 43, 45 numbers, using 29 answering 110
input() function 41 comparing 32
H integers 29
O
skipping 113
hacks and tweaks interface, planning 104 quizzes see Big Quiz
Balloon Flight join function 136 obstacles 118
133–35 collisions with 129
Big Quiz 113–15 multiples of 134 R
Coin Collector 67 K preparing 122 rain 175
Dance Challenge keys 184 on screen 123 randint() function 56, 64,
153 spacing out 135 72, 96, 145
Follow the Numbers on_key_up() function Random module 56
78–79 L 113, 146, 151 random numbers 56
Happy Garden lairs 184–85, 187, 189 on_mouse_down() range 36
174–75 len() function 30 function 55, 72, 77, 93, Raspberry Pi
Red Alert 96–97 levels 34, 78, 92, 135 125 computers 17
Shoot the Fruit line() function 75 open() function read() function 132
57 list comprehension 97 132 Red Alert 80–97
224 REFERENCE
Acknowledgments
DK Publishing would like to thank Caroline Hunt for
proofreading; Jonathan Burd for the index; Daniel Pope for
creating Pygame Zero; Jason Shaw at audionautix.com for the
music for Dance Challenge; Chloe Parry, Phoebe Parry, and
Joshua Parry for user testing; Aashirwad Jain for code testing;
and Isha Sharma for editorial assistance.
Python is copyright © 2001–2018 Python Software Foundation.
All Rights Reserved.