A hit, a split and a splat: the fries finally hit. Three 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 5 ends with this: the fries hit the shakes. A big shake splits into two small ones, a small shake goes splat, the splat animation plays in the flavor's color, and when the screen is clear a new wave of four arrives.
You will need: your project from episode 4 (a game.py, an art folder and the .venv), or the starter files below.
You will make: collision tests between circles, a pop method that splits shakes, and a Splat class with an animation.
You will learn: circle collisions, removing things from a list while you loop, a timed animation made from picture frames.
Starter files: burger-blaster-ep04.zip is where this episode begins, burger-blaster-ep05.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 three 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
Four shakes drift and spin, the burger flies and shoots, and the fries go straight through the shakes. The file is 183 lines. In class Game we add two methods, pop and check_fry_hits, and in step 3 a new class, Splat.
Step 1: the hit
Both the fry and the shake have a radius. Two circles touch when the distance between their centres is less than the sum of the radii. Make these changes to class Game:
1 Add a method pop(shake), which for now only removes the shake from the list
2 Add a method check_fry_hits, which tests every live fry against every shake
3 Call check_fry_hits at the end of Game.update
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
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
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):
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 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.spawn_shakes(4)
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: for now it just disappears."""
self.shakes.remove(shake)
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 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()
def draw(self):
surf = self.screen
surf.blit(IMG["background"], (0, 0))
for shake in self.shakes:
shake.draw(surf)
for fry in self.fries:
fry.draw(surf)
self.player.draw(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:
distance_to(...) < radius + radius the whole circle test. A big shake has radius 50 and a fry 8, so a fry touches a big shake from 58 pixels away
if fry.life <= 0: continue a fry that has already hit something this frame (or expired) must not hit a second shake
fry.life = 0 the fry is used up. Episode 3's filter removes it from the list in the next frame
self.pop(shake) what happens to the shake is its own method, so we can change it in the next steps
break after one hit, stop looking at more shakes for this fry
self.shakes.remove(shake) take the shake out of the list. Careful: we do this inside a loop over self.fries, not over self.shakes, and we break right after, so the list we are looping over is never changed while we loop over it
Run it, and shoot:
(.venv) $ python game.py
A fry touches a shake and the shake is gone. Clear all four and a new wave of four arrives (the if not self.shakes line from episode 4 has something to do now). (Checked in the lab: a fry touching a big shake took the shakes from 4 to 3, a fry far away hit nothing, and with no shakes left one frame of update brought a new wave of 4.)
Step 2: a big shake splits
A big shake should split in two, and a small one should disappear. That is a change in pop, and nothing else:
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
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
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):
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 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.spawn_shakes(4)
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 vanish."""
self.shakes.remove(shake)
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 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()
def draw(self):
surf = self.screen
surf.blit(IMG["background"], (0, 0))
for shake in self.shakes:
shake.draw(surf)
for fry in self.fries:
fry.draw(surf)
self.player.draw(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:
if shake.size == "big" only the big ones split. A small one is removed in the line before and nothing replaces it
for _ in range(2) do it twice. The underscore is the name Python programmers use for a loop variable they do not need
Shake(shake.pos, "small", shake.flavor, shake.boost) two new small shakes in the same place, with the same flavor. They get their own random direction and spin, because the constructor from episode 4 does that
shake.boost passed on, so that in episode 7 the small shakes of a fast wave are fast as well
Run it:
(.venv) $ python game.py
Hit a big shake and two small ones fly out of it, faster than the big one. Hit those, and they are gone. One big shake takes three hits. (Checked: a hit on a big shake took the list from 4 shakes to 5, three big and two small; a hit on a small one took it from 5 to 4.)
Step 3: the splat
The last piece is the visual reward. The art folder has five pictures of a splash for each flavor (splat_strawberry_0.png to splat_strawberry_4.png, and the same for chocolate and mint). A Splat plays them one after the other, in 0.4 seconds, in the place where the shake was. The whole file after step 3, which is also the file in burger-blaster-ep05.zip:
#!/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
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
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):
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.spawn_shakes(4)
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))
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 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()
for splat in self.splats:
splat.update(dt)
self.splats = [s for s in self.splats if s.age < Splat.DURATION]
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)
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:
DURATION = 0.4 a class constant: how long the animation takes, in seconds
self.age += dt the age of the splat, counted up every frame
int(self.age / DURATION * 5) the progress from 0 to 1, times 5 frames, rounded down: frame 0 at the start, frame 4 at the end
min(..., 4) never past the last frame, even when a slow frame makes the age larger than DURATION
IMG[f"splat_{flavor}_{frame}"] the file name built from the flavor and the frame number
self.splats.append(Splat(...)) pop adds one, for every shake that is hit, big or small
self.splats = [s for s in self.splats if s.age < Splat.DURATION] the same list filter as the fries use: old splats drop out
splats are drawn first underneath the shakes and the fries
Run it:
(.venv) $ python game.py
Every hit leaves a splash in the color of the shake, which plays through its five pictures and disappears. (Checked: a hit left 1 splat, and half a second later there were none.)
Episode 5 running.
Tuning the feel
The feel of a hit is in a few places:
Fry.radius = 8, Shake.radius = 50 / 25 the hit boxes. A bigger fry radius makes the game easier, because fries hit from further away
DURATION = 0.4 a longer splat is more satisfying, but a very long one covers the screen
range(2) in pop how many pieces a big shake breaks into
The scoring in episode 7 will count every hit, so the splits decide how many points a shake is worth.
Try it yourself
Three small changes before episode 6:
1 Make a big shake split into three small ones.
2 Make the splat last one second. How does it feel?
3 Change the fry radius to 20. Which shakes become easy and which stay hard?
Episode 6 gives the shakes a way to hit back: when a shake touches the burger it loses a life, respawns blinking and safe, and the game can end.
Check your work
If something is different:
AttributeError: 'Shake' object has no attribute 'size' the Shake class from episode 4 has to keep self.size = size
KeyError: 'splat_mint_0' the art folder is missing the splat pictures: use the starter zip
ValueError: list.remove(x): x not in list a shake was removed twice. Check the break after self.pop(shake) and the life test
shakes do not split pop is missing the 'if shake.size == "big"' block
the splat shows for one frame only DURATION is 0 or the frame calculation lost the * 5
Not run in the lab: other Linux distributions, Wayland-only sessions and pygame older than 2.6. The numbers in the checks come from simulating a fry on top of a shake, one hit at a time.