๐ŸŸ Burger Blaster, Episode 3

A fry that flies, a fry that expires and a gun that waits. Three small steps, each one run before it was written down.

Video: Burger Blaster, Episode 3 (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 3 ends with this: you hold Space and the burger shoots fries straight out of its front, a few every second, each one flying on, wrapping at the screen edge and then disappearing.

You will need: your project from episode 2 (a game.py, an art folder and the .venv), or the starter files below.
You will make: a Fry class, a list of fries in the game, a lifetime for each fry and a cooldown for the gun.
You will learn: more than one object of the same kind, a list that is updated and filtered every frame, timers that count down with dt.
Starter files: burger-blaster-ep02.zip is where this episode begins, burger-blaster-ep03.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 2 turns with Left and Right, flies with Up and wraps at the edges. Space does nothing yet. The file is 106 lines. These are the three places we will change: the constants at the top, class Player, and class Game, and we add one new class, Fry, between them.

Step 1: a fry that flies

A fry is a small object, like the player: a position, a velocity and an angle to draw it at. Make these changes to game.py:

1  Add a constant after MAX_SPEED:  FRY_SPEED = 720
2  Add a shoot method to Player, and a new class Fry between Player and Game
3  In Game: make an empty list of fries, add the new fry in update, update every fry, and draw every fry before the burger

The whole file after step 1:

#!/usr/bin/env python3
"""Burger Blaster: a hamburger shoots french fries at angry milkshakes."""
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

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

    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)

    def shoot(self, keys):
        if keys[pygame.K_SPACE]:
            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

    def update(self, dt):
        self.pos += self.vel * dt
        wrap(self.pos)

    def draw(self, surf):
        draw_rotated(surf, IMG["fry"], 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 = []

    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)

    def draw(self):
        surf = self.screen
        surf.blit(IMG["background"], (0, 0))
        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:

FRY_SPEED = 720            pixels per second, faster than the burger's top speed of 480, so a fry always leaves the burger behind
Fry(pos, direction, angle) the position where it starts, the unit vector it flies along and the angle it is drawn at
self.vel = direction * FRY_SPEED     a vector of length 1 times the speed: the velocity, in pixels per second
pos + direction * 44       the fry starts 44 pixels in front of the burger's centre, so it appears at the nose and not on top of the burger
shoot returns a Fry or None  Python returns None when a function ends without a return, and 'if fry:' is false for None
self.fries = []            a list, because we will have many fries at once and each one lives its own life
for fry in self.fries: fry.update(dt)   every frame each fry moves by its velocity times dt, and wraps round the screen like the burger does
fries are drawn first, then the burger     the fry sprites go under the burger, so it looks like they come out of it

Run it, and hold Space:

(.venv) $ python game.py

Fries fly out of the front of the burger, straight along the direction it points. Turn while you hold Space and the line bends. There is one problem: nothing ever removes a fry. They wrap around the screen for ever, and there is a new one every frame. (Checked in the lab, simulating 60 frames per second with Space held: 60 fries after one second, 120 after two, 240 after four. Every one of them still alive.)

Step 2: a fry that expires

Give each fry a lifetime. A new constant, a counter in Fry, and one line in Game.update that throws away the old ones:

FRY_LIFE = 0.9             seconds before a fry disappears

The whole file after step 2:

#!/usr/bin/env python3
"""Burger Blaster: a hamburger shoots french fries at angry milkshakes."""
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

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

    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)

    def shoot(self, keys):
        if keys[pygame.K_SPACE]:
            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 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 = []

    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]

    def draw(self):
        surf = self.screen
        surf.blit(IMG["background"], (0, 0))
        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:

self.life = FRY_LIFE       every fry starts with the same lifetime
self.life -= dt            every frame it loses the time that passed. After 0.9 seconds of frames, it is at 0 or below
self.fries = [f for f in self.fries if f.life > 0]     a list comprehension: a new list that keeps only the fries that are still alive. The old ones are not in the list any more, so they are never updated or drawn again, and Python frees them

Run it, hold Space:

(.venv) $ python game.py

The fries fly out, travel a little way (0.9 seconds at 720 pixels per second is 648 pixels, about half the width of the window) and disappear. The solid line is shorter, but it is still solid, because there is still a new fry every frame. (Checked: with Space held the number of fries alive settles at 53 and stays there, instead of growing.)

Step 3: a gun that waits

The last problem is the rate of fire. Add a timer to the player: a cooldown that counts down, and the gun only shoots when it has run out.

SHOOT_DELAY = 0.22         seconds between shots

The whole file after step 3, which is also the file in burger-blaster-ep03.zip:

#!/usr/bin/env python3
"""Burger Blaster: a hamburger shoots french fries at angry milkshakes."""
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 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 = []

    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]

    def draw(self):
        surf = self.screen
        surf.blit(IMG["background"], (0, 0))
        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:

self.cooldown = 0          a timer, in seconds. At 0 or below the gun is ready
self.cooldown -= dt        counts down by the time of the frame, in Player.update
and self.cooldown <= 0     shoot only fires if the gun is ready
self.cooldown = SHOOT_DELAY  after a shot, the gun has to wait 0.22 seconds again, about four and a half shots a second

This is the pattern that every timer in a game uses: set it to a number of seconds, subtract dt every frame, act when it reaches zero. The invulnerability after the burger is hit in episode 6 is exactly the same thing.

Run it:

(.venv) $ python game.py

Hold Space and the fries come out in a steady stream, a little way apart, each one a separate fry. Turn while you shoot and the fries paint a spiral. (Checked: with Space held, four fries are alive at any moment: 0.9 seconds of life divided by 0.22 seconds between shots.)
The Burger Blaster window with the burger shooting a stream of fries
Episode 3 running: fries in a steady stream, each one flying on and then disappearing.

Tuning the feel

Three numbers, all at the top, set how the gun feels:

FRY_SPEED = 720            a faster fry feels like a laser, a slower one like a thrown fry
FRY_LIFE = 0.9             how far the fry flies: speed times life, 648 pixels with these values
SHOOT_DELAY = 0.22         the rate of fire

Fire rate and range interact: a long life and a short delay fills the screen, and in the next episodes a full screen of fries is not much of a challenge. The values in the file are the ones the rest of the series uses.

Try it yourself

Three small changes before episode 4:

1  Double FRY_LIFE. How far does a fry fly now, and what happens at the screen edge?
2  Set SHOOT_DELAY to 0.05. Is the game easier, or just messier?
3  Shoot from the back of the burger by changing the direction in shoot (hint: the sign).

Episode 4 brings the milkshakes: three flavours, big and small, drifting and spinning across the screen.

Check your work

If something is different:

NameError: name 'Fry' is not defined               class Fry has to be in the file; it can be after Player because the name is only looked up when shoot runs
KeyError: 'fry'                                    the art folder is missing fry.png: use the starter zip
nothing happens when you press Space              Player.shoot is not called in Game.update, or the new fry is not added to self.fries
the fries are drawn on top of the burger          the fry loop in draw must come before self.player.draw(surf)
one fry per frame, and they never go away          the life line in Fry.update or the filter in Game.update is missing

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