0% found this document useful (0 votes)
85 views19 pages

Balloon Flight

This document provides instructions for building a hot air balloon flight game in Pygame Zero. The game has the player control a hot air balloon to avoid obstacles like birds, houses and trees that appear randomly on the screen. The player moves the balloon up by clicking the mouse button and it falls when not clicking. The game displays the score and high scores. The document outlines setting up the files, images, actors and logic to generate random obstacle positions and check for collisions to end the game.

Uploaded by

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

Balloon Flight

This document provides instructions for building a hot air balloon flight game in Pygame Zero. The game has the player control a hot air balloon to avoid obstacles like birds, houses and trees that appear randomly on the screen. The player moves the balloon up by clicking the mouse button and it falls when not clicking. The game displays the score and high scores. The document outlines setting up the files, images, actors and logic to generate random obstacle positions and check for collisions to end the game.

Uploaded by

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

Balloon

Flight
118 BALLOON FLIGHT

How to build
Balloon Flight A cloudy backdrop
sets the scene.

Take control of your own hot-air


balloon and try to avoid the obstacles
Pygame Zero Game
that come your way as you fly.

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

Watch out for the


bird as it flies across
the screen.

Score: 0
The clouds are part
of the background,
so you don’t need
to avoid them.

The balloon moves up


when you’re pressing
the mouse button and
down when you’re not
pressing it.

◁ 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

Has an obstacle Has the balloon N


disappeared off the collided with an
left side of the screen? obstacle?

Y Add one point Y


to the score

Place obstacle at a Show high scores End


random position
off the right side
of the screen

Has the player


clicked the Make balloon fall
mouse?
N
Y △ Balloon Flight flowchart
This flowchart maps the progress of the
game, which constantly checks for obstacles
Move balloon up disappearing off the screen, mouse clicks, and
collisions between the balloon and the obstacles.
GAME PROGRESS 14% 121
Up, up, and away!
Before you take to the skies, it’s
important to understand the key
elements used to build this game.
The code is a bit long and tricky, so be
extra careful when you’re typing it out.

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.

Save As: balloon.py balloon-flight

Tags: balloon.py
images
background.png
Where: balloon-flight
balloon.png
bird-down.png
bird-up.png
Cancel Save house.png
tree.png

3 Create a file to store the high scores


Next open a new file in IDLE and type the following
balloon.py
balloon-flight

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

Make sure you put a space


between each 0.
IDLE automatically adds .py to a file name.
So remember to change the extension to
.txt when saving the file.

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

5 Set the screen size


Next you need to set the size of the screen 6 Get the balloon ready
Now you need to set up the Actors. First
for your game. Type this code under the add the hot-air balloon, which the player
line from Step 4. controls to play the game.

WIDTH = 800 balloon = Actor("balloon") This line creates


HEIGHT = 600 balloon.pos = 400, 300 a new Actor
using the
This sets the screen balloon image.
size in pixels. This line places the balloon
in the center of the screen.

7 Prepare the obstacles


Next you need to set up the Actors for all the
obstacles in the game. Create one for the bird,
one for the house, and one for the tree.
This line makes the bird
bird = Actor("bird-up") appear at a random position
on the x-axis between 800
bird.pos = randint(800, 1600), randint(10, 200)
and 1600 pixels, and at a
random position on the y-axis
between 10 and 200 pixels.
This line creates a house = Actor("house")
new Actor using the
house.pos = randint(800, 1600), 460
image of the house.

This value makes the


tree = Actor("tree") tree appear on the
grass at the bottom
tree.pos = randint(800, 1600), 450
of the screen.

EXPERT TIPS

Pygame Zero Game


Functions
A function is made up of two
parts—a header and a body.
The header is the first line of the
function that includes the name
The balloon
and any parameters it has. The
has to avoid body is the code that the function
birds, houses, runs when it’s called.
and trees.
Name of the The function’s
function parameters

def add(a, b):


return a + b

Body of the
function
GAME PROGRESS 31% 123

8 Create global variables


You can now set up the global
EXPERT TIPS
variables. Add these lines after the Obstacles on screen
code from Step 7.
In Balloon Flight, the balloon stays in the
This keeps track of the image used for the middle of the screen and the obstacles
bird Actor. The image will be changed later
in the game to make the bird look like it’s
move past it. This makes it look like it’s
flapping its wings. the balloon that’s moving. To make the
obstacles appear at random intervals, the
tree.pos = randint(800, 1600), 450 game chooses a random position for each
one to appear between 800 and 1600
pixels. Because the width of the screen is
bird_up = True 800 pixels, the obstacles will first “appear”
up = False off screen, so you won’t see them right
This line
game_over = False keeps track of away. Later on, you’ll add code to make
the player’s these obstacles move from right to left,
score = 0 score. so the farther off screen an obstacle is
number_of_updates = 0 placed, the longer it will take to appear
on screen. The upper limit is set to 1600
because otherwise the obstacles would
scores = [] take too long to appear.

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

9 Manage the high scores


Next add placeholders for the functions that
The house can appear
anywhere along the x-axis
will manage the high scores. You will need a between 800 and 1600 pixels.
function to update the scores and another to
display them. The bodies of these functions
will be added later on.

scores = []
I must steer clear of
all these obstacles!
def update_high_scores():
pass

def display_high_scores():
pass

Use pass to create a function


placeholder. You can define it later.
124 BALLOON FLIGHT

10 Create the draw() function


Just like in the other games you’ve created, you now
need to add a draw() function to your code. You will also This adds a background
add an image for the game background instead of just a image of the sky, grass,
solid color. Add these lines after the code from Step 9. and clouds.

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

If the game isn’t over, this code


will draw the Actors on screen.

11 Show high scores


In the draw() function, you need to add
else:
display_high_scores()
a call to display_high_scores() when the
game is over. Type this immediately after
the last line of code from Step 10. Remember to add four This won’t do anything yet
spaces before else. because you haven’t written
the body of this function.

12 Test your code


Now try running your code. You should see the Pygame Zero Game
balloon in the middle of the screen and a current
score of zero. There won’t be any obstacles on Score: 0
the screen yet—these will only appear once
you’ve added some code to make them move
onto the screen.

You can see the


background used
in the game.
GAME PROGRESS 45% 125
EXPERT TIPS 13 Reacting to mouse clicks
Now you need to define two event handler
Coordinates functions—on_mouse_down() to make
the balloon rise if the player pushes down
In most programming languages, the coordinates on the mouse button, and on_mouse_up()
(0, 0) refer to the top-left corner of the screen. to let the balloon fall if they release the
Subtracting 50 pixels from the y-coordinate in button. Add this code under what you
on_mouse_down() makes the balloon go 50 typed in Step 11.
pixels closer to 0 on the y-axis, which is the top
of the screen. Therefore, the balloon goes up. else:
display_high_scores()

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 shorter way to write this calculation and


still get the same result is a += 1. You can
also do this with subtraction, multiplication,
and division. For example:

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

14 Make the bird flap


To make the bird more realistic, add a
EXPERT TIPS
function to make it look like it’s flapping Actor animations
its wings. You don’t need to do this for
the other obstacles. You can make your Actors look like they’re moving
by using two or more different images of the same
def flap(): Actor. For example, in this game, there are two images
global bird_up of a bird—one with its wings up and one with its wings
down. By alternating between the two images, it looks
if bird_up:
as if the bird is flapping its wings. The same function
bird.image = "bird-down" could make a person look like they’re dancing, or a frog
bird_up = False look like it’s jumping!
else:
bird.image = "bird-up"
bird_up = True

If the bird’s wings are up, this code


will change its image to the one
where the bird’s wings are down.

15 Create the update() function


Now you need to create a function to
def update():
global game_over, score, number_of_updates
update the game. Remember, update()
is a built-in function that automatically
runs 60 times a second, so you don’t This line declares the
variables the function
need to call it. Add this code right after
must change.
the lines from Step 14.

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 the mouse button

17 Test your code


Let’s run the code again. This time
is not being pressed,
this moves the balloon
down by one pixel.
you’ll see the same screen as in
Step 12, but the balloon should
react to mouse clicks.
GAME PROGRESS 65% 127
Move the bird
18 Next you need to add some code to make it
look like the bird is flying across the screen Get out of the way!
while flapping its wings. This code will move
the bird to the left by four pixels to make it
seem like it’s flying across the screen. If the bird is on the
screen, this will move
it to the left.
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

19 Handle the bird flying off the screen


When the bird disappears off the left edge of the
EXPERT TIPS
screen, you need to move it back to a random Smooth animations
position off the right side of the screen, just
like you did at the beginning of the game. The In Python, the update() function is
height at which the bird appears also needs to automatically called 60 times every
be randomly chosen. Type the following code second. If you change the image of the
immediately after the last line of code in Step 18. bird each time this function is called, it
would just be a blur on the screen. To
make the animation smoother, add a block
Remember to add This code places the bird at of code that will change the image every
eight spaces before a random position off the tenth time the function is called. You can
typing this line. right side of the screen. change this interval if you want. But if the
gap between the updates is too big, the
else: bird will appear to move very slowly.
number_of_updates += 1
else: Dude, you’re so
bird.x = randint(800, 1600) wrong! The actors aren’t
blurry at all!
bird.y = randint(10, 200)
score += 1
number_of_updates = 0

This adds one to the player’s


score for every obstacle that
disappears off the screen.
128 BALLOON FLIGHT

20 Move the house


Just like you made the bird move across the
screen, you now need to make the house move, MOVING VAN
too. Add this code under the lines from Step 19.

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.

This line will update the


score by one if the house
moves off the screen.

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

balloon hits the top or the bottom


of the screen. Type this code under if balloon.top < 0 or balloon.bottom > 560:
the lines from Step 21.
game_over = True
update_high_scores()

This line checks if the


balloon has touched the
top or bottom of the screen.
Handle collisions with obstacles
23 Finally, you need to add some code to This checks if the
end the game if the balloon hits any of balloon has hit any of
the three obstacles. Add the code below. the three obstacles.

update_high_scores()

This sets game_over


to True, which tells if balloon.collidepoint(bird.x, bird.y) or \ Use a backslash
the program that the balloon.collidepoint(house.x, house.y) or \ character if you
game is over. need to split a long
balloon.collidepoint(tree.x, tree.y): line of code over
more than one line.
This updates game_over = True
the high scores, update_high_scores()
if necessary.

Test your code


24 Save your program and run it Pygame Zero Game
from the command line. You
should now be able to play the Score: 0
game, but it’s not quite finished
yet! Next you’ll find out how to
add high scores to your game.

All the obstacles will


now seem to move
across the screen.
130 BALLOON FLIGHT

25 Update the high scores


Now go back to the update_high_scores() function
from Step 9 and write the body. This function gets
the top three high scores and updates them if the
player’s current score has beaten one of them.
Replace pass with the code in black below, then
carefully follow the extra instructions to get the
path for your high-score.txt file.

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.

26 Get the current high scores


To know if the player’s score has beaten any of the
previous scores, you’ll need to read the scores saved
in the high-scores.txt file you created in Step 3. Add This opens the high-scores.txt
file for reading.
this code under the lines from Step 25.

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.

27 Find the highest scores


Now write some code that will check if the current This loops
score has beaten any of the three high scores. through the list
Add this code under the lines from Step 26. of high scores.

high_scores = line.split()
for high_score in high_scores:

This checks if the player’s if(score > int(high_score)):


score is higher than the scores.append(str(score) + " ")
existing high scores.
score = int(high_score)
else:
This sets score to scores.append(str(high_score) + " ")
the high score that
was just beaten.
If the player hasn’t beaten the high If the player’s score is higher
score in question, that current than an existing high score,
high score is added to the list. this adds it to the list.

28 Write the high scores in the file


Use write() to write the new high score
scores.append(str(high_score) + " ")
with open(filename, "w") as file:
to the high-scores.txt file. Add this
code under the code from Step 27. for high_score in scores:
file.write(high_score)

This block writes the new This opens the high-scores.txt


high scores to the .txt file. file to be written to.
132 BALLOON FLIGHT

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

▷ open() takes two parameters, the file name


file = open("names.txt", "r")
and the “mode,”, which tells Python what you
want to do with the file. There are four modes in
Name of Mode
Python: r for reading, w for writing, a for adding
the file
to the end of a file, and r+ for reading and writing.

▽ 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()

▽ You can even add all the lines to a list.

lines = []
▽ Now use the write() function to write to a file.

for line in file:


file = open("names.txt", "w")
lines.append(line)
file.write("Martin")

▽ 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()

Body of the function.


GAME PROGRESS 100% 133

29 Display high scores


Now that you’ve written a function to collect the high scores, you
need to write one to display them on the screen. Replace the word
pass under def display_high_scores() from Step 9 with this code.

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

This adds to the y position, so This line displays the high


that each high score is displayed scores on the screen.
25 pixels below the previous one.

Hacks and tweaks


There are lots of ways you can adapt this
game to make it more complex. Here are
some ideas you can try out.
Phew! I still have
Pygame Zero Game two lives left.

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

I think I read about


file handling on
page 132 as well.

new_high_score = False

Make this number higher △ File handling


bird.x -= 4 In the game, you write to the high-scores.txt file every
to increase the speed.
time the program exits. It would be more efficient to write
△ Speed it up to the file only if the high scores have changed. To code
Do you want to make the game more this, you can use a Boolean variable to track whether
challenging? Why don’t you make the obstacles the high scores have changed. In programming, this is
go faster? You can do this by changing the sometimes referred to as a “flag.” In the game, if the flag
number of pixels the obstacles move by. If you is set to True, then the high scores have changed and
make the bird faster, remember to also update you have to write them back to the file. But if there is no
the flap() function to match the new speed. change, there is no need to write anything to the file.

I didn’t know I could


score points like this!

Name of the second


bird obstacle.

△ Different way to score bird2 = Actor("bird-up")


In the current game, the player scores a point
bird2.pos = randint(800, 1600), randint(10, 200)
every time an obstacle disappears off the left
edge of the screen. You can change the code
so that the player scores every time they pass △ Add in multiples of each obstacle
an obstacle on the screen. Can you figure out Do you find avoiding just one of each obstacle on the
how to do this? Remember the position of the screen too easy? You could change the code so that
balloon always remains at 400 pixels along more than one of each obstacle appears on the screen
the x-axis. at the same time.
HACKS AND TWEAKS 135
▽ Level up
EXPERT TIPS
Make the game more fun by adding levels and increasing
the speed with each level. To do this, you could set the Modulo operator
number of obstacles in each level to ten. To complete the
level, the player must clear all the obstacles and score ten When Python performs division, it ignores the
points. Every time the score reaches a multiple of ten, remainder. But sometimes it’s useful to know if
make the obstacles move faster. In the original game, the there is a remainder and what it is. For example,
birds move by four pixels at a time, and the houses and if you want to test if the number is even, you can
trees move by two. If you want to increase it with every do so by dividing it by 2 and checking if there is
level, you need to store the speed in a variable. Just a remainder. To do this, you can use the modulo
remember that the bird should always be traveling twice operator %.
as fast as the trees and houses.
>>> print(2 % 2)
speed = 2
0
bird.x -= speed * 2
This is 0 because there is no
remainder when 2 is divided by 2.

>>> print(3 % 2)
1

This is the remainder


when 3 is divided by 2.

In Balloon Flight, you can use the modulo


operator to know if the score is a multiple of 10,
and therefore whether the player should move
to the next level.

▽ Space out the obstacles score % 10


Sometimes all the obstacles—the tree, the
house, and the bird—might appear at the same This would return the remainder
position on the x-axis. This works fine, but you when the score is divided by 10.
may want to avoid it. Try to change the update()
function so that the obstacles pick a new random
x coordinate if there is a clash. This code will
help you get started.

if bird.x == house.x

You might also like