🥤 Burger Blaster, Episode 4

Milkshakes that drift, spin and wrap: one shake, then flavors and sizes, then a wave. Three small steps, each one run before it was written down.

Video: Burger Blaster, Episode 4 (Burger Blaster video)
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 4 ends with this: four angry milkshakes of random flavors start in random places, drift and spin across the screen and wrap round the edges, while the burger flies and shoots. The fries do not hurt them yet; that is episode 5.

You will need: your project from episode 3 (a game.py, an art folder and the .venv), or the starter files below.
You will make: a Shake class, a list of flavors, and a function that spawns a wave of shakes.
You will learn: random numbers, a vector rotated by a random angle, one class with two sizes, and a loop that keeps trying until a position is good enough.
Starter files: burger-blaster-ep03.zip is where this episode begins, burger-blaster-ep04.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

The burger from episode 3 turns, flies, wraps and shoots fries that fly and expire. There is nothing to shoot at. The file is 143 lines. We add one class, Shake, between Fry and Game, and change Game in three places.

Step 1: one shake

A milkshake is an object with a position, a velocity, an angle and a spin. Make these changes to game.py:

1  Add  import random  at the top, with the other imports
2  Add a new class Shake between class Fry and class Game
3  In Game: a list of shakes with one strawberry shake in it, update it every frame, and draw it under the fries

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

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, flavor):
        self.pos = pygame.Vector2(pos)
        self.flavor = flavor
        self.radius = 50
        self.vel = pygame.Vector2(random.uniform(60, 130), 0).rotate(random.uniform(0, 360))
        self.angle = random.uniform(0, 360)
        self.spin = random.uniform(-90, 90)
        self.image = IMG[f"shake_{flavor}"]

    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 = [Shake((200, 150), "strawberry")]

    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)

    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:

import random                       Python's random numbers, from the standard library, nothing to install
random.uniform(60, 130)             a random decimal number between 60 and 130: the speed of this shake, in pixels per second
Vector2(speed, 0).rotate(angle)     a vector pointing right, with the length of the speed, turned by a random angle from 0 to 360 degrees. That makes a random velocity: any direction, any speed in the range
self.spin = uniform(-90, 90)        degrees per second. The sign decides which way it turns, so some shakes turn clockwise and some the other way
self.angle += self.spin * dt        the same pattern as the burger's turn: a rate times dt
wrap(self.pos, 70)                  the wrap function from episode 2, with a bigger margin than a fry has, because a shake is a bigger picture
IMG[f"shake_{flavor}"]              the picture, picked by name. 'shake_strawberry' is the file art/shake_strawberry.png, loaded in episode 1 with all the others
radius = 50                         not used yet. It is the size of the shake for collisions, and episode 5 uses it when the fries hit

Run it:

(.venv) $ python game.py

A strawberry shake drifts across the diner floor, turning slowly, and wraps round the screen. Fly and shoot at it: the fries go straight through, because nothing checks for a hit yet. (Checked in the lab: after 10 seconds the shake was still inside the wrapped playfield.) Every run is a little different, because the speed, direction and spin are random.

Step 2: flavors and sizes

There are three flavors and two sizes. Change the Shake class so that it takes a size and a flavor, and add a list of the flavors:

FLAVORS = ["strawberry", "chocolate", "mint"]

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 = [Shake((200 + 350 * i, 200), "big", flavor) for i, flavor in enumerate(FLAVORS)]
        self.shakes += [Shake((300, 550), "small", "mint"), Shake((900, 550), "small", "strawberry")]

    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)

    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:

FLAVORS                             a list of the three flavor names, which are also part of the picture names
Shake(pos, size, flavor, boost=1.0) one class for both sizes. 'big' and 'small' are just strings
radius = 50 if size == "big" else 25   a conditional expression: one line, two values. The small shake has half the radius
speed = uniform(60, 130) if big else uniform(110, 200)    small shakes are faster
shake_{flavor} or shake_{flavor}_small    the big and the small pictures have different names, and the class picks the right one
boost                               a multiplier for the speed. It is 1.0 for now, and episode 7 raises it a little for each wave
[Shake(...) for i, flavor in enumerate(FLAVORS)]    a list comprehension: one big shake for each flavor, 350 pixels apart. enumerate gives the position in the list, i, along with the flavor
self.shakes += [...]                two small shakes added to the list, to see them as well

Run it:

(.venv) $ python game.py

Three big shakes (strawberry, chocolate and mint) and two small ones, which move faster. (Checked in the lab: five shakes, three with radius 50 and two with radius 25, all inside the wrapped playfield after 10 seconds.)

Step 3: a wave of shakes

Placing the shakes by hand is no way to make a game. A method spawns as many as we ask for, at random places, but never on top of the burger. The whole file after step 3, which is also the file in burger-blaster-ep04.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 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 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)

    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:

spawn_shakes(count)                 makes count new big shakes
while True: ... break               a loop that runs until it breaks: choose a random position, and stop as soon as it is good enough
distance_to(self.player.pos) > 300  good enough means more than 300 pixels from the burger, so a new shake never starts where it could hit the burger at once
random.choice(FLAVORS)              a random flavor from the list
self.spawn_shakes(4)                the first wave is four shakes
if not self.shakes:                 an empty list is false in Python. When no shakes are left, the next wave of four arrives. Nothing can destroy a shake yet, so this only starts to matter in episode 5

Run it:

(.venv) $ python game.py

Four big shakes in random places, random flavors, all drifting and spinning. Close the window and run it again, and the wave is different. (Checked in the lab: over 200 simulated waves, no shake ever started closer than 300 pixels to the burger.)
Burger Blaster episode 4 running
Episode 4 running.

Tuning the feel

The feel of the shakes is in a few numbers:

uniform(60, 130)                    the speed range of the big ones. Faster ones are harder to hit
uniform(110, 200)                   the speed range of the small ones
uniform(-90, 90)                    the spin. It does not matter for the game, only for the look
spawn_shakes(4)                     how many in a wave
distance_to(...) > 300              how much room the burger gets at the start

The shakes will get harder in episode 7: every wave has one more shake and a higher boost. For now, four is a comfortable number.

Try it yourself

Three small changes before episode 5:

1  Start with ten shakes. Is it still playable, or does the burger need the 300 pixels?
2  Make the shakes spin faster by changing the range of the spin.
3  Make a wave of only small shakes (hint: the second argument of Shake).

Episode 5 is the one where something finally happens: the fries hit the shakes, big shakes split in two, small ones splat and vanish.

Check your work

If something is different:

NameError: name 'random' is not defined          import random is missing from the top of the file
NameError: name 'FLAVORS' is not defined         in step 2 and 3 the list has to be near the top, with the other constants
KeyError: 'shake_strawberry_small'               the art folder is missing the small pictures: use the starter zip
the shakes all move the same way                 the random call is outside the class, or called once and reused
a shake starts on top of the burger              the distance check is missing, or it is shorter than the burger's size

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 ten simulated seconds at 60 frames per second.