Balloon Flight
Balloon Flight
Flight
118 BALLOON FLIGHT
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