A score, waves that get harder, a title and a game over screen, and a saved high score. Four small steps, each one run before it was written down.
▶Prefer to watch? This short video runs this page's main commands on a real Ubuntu 24.04 desktop, with on-screen captions and a synthetic voiceover (an AI voice trained on the author's own recording). Click to play, or watch it on YouTube.
Episode 7 ends with this: a title screen, a game with a score, a wave counter and three lives on screen, waves that get bigger and faster, a game over screen, and a best score that is still there the next time you start the game.
You will need: your project from episode 6 (a game.py, an art folder and the .venv), or the starter files below.
You will make: a text helper and a display (HUD), a wave counter with a boost, a game state, and a small save file.
You will learn: drawing text with a font, a state as a string, splitting update in two, reading and writing a JSON file safely.
Starter files: burger-blaster-ep06.zip is where this episode begins, burger-blaster-ep07.zip is where it ends. Both have the art folder.
The code on this page was run on a clean Ubuntu 24.04 desktop with Python 3.12.3 and pygame 2.6.1. Each of the four steps was run on its own, and what it does is described below.
Where we start
Open a terminal, go to the project, turn on the virtual environment and run the game:
$ cd burger-blaster
$ source .venv/bin/activate
(.venv) $ python game.py
The burger shoots and gets hit, there are three lives and a safe time, but nothing is shown on the screen, the game starts at once and there is no score. The file is 254 lines. Most of the changes this time are in class Game.
Step 1: the score and the lives
Pygame draws text with a Font. A small helper draws it with a shadow, a method draws the display (the HUD), and pop adds to the score. The whole file after step 1:
#!/usr/bin/env python3
"""Burger Blaster: a hamburger shoots french fries at angry milkshakes."""
import random
import sys
from pathlib import Path
import pygame
WIDTH, HEIGHT = 1280, 720
FPS = 60
HERE = Path(__file__).resolve().parent
ART = HERE / "art"
TURN_SPEED = 220 # degrees per second
THRUST = 420 # pixels per second, every second
FRICTION = 0.55 # share of speed left after one second of coasting
MAX_SPEED = 480
FRY_SPEED = 720
FRY_LIFE = 0.9 # seconds before a fry disappears
SHOOT_DELAY = 0.22 # seconds between shots
FLAVORS = ["strawberry", "chocolate", "mint"]
IMG = {}
def load_images():
return {p.stem: pygame.image.load(p).convert_alpha() for p in ART.glob("*.png")}
def wrap(pos, margin=40):
"""Leave one side of the screen, come back on the other."""
pos.x = (pos.x + margin) % (WIDTH + 2 * margin) - margin
pos.y = (pos.y + margin) % (HEIGHT + 2 * margin) - margin
def draw_rotated(surf, image, pos, angle):
rotated = pygame.transform.rotate(image, -angle) # pygame turns counter-clockwise
surf.blit(rotated, rotated.get_rect(center=pos))
class Player:
radius = 34
def __init__(self):
self.reset()
def reset(self):
self.pos = pygame.Vector2(WIDTH / 2, HEIGHT / 2)
self.vel = pygame.Vector2()
self.angle = 0 # degrees, 0 = up, clockwise
self.cooldown = 0
self.invulnerable = 0
def direction(self):
return pygame.Vector2(0, -1).rotate(self.angle)
def update(self, dt, keys):
if keys[pygame.K_LEFT]:
self.angle -= TURN_SPEED * dt
if keys[pygame.K_RIGHT]:
self.angle += TURN_SPEED * dt
if keys[pygame.K_UP]:
self.vel += self.direction() * THRUST * dt
self.vel *= FRICTION**dt
if self.vel.length() > MAX_SPEED:
self.vel.scale_to_length(MAX_SPEED)
self.pos += self.vel * dt
wrap(self.pos)
self.cooldown -= dt
self.invulnerable -= dt
def shoot(self, keys):
if keys[pygame.K_SPACE] and self.cooldown <= 0:
self.cooldown = SHOOT_DELAY
return Fry(self.pos + self.direction() * 44, self.direction(), self.angle)
def draw(self, surf):
if self.invulnerable > 0 and int(self.invulnerable * 10) % 2:
return # blink while safe
draw_rotated(surf, IMG["burger"], self.pos, self.angle)
class Fry:
radius = 8
def __init__(self, pos, direction, angle):
self.pos = pygame.Vector2(pos)
self.vel = direction * FRY_SPEED
self.angle = angle
self.life = FRY_LIFE
def update(self, dt):
self.pos += self.vel * dt
wrap(self.pos)
self.life -= dt
def draw(self, surf):
draw_rotated(surf, IMG["fry"], self.pos, self.angle)
class Shake:
def __init__(self, pos, size, flavor, boost=1.0):
self.pos = pygame.Vector2(pos)
self.size = size # "big" or "small"
self.flavor = flavor
self.boost = boost
self.radius = 50 if size == "big" else 25
speed = random.uniform(60, 130) if size == "big" else random.uniform(110, 200)
self.vel = pygame.Vector2(speed * boost, 0).rotate(random.uniform(0, 360))
self.angle = random.uniform(0, 360)
self.spin = random.uniform(-90, 90)
self.image = IMG[f"shake_{flavor}" if size == "big" else f"shake_{flavor}_small"]
def update(self, dt):
self.pos += self.vel * dt
self.angle += self.spin * dt
wrap(self.pos, 70)
def draw(self, surf):
draw_rotated(surf, self.image, self.pos, self.angle)
class Splat:
"""A short animation where a shake used to be."""
DURATION = 0.4
def __init__(self, pos, flavor):
self.pos = pygame.Vector2(pos)
self.flavor = flavor
self.age = 0
def update(self, dt):
self.age += dt
def draw(self, surf):
frame = min(int(self.age / self.DURATION * 5), 4)
image = IMG[f"splat_{self.flavor}_{frame}"]
surf.blit(image, image.get_rect(center=self.pos))
class Game:
def __init__(self):
pygame.init()
pygame.display.set_caption("Burger Blaster")
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.clock = pygame.time.Clock()
IMG.update(load_images())
self.running = True
self.player = Player()
self.fries = []
self.shakes = []
self.splats = []
self.font = pygame.font.Font(None, 52)
self.new_game()
def new_game(self):
self.score = 0
self.lives = 3
self.player.reset()
self.fries.clear()
self.shakes.clear()
self.splats.clear()
def spawn_shakes(self, count):
for _ in range(count):
while True: # keep new shakes away from the burger
pos = pygame.Vector2(random.uniform(0, WIDTH), random.uniform(0, HEIGHT))
if pos.distance_to(self.player.pos) > 300:
break
self.shakes.append(Shake(pos, "big", random.choice(FLAVORS)))
def pop(self, shake):
"""A fry hit a shake: big ones split in two, small ones splat."""
self.shakes.remove(shake)
self.splats.append(Splat(shake.pos, shake.flavor))
self.score += 20 if shake.size == "big" else 50
if shake.size == "big":
for _ in range(2):
self.shakes.append(Shake(shake.pos, "small", shake.flavor, shake.boost))
def check_fry_hits(self):
for fry in self.fries:
if fry.life <= 0:
continue
for shake in self.shakes:
if fry.pos.distance_to(shake.pos) < shake.radius + fry.radius:
fry.life = 0
self.pop(shake)
break
def check_player_hit(self):
player = self.player
if player.invulnerable > 0:
return
for shake in self.shakes:
if player.pos.distance_to(shake.pos) < player.radius + shake.radius * 0.8:
self.splats.append(Splat(player.pos, "chocolate"))
self.lives -= 1
player.reset()
player.invulnerable = 2.0
if self.lives == 0:
self.new_game()
return
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.running = False
def update(self, dt):
keys = pygame.key.get_pressed()
self.player.update(dt, keys)
fry = self.player.shoot(keys)
if fry:
self.fries.append(fry)
for fry in self.fries:
fry.update(dt)
self.fries = [f for f in self.fries if f.life > 0]
for shake in self.shakes:
shake.update(dt)
if not self.shakes:
self.spawn_shakes(4)
self.check_fry_hits()
self.check_player_hit()
for splat in self.splats:
splat.update(dt)
self.splats = [s for s in self.splats if s.age < Splat.DURATION]
def draw_text(self, surf, text, font, center, color=(255, 255, 255)):
shadow = font.render(text, True, (20, 20, 40))
surf.blit(shadow, shadow.get_rect(center=(center[0] + 3, center[1] + 4)))
label = font.render(text, True, color)
surf.blit(label, label.get_rect(center=center))
def draw_hud(self, surf):
self.draw_text(surf, f"Score {self.score}", self.font, (130, 36))
for i in range(self.lives):
surf.blit(IMG["life"], (24 + i * 46, HEIGHT - 60))
def draw(self):
surf = self.screen
surf.blit(IMG["background"], (0, 0))
for splat in self.splats:
splat.draw(surf)
for shake in self.shakes:
shake.draw(surf)
for fry in self.fries:
fry.draw(surf)
self.player.draw(surf)
self.draw_hud(surf)
pygame.display.flip()
def run(self):
while self.running:
dt = self.clock.tick(FPS) / 1000
self.handle_events()
self.update(dt)
self.draw()
pygame.quit()
if __name__ == "__main__":
Game().run()
sys.exit(0)
What is new:
pygame.font.Font(None, 52) None is pygame's built-in default font, at size 52
font.render(text, True, color) makes a picture of the text. True switches on smoothing (anti-aliasing)
draw_text draws the text twice: once in a dark color, 3 pixels right and 4 pixels down, and then in the real color on top. The shadow keeps white text readable on any background
get_rect(center=...) the text picture is placed by its centre, like the burger and the shakes
f"Score {self.score}" an f-string puts the number into the text
for i in range(self.lives): blit one small burger (the life.png picture) for each life, 46 pixels apart, along the bottom
self.score += 20 if big else 50 in pop. A small shake is worth more, because it is faster and harder to hit
Run it:
(.venv) $ python game.py
The score counts up as you shoot, and there are three small burgers in the bottom left corner, one of which disappears with every hit. (Checked in the lab: one hit on a big shake gave 20 points, a hit on a small one gave 50 more, 70 in all.)
Step 2: waves
A wave is a group of shakes, and the next one starts a little after the last shake is gone. Each wave is bigger and a bit faster. The whole file after step 2:
#!/usr/bin/env python3
"""Burger Blaster: a hamburger shoots french fries at angry milkshakes."""
import random
import sys
from pathlib import Path
import pygame
WIDTH, HEIGHT = 1280, 720
FPS = 60
HERE = Path(__file__).resolve().parent
ART = HERE / "art"
TURN_SPEED = 220 # degrees per second
THRUST = 420 # pixels per second, every second
FRICTION = 0.55 # share of speed left after one second of coasting
MAX_SPEED = 480
FRY_SPEED = 720
FRY_LIFE = 0.9 # seconds before a fry disappears
SHOOT_DELAY = 0.22 # seconds between shots
FLAVORS = ["strawberry", "chocolate", "mint"]
IMG = {}
def load_images():
return {p.stem: pygame.image.load(p).convert_alpha() for p in ART.glob("*.png")}
def wrap(pos, margin=40):
"""Leave one side of the screen, come back on the other."""
pos.x = (pos.x + margin) % (WIDTH + 2 * margin) - margin
pos.y = (pos.y + margin) % (HEIGHT + 2 * margin) - margin
def draw_rotated(surf, image, pos, angle):
rotated = pygame.transform.rotate(image, -angle) # pygame turns counter-clockwise
surf.blit(rotated, rotated.get_rect(center=pos))
class Player:
radius = 34
def __init__(self):
self.reset()
def reset(self):
self.pos = pygame.Vector2(WIDTH / 2, HEIGHT / 2)
self.vel = pygame.Vector2()
self.angle = 0 # degrees, 0 = up, clockwise
self.cooldown = 0
self.invulnerable = 0
def direction(self):
return pygame.Vector2(0, -1).rotate(self.angle)
def update(self, dt, keys):
if keys[pygame.K_LEFT]:
self.angle -= TURN_SPEED * dt
if keys[pygame.K_RIGHT]:
self.angle += TURN_SPEED * dt
if keys[pygame.K_UP]:
self.vel += self.direction() * THRUST * dt
self.vel *= FRICTION**dt
if self.vel.length() > MAX_SPEED:
self.vel.scale_to_length(MAX_SPEED)
self.pos += self.vel * dt
wrap(self.pos)
self.cooldown -= dt
self.invulnerable -= dt
def shoot(self, keys):
if keys[pygame.K_SPACE] and self.cooldown <= 0:
self.cooldown = SHOOT_DELAY
return Fry(self.pos + self.direction() * 44, self.direction(), self.angle)
def draw(self, surf):
if self.invulnerable > 0 and int(self.invulnerable * 10) % 2:
return # blink while safe
draw_rotated(surf, IMG["burger"], self.pos, self.angle)
class Fry:
radius = 8
def __init__(self, pos, direction, angle):
self.pos = pygame.Vector2(pos)
self.vel = direction * FRY_SPEED
self.angle = angle
self.life = FRY_LIFE
def update(self, dt):
self.pos += self.vel * dt
wrap(self.pos)
self.life -= dt
def draw(self, surf):
draw_rotated(surf, IMG["fry"], self.pos, self.angle)
class Shake:
def __init__(self, pos, size, flavor, boost=1.0):
self.pos = pygame.Vector2(pos)
self.size = size # "big" or "small"
self.flavor = flavor
self.boost = boost
self.radius = 50 if size == "big" else 25
speed = random.uniform(60, 130) if size == "big" else random.uniform(110, 200)
self.vel = pygame.Vector2(speed * boost, 0).rotate(random.uniform(0, 360))
self.angle = random.uniform(0, 360)
self.spin = random.uniform(-90, 90)
self.image = IMG[f"shake_{flavor}" if size == "big" else f"shake_{flavor}_small"]
def update(self, dt):
self.pos += self.vel * dt
self.angle += self.spin * dt
wrap(self.pos, 70)
def draw(self, surf):
draw_rotated(surf, self.image, self.pos, self.angle)
class Splat:
"""A short animation where a shake used to be."""
DURATION = 0.4
def __init__(self, pos, flavor):
self.pos = pygame.Vector2(pos)
self.flavor = flavor
self.age = 0
def update(self, dt):
self.age += dt
def draw(self, surf):
frame = min(int(self.age / self.DURATION * 5), 4)
image = IMG[f"splat_{self.flavor}_{frame}"]
surf.blit(image, image.get_rect(center=self.pos))
class Game:
def __init__(self):
pygame.init()
pygame.display.set_caption("Burger Blaster")
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.clock = pygame.time.Clock()
IMG.update(load_images())
self.running = True
self.player = Player()
self.fries = []
self.shakes = []
self.splats = []
self.font = pygame.font.Font(None, 52)
self.new_game()
def new_game(self):
self.score = 0
self.lives = 3
self.wave = 0
self.wave_timer = 0
self.player.reset()
self.fries.clear()
self.shakes.clear()
self.splats.clear()
def spawn_shakes(self, count):
for _ in range(count):
while True: # keep new shakes away from the burger
pos = pygame.Vector2(random.uniform(0, WIDTH), random.uniform(0, HEIGHT))
if pos.distance_to(self.player.pos) > 300:
break
boost = 1 + 0.12 * (self.wave - 1)
self.shakes.append(Shake(pos, "big", random.choice(FLAVORS), boost))
def pop(self, shake):
"""A fry hit a shake: big ones split in two, small ones splat."""
self.shakes.remove(shake)
self.splats.append(Splat(shake.pos, shake.flavor))
self.score += 20 if shake.size == "big" else 50
if shake.size == "big":
for _ in range(2):
self.shakes.append(Shake(shake.pos, "small", shake.flavor, shake.boost))
def check_fry_hits(self):
for fry in self.fries:
if fry.life <= 0:
continue
for shake in self.shakes:
if fry.pos.distance_to(shake.pos) < shake.radius + fry.radius:
fry.life = 0
self.pop(shake)
break
def check_player_hit(self):
player = self.player
if player.invulnerable > 0:
return
for shake in self.shakes:
if player.pos.distance_to(shake.pos) < player.radius + shake.radius * 0.8:
self.splats.append(Splat(player.pos, "chocolate"))
self.lives -= 1
player.reset()
player.invulnerable = 2.0
if self.lives == 0:
self.new_game()
return
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.running = False
def update(self, dt):
keys = pygame.key.get_pressed()
self.player.update(dt, keys)
fry = self.player.shoot(keys)
if fry:
self.fries.append(fry)
for fry in self.fries:
fry.update(dt)
self.fries = [f for f in self.fries if f.life > 0]
for shake in self.shakes:
shake.update(dt)
self.wave_timer -= dt if not self.shakes else 0
if not self.shakes and self.wave_timer <= 0:
self.wave += 1
self.spawn_shakes(2 + self.wave)
self.wave_timer = 1.5
self.check_fry_hits()
self.check_player_hit()
for splat in self.splats:
splat.update(dt)
self.splats = [s for s in self.splats if s.age < Splat.DURATION]
def draw_text(self, surf, text, font, center, color=(255, 255, 255)):
shadow = font.render(text, True, (20, 20, 40))
surf.blit(shadow, shadow.get_rect(center=(center[0] + 3, center[1] + 4)))
label = font.render(text, True, color)
surf.blit(label, label.get_rect(center=center))
def draw_hud(self, surf):
self.draw_text(surf, f"Score {self.score}", self.font, (130, 36))
self.draw_text(surf, f"Wave {self.wave}", self.font, (WIDTH / 2, 36))
for i in range(self.lives):
surf.blit(IMG["life"], (24 + i * 46, HEIGHT - 60))
def draw(self):
surf = self.screen
surf.blit(IMG["background"], (0, 0))
for splat in self.splats:
splat.draw(surf)
for shake in self.shakes:
shake.draw(surf)
for fry in self.fries:
fry.draw(surf)
self.player.draw(surf)
self.draw_hud(surf)
pygame.display.flip()
def run(self):
while self.running:
dt = self.clock.tick(FPS) / 1000
self.handle_events()
self.update(dt)
self.draw()
pygame.quit()
if __name__ == "__main__":
Game().run()
sys.exit(0)
What is new:
self.wave, self.wave_timer the number of the wave, and a timer in seconds, both set to 0 in new_game
self.wave_timer -= dt if not self.shakes else 0 the timer only counts down while the screen is empty
if not self.shakes and self.wave_timer <= 0 the wave is cleared, and the pause is over
self.wave += 1; spawn_shakes(2 + self.wave) wave 1 has 3 shakes, wave 2 has 4, wave 3 has 5
self.wave_timer = 1.5 the pause before the next wave: one and a half seconds
boost = 1 + 0.12 * (self.wave - 1) wave 1 has a boost of 1.0, wave 2 of 1.12, wave 3 of 1.24. It is the number that the Shake class from episode 4 multiplies its speed with, so every wave is 12 percent faster than the one before
the 'Wave' line in draw_hud the number of the wave, in the middle at the top
Run it:
(.venv) $ python game.py
The first wave has three shakes. When you have cleared them and all their pieces there is a short pause, and then wave 2 arrives, with four shakes, a little faster. (Checked in the lab: waves 1 to 4 had 3, 4, 5 and 6 shakes, with boosts of 1.0, 1.12, 1.24 and 1.36.)
Step 3: a title screen and game over
A game is more than play. It has a title screen and a game over screen, and what the game does depends on which one it is in. That is a state: a word, here "title", "play" or "over", stored in self.state. The whole file after step 3:
#!/usr/bin/env python3
"""Burger Blaster: a hamburger shoots french fries at angry milkshakes."""
import random
import sys
from pathlib import Path
import pygame
WIDTH, HEIGHT = 1280, 720
FPS = 60
HERE = Path(__file__).resolve().parent
ART = HERE / "art"
TURN_SPEED = 220 # degrees per second
THRUST = 420 # pixels per second, every second
FRICTION = 0.55 # share of speed left after one second of coasting
MAX_SPEED = 480
FRY_SPEED = 720
FRY_LIFE = 0.9 # seconds before a fry disappears
SHOOT_DELAY = 0.22 # seconds between shots
FLAVORS = ["strawberry", "chocolate", "mint"]
IMG = {}
def load_images():
return {p.stem: pygame.image.load(p).convert_alpha() for p in ART.glob("*.png")}
def wrap(pos, margin=40):
"""Leave one side of the screen, come back on the other."""
pos.x = (pos.x + margin) % (WIDTH + 2 * margin) - margin
pos.y = (pos.y + margin) % (HEIGHT + 2 * margin) - margin
def draw_rotated(surf, image, pos, angle):
rotated = pygame.transform.rotate(image, -angle) # pygame turns counter-clockwise
surf.blit(rotated, rotated.get_rect(center=pos))
class Player:
radius = 34
def __init__(self):
self.reset()
def reset(self):
self.pos = pygame.Vector2(WIDTH / 2, HEIGHT / 2)
self.vel = pygame.Vector2()
self.angle = 0 # degrees, 0 = up, clockwise
self.cooldown = 0
self.invulnerable = 0
def direction(self):
return pygame.Vector2(0, -1).rotate(self.angle)
def update(self, dt, keys):
if keys[pygame.K_LEFT]:
self.angle -= TURN_SPEED * dt
if keys[pygame.K_RIGHT]:
self.angle += TURN_SPEED * dt
if keys[pygame.K_UP]:
self.vel += self.direction() * THRUST * dt
self.vel *= FRICTION**dt
if self.vel.length() > MAX_SPEED:
self.vel.scale_to_length(MAX_SPEED)
self.pos += self.vel * dt
wrap(self.pos)
self.cooldown -= dt
self.invulnerable -= dt
def shoot(self, keys):
if keys[pygame.K_SPACE] and self.cooldown <= 0:
self.cooldown = SHOOT_DELAY
return Fry(self.pos + self.direction() * 44, self.direction(), self.angle)
def draw(self, surf):
if self.invulnerable > 0 and int(self.invulnerable * 10) % 2:
return # blink while safe
draw_rotated(surf, IMG["burger"], self.pos, self.angle)
class Fry:
radius = 8
def __init__(self, pos, direction, angle):
self.pos = pygame.Vector2(pos)
self.vel = direction * FRY_SPEED
self.angle = angle
self.life = FRY_LIFE
def update(self, dt):
self.pos += self.vel * dt
wrap(self.pos)
self.life -= dt
def draw(self, surf):
draw_rotated(surf, IMG["fry"], self.pos, self.angle)
class Shake:
def __init__(self, pos, size, flavor, boost=1.0):
self.pos = pygame.Vector2(pos)
self.size = size # "big" or "small"
self.flavor = flavor
self.boost = boost
self.radius = 50 if size == "big" else 25
speed = random.uniform(60, 130) if size == "big" else random.uniform(110, 200)
self.vel = pygame.Vector2(speed * boost, 0).rotate(random.uniform(0, 360))
self.angle = random.uniform(0, 360)
self.spin = random.uniform(-90, 90)
self.image = IMG[f"shake_{flavor}" if size == "big" else f"shake_{flavor}_small"]
def update(self, dt):
self.pos += self.vel * dt
self.angle += self.spin * dt
wrap(self.pos, 70)
def draw(self, surf):
draw_rotated(surf, self.image, self.pos, self.angle)
class Splat:
"""A short animation where a shake used to be."""
DURATION = 0.4
def __init__(self, pos, flavor):
self.pos = pygame.Vector2(pos)
self.flavor = flavor
self.age = 0
def update(self, dt):
self.age += dt
def draw(self, surf):
frame = min(int(self.age / self.DURATION * 5), 4)
image = IMG[f"splat_{self.flavor}_{frame}"]
surf.blit(image, image.get_rect(center=self.pos))
class Game:
def __init__(self):
pygame.init()
pygame.display.set_caption("Burger Blaster")
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.clock = pygame.time.Clock()
IMG.update(load_images())
self.running = True
self.player = Player()
self.fries = []
self.shakes = []
self.splats = []
self.font = pygame.font.Font(None, 52)
self.big_font = pygame.font.Font(None, 150)
self.state = "title"
self.new_game()
def new_game(self):
self.score = 0
self.lives = 3
self.wave = 0
self.wave_timer = 0
self.player.reset()
self.fries.clear()
self.shakes.clear()
self.splats.clear()
def spawn_shakes(self, count):
for _ in range(count):
while True: # keep new shakes away from the burger
pos = pygame.Vector2(random.uniform(0, WIDTH), random.uniform(0, HEIGHT))
if pos.distance_to(self.player.pos) > 300:
break
boost = 1 + 0.12 * (self.wave - 1)
self.shakes.append(Shake(pos, "big", random.choice(FLAVORS), boost))
def pop(self, shake):
"""A fry hit a shake: big ones split in two, small ones splat."""
self.shakes.remove(shake)
self.splats.append(Splat(shake.pos, shake.flavor))
self.score += 20 if shake.size == "big" else 50
if shake.size == "big":
for _ in range(2):
self.shakes.append(Shake(shake.pos, "small", shake.flavor, shake.boost))
def check_fry_hits(self):
for fry in self.fries:
if fry.life <= 0:
continue
for shake in self.shakes:
if fry.pos.distance_to(shake.pos) < shake.radius + fry.radius:
fry.life = 0
self.pop(shake)
break
def check_player_hit(self):
player = self.player
if player.invulnerable > 0:
return
for shake in self.shakes:
if player.pos.distance_to(shake.pos) < player.radius + shake.radius * 0.8:
self.splats.append(Splat(player.pos, "chocolate"))
self.lives -= 1
player.reset()
player.invulnerable = 2.0
if self.lives == 0:
self.game_over()
return
def game_over(self):
self.state = "over"
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.running = False
elif event.key == pygame.K_RETURN and self.state != "play":
self.new_game()
self.state = "play"
def update(self, dt):
if self.state == "play":
self.update_play(dt)
for splat in self.splats:
splat.update(dt)
self.splats = [s for s in self.splats if s.age < Splat.DURATION]
def update_play(self, dt):
keys = pygame.key.get_pressed()
self.player.update(dt, keys)
fry = self.player.shoot(keys)
if fry:
self.fries.append(fry)
for fry in self.fries:
fry.update(dt)
self.fries = [f for f in self.fries if f.life > 0]
for shake in self.shakes:
shake.update(dt)
self.wave_timer -= dt if not self.shakes else 0
if not self.shakes and self.wave_timer <= 0:
self.wave += 1
self.spawn_shakes(2 + self.wave)
self.wave_timer = 1.5
self.check_fry_hits()
self.check_player_hit()
def draw_text(self, surf, text, font, center, color=(255, 255, 255)):
shadow = font.render(text, True, (20, 20, 40))
surf.blit(shadow, shadow.get_rect(center=(center[0] + 3, center[1] + 4)))
label = font.render(text, True, color)
surf.blit(label, label.get_rect(center=center))
def draw_hud(self, surf):
self.draw_text(surf, f"Score {self.score}", self.font, (130, 36))
self.draw_text(surf, f"Wave {self.wave}", self.font, (WIDTH / 2, 36))
for i in range(self.lives):
surf.blit(IMG["life"], (24 + i * 46, HEIGHT - 60))
def draw(self):
surf = self.screen
surf.blit(IMG["background"], (0, 0))
for splat in self.splats:
splat.draw(surf)
for shake in self.shakes:
shake.draw(surf)
for fry in self.fries:
fry.draw(surf)
if self.state == "play":
self.player.draw(surf)
if self.state == "play":
self.draw_hud(surf)
elif self.state == "title":
self.draw_text(surf, "BURGER BLASTER", self.big_font, (WIDTH / 2, 250))
self.draw_text(surf, "Arrow keys fly, Space fires", self.font, (WIDTH / 2, 380))
self.draw_text(surf, "Press Enter to start", self.font, (WIDTH / 2, 450), (255, 220, 90))
else:
self.draw_text(surf, "GAME OVER", self.big_font, (WIDTH / 2, 250))
self.draw_text(surf, f"Score {self.score}", self.font, (WIDTH / 2, 380))
self.draw_text(surf, "Press Enter to play again", self.font, (WIDTH / 2, 450), (255, 220, 90))
pygame.display.flip()
def run(self):
while self.running:
dt = self.clock.tick(FPS) / 1000
self.handle_events()
self.update(dt)
self.draw()
pygame.quit()
if __name__ == "__main__":
Game().run()
sys.exit(0)
What is new:
self.state = "title" the game starts on the title screen
update and update_play update is split in two. update runs update_play only when the state is "play" (everything that used to be in update moved there), and animates the splats in every state, so a splat that is playing when the last life goes does not freeze
K_RETURN and self.state != "play" Enter starts a new game from the title and from the game over screen, and does nothing during play
game_over() a method that only sets the state to "over". Before, check_player_hit called new_game, which started again at once
draw an if / elif / else on the state: in play, the burger and the HUD; on the title, the name of the game and the instructions; otherwise the game over screen with the score
big_font = Font(None, 150) a bigger font for the headlines
Run it:
(.venv) $ python game.py
The title screen, then Enter starts the game. When the last life is gone the game over screen shows the score, and Enter starts a new game with the score back at 0 and three lives. (Checked in the lab: the game starts in "title", Enter makes it "play", the last hit makes it "over", and Enter again gives "play" with score 0 and 3 lives.)
Step 4: the high score
The best score should survive the game being closed. A small JSON file in the user's data folder holds it. The whole file after step 4, which is also the file in burger-blaster-ep07.zip:
#!/usr/bin/env python3
"""Burger Blaster: a hamburger shoots french fries at angry milkshakes."""
import json
import os
import random
import sys
from pathlib import Path
import pygame
WIDTH, HEIGHT = 1280, 720
FPS = 60
HERE = Path(__file__).resolve().parent
ART = HERE / "art"
SAVE = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "burger-blaster" / "highscore.json"
TURN_SPEED = 220 # degrees per second
THRUST = 420 # pixels per second, every second
FRICTION = 0.55 # share of speed left after one second of coasting
MAX_SPEED = 480
FRY_SPEED = 720
FRY_LIFE = 0.9 # seconds before a fry disappears
SHOOT_DELAY = 0.22 # seconds between shots
FLAVORS = ["strawberry", "chocolate", "mint"]
IMG = {}
def load_images():
return {p.stem: pygame.image.load(p).convert_alpha() for p in ART.glob("*.png")}
def load_high():
try:
return json.loads(SAVE.read_text())["high"]
except (OSError, ValueError, KeyError):
return 0
def save_high(score):
SAVE.parent.mkdir(parents=True, exist_ok=True)
SAVE.write_text(json.dumps({"high": score}))
def wrap(pos, margin=40):
"""Leave one side of the screen, come back on the other."""
pos.x = (pos.x + margin) % (WIDTH + 2 * margin) - margin
pos.y = (pos.y + margin) % (HEIGHT + 2 * margin) - margin
def draw_rotated(surf, image, pos, angle):
rotated = pygame.transform.rotate(image, -angle) # pygame turns counter-clockwise
surf.blit(rotated, rotated.get_rect(center=pos))
class Player:
radius = 34
def __init__(self):
self.reset()
def reset(self):
self.pos = pygame.Vector2(WIDTH / 2, HEIGHT / 2)
self.vel = pygame.Vector2()
self.angle = 0 # degrees, 0 = up, clockwise
self.cooldown = 0
self.invulnerable = 0
def direction(self):
return pygame.Vector2(0, -1).rotate(self.angle)
def update(self, dt, keys):
if keys[pygame.K_LEFT]:
self.angle -= TURN_SPEED * dt
if keys[pygame.K_RIGHT]:
self.angle += TURN_SPEED * dt
if keys[pygame.K_UP]:
self.vel += self.direction() * THRUST * dt
self.vel *= FRICTION**dt
if self.vel.length() > MAX_SPEED:
self.vel.scale_to_length(MAX_SPEED)
self.pos += self.vel * dt
wrap(self.pos)
self.cooldown -= dt
self.invulnerable -= dt
def shoot(self, keys):
if keys[pygame.K_SPACE] and self.cooldown <= 0:
self.cooldown = SHOOT_DELAY
return Fry(self.pos + self.direction() * 44, self.direction(), self.angle)
def draw(self, surf):
if self.invulnerable > 0 and int(self.invulnerable * 10) % 2:
return # blink while safe
draw_rotated(surf, IMG["burger"], self.pos, self.angle)
class Fry:
radius = 8
def __init__(self, pos, direction, angle):
self.pos = pygame.Vector2(pos)
self.vel = direction * FRY_SPEED
self.angle = angle
self.life = FRY_LIFE
def update(self, dt):
self.pos += self.vel * dt
wrap(self.pos)
self.life -= dt
def draw(self, surf):
draw_rotated(surf, IMG["fry"], self.pos, self.angle)
class Shake:
def __init__(self, pos, size, flavor, boost=1.0):
self.pos = pygame.Vector2(pos)
self.size = size # "big" or "small"
self.flavor = flavor
self.boost = boost
self.radius = 50 if size == "big" else 25
speed = random.uniform(60, 130) if size == "big" else random.uniform(110, 200)
self.vel = pygame.Vector2(speed * boost, 0).rotate(random.uniform(0, 360))
self.angle = random.uniform(0, 360)
self.spin = random.uniform(-90, 90)
self.image = IMG[f"shake_{flavor}" if size == "big" else f"shake_{flavor}_small"]
def update(self, dt):
self.pos += self.vel * dt
self.angle += self.spin * dt
wrap(self.pos, 70)
def draw(self, surf):
draw_rotated(surf, self.image, self.pos, self.angle)
class Splat:
"""A short animation where a shake used to be."""
DURATION = 0.4
def __init__(self, pos, flavor):
self.pos = pygame.Vector2(pos)
self.flavor = flavor
self.age = 0
def update(self, dt):
self.age += dt
def draw(self, surf):
frame = min(int(self.age / self.DURATION * 5), 4)
image = IMG[f"splat_{self.flavor}_{frame}"]
surf.blit(image, image.get_rect(center=self.pos))
class Game:
def __init__(self):
pygame.init()
pygame.display.set_caption("Burger Blaster")
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.clock = pygame.time.Clock()
IMG.update(load_images())
self.running = True
self.player = Player()
self.fries = []
self.shakes = []
self.splats = []
self.font = pygame.font.Font(None, 52)
self.big_font = pygame.font.Font(None, 150)
self.high = load_high()
self.state = "title"
self.new_game()
def new_game(self):
self.score = 0
self.lives = 3
self.wave = 0
self.wave_timer = 0
self.player.reset()
self.fries.clear()
self.shakes.clear()
self.splats.clear()
def spawn_shakes(self, count):
for _ in range(count):
while True: # keep new shakes away from the burger
pos = pygame.Vector2(random.uniform(0, WIDTH), random.uniform(0, HEIGHT))
if pos.distance_to(self.player.pos) > 300:
break
boost = 1 + 0.12 * (self.wave - 1)
self.shakes.append(Shake(pos, "big", random.choice(FLAVORS), boost))
def pop(self, shake):
"""A fry hit a shake: big ones split in two, small ones splat."""
self.shakes.remove(shake)
self.splats.append(Splat(shake.pos, shake.flavor))
self.score += 20 if shake.size == "big" else 50
if shake.size == "big":
for _ in range(2):
self.shakes.append(Shake(shake.pos, "small", shake.flavor, shake.boost))
def check_fry_hits(self):
for fry in self.fries:
if fry.life <= 0:
continue
for shake in self.shakes:
if fry.pos.distance_to(shake.pos) < shake.radius + fry.radius:
fry.life = 0
self.pop(shake)
break
def check_player_hit(self):
player = self.player
if player.invulnerable > 0:
return
for shake in self.shakes:
if player.pos.distance_to(shake.pos) < player.radius + shake.radius * 0.8:
self.splats.append(Splat(player.pos, "chocolate"))
self.lives -= 1
player.reset()
player.invulnerable = 2.0
if self.lives == 0:
self.game_over()
return
def game_over(self):
self.state = "over"
if self.score > self.high:
self.high = self.score
save_high(self.high)
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.running = False
elif event.key == pygame.K_RETURN and self.state != "play":
self.new_game()
self.state = "play"
def update(self, dt):
if self.state == "play":
self.update_play(dt)
for splat in self.splats:
splat.update(dt)
self.splats = [s for s in self.splats if s.age < Splat.DURATION]
def update_play(self, dt):
keys = pygame.key.get_pressed()
self.player.update(dt, keys)
fry = self.player.shoot(keys)
if fry:
self.fries.append(fry)
for fry in self.fries:
fry.update(dt)
self.fries = [f for f in self.fries if f.life > 0]
for shake in self.shakes:
shake.update(dt)
self.wave_timer -= dt if not self.shakes else 0
if not self.shakes and self.wave_timer <= 0:
self.wave += 1
self.spawn_shakes(2 + self.wave)
self.wave_timer = 1.5
self.check_fry_hits()
self.check_player_hit()
def draw_text(self, surf, text, font, center, color=(255, 255, 255)):
shadow = font.render(text, True, (20, 20, 40))
surf.blit(shadow, shadow.get_rect(center=(center[0] + 3, center[1] + 4)))
label = font.render(text, True, color)
surf.blit(label, label.get_rect(center=center))
def draw_hud(self, surf):
self.draw_text(surf, f"Score {self.score}", self.font, (130, 36))
self.draw_text(surf, f"Wave {self.wave}", self.font, (WIDTH / 2, 36))
self.draw_text(surf, f"Best {self.high}", self.font, (WIDTH - 110, 36))
for i in range(self.lives):
surf.blit(IMG["life"], (24 + i * 46, HEIGHT - 60))
def draw(self):
surf = self.screen
surf.blit(IMG["background"], (0, 0))
for splat in self.splats:
splat.draw(surf)
for shake in self.shakes:
shake.draw(surf)
for fry in self.fries:
fry.draw(surf)
if self.state == "play":
self.player.draw(surf)
if self.state == "play":
self.draw_hud(surf)
elif self.state == "title":
self.draw_text(surf, "BURGER BLASTER", self.big_font, (WIDTH / 2, 250))
self.draw_text(surf, "Arrow keys fly, Space fires", self.font, (WIDTH / 2, 380))
self.draw_text(surf, "Press Enter to start", self.font, (WIDTH / 2, 450), (255, 220, 90))
else:
self.draw_text(surf, "GAME OVER", self.big_font, (WIDTH / 2, 250))
self.draw_text(surf, f"Score {self.score} Best {self.high}", self.font, (WIDTH / 2, 380))
self.draw_text(surf, "Press Enter to play again", self.font, (WIDTH / 2, 450), (255, 220, 90))
pygame.display.flip()
def run(self):
while self.running:
dt = self.clock.tick(FPS) / 1000
self.handle_events()
self.update(dt)
self.draw()
pygame.quit()
if __name__ == "__main__":
Game().run()
sys.exit(0)
What is new:
import json, os json turns Python values into text and back. os gives us the environment variable
XDG_DATA_HOME on Linux, the folder for a program's data, usually ~/.local/share. If the variable is not set, we use ~/.local/share ourselves
SAVE = ... / "burger-blaster" / "highscore.json" the path of the file. The / operator on a Path joins the parts
load_high() reads the file and returns the number. If the file is missing (OSError), not valid JSON (ValueError) or has no "high" in it (KeyError), it returns 0. The game must never crash because of a damaged save file
save_high(score) makes the folder (parents=True, exist_ok=True) and writes {"high": 340}
self.high = load_high() the best score is read once, when the game starts
game_over: if self.score > self.high a new best is stored in the game and saved at once, so even a crash on the title screen cannot lose it
Best in the HUD and on the game over screen the top right corner during play, and next to the score at the end
Run it:
(.venv) $ python game.py
Play a round, let the game end and look at the best score. Close the game, start it again and the best score is still there, from the file. The file is a few bytes of text:
(.venv) $ cat ~/.local/share/burger-blaster/highscore.json
{"high": 340}
(Checked in the lab: the game over with a score of 340 wrote {'high': 340} to a data folder, and a new Game() read it back as the best score. The cat line shows the format and a score from that check; your number will be your own.)
Episode 7 running.
Tuning the feel
Four numbers make the game's difficulty:
20 and 50 in pop how much each shake is worth
2 + self.wave how many shakes a wave starts with
0.12 in the boost how much faster each wave is
self.wave_timer = 1.5 the pause between waves
The game is a little too easy at the start and gets hard by wave 5 or so. If you want it harder, raise 0.12 to 0.2 and see how far you get.
Try it yourself
Four small changes before episode 8:
1 Show the best score in yellow on the game over screen when you have just beaten it (hint: compare self.score with the old self.high before game_over updates it).
2 Start with five lives and see how the waves feel.
3 Make the game over screen show the wave you reached.
4 Delete the highscore.json file and start the game. What does the best score say, and why does it not crash?
Episode 8 adds sound: a pew for every fry, a splat for every hit, music, and a little shake of the screen.
Check your work
If something is different:
AttributeError: 'Game' object has no attribute 'font' self.font = Font(None, 52) is missing in __init__
the score does not go up pop has to add to self.score for every shake that is hit
the waves never come the 'if not self.shakes and self.wave_timer <= 0' block has to be in update_play
the game starts at once, with no title screen self.state = "title" has to come before self.new_game() is called, and Enter has to start the game
the best score is always 0 save_high is never called: check game_over
FileNotFoundError when saving the folder is not created: parents=True, exist_ok=True in save_high
Not run in the lab: other Linux distributions, Wayland-only sessions and pygame older than 2.6. The numbers in the checks come from running each stage for a few simulated seconds at 60 frames per second.