🕊️ Hotdog Dash, Episode 5

The gull picks a spot, warns you with a shadow and a red ring, dives, and costs a life if you are still there. Three small steps.

Video: Hotdog Dash, Episode 5 (Hotdog Dash 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 5 ends with this: every few seconds the gull's shadow leaves its loop and slides to a spot on the floor while it shrinks and darkens, a red ring pulses on a three by three patch of tiles, and 1.5 seconds later the gull dives and lands. If the hotdog is standing on the patch it loses a life, goes back to the start blinking, and cannot be hit for two seconds. Three lives, and the game starts again. If you keep running, the gull aims where you will be, so you have to turn to get away.

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: a state machine for the gull, a prediction of where the hotdog is going, a hit check, and lives.
You will learn: states as strings, interpolation with lerp and smoothstep, why a game aims ahead of the player, and a hit with a short grace time.
Starter files: hotdog-dash-ep04.zip is where this episode begins, hotdog-dash-ep05.zip is where it ends. Both have the art folder.

The code of each step was run headless on Python 3.12 and pygame 2.6.1, 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 hotdog-dash
$ source .venv/bin/activate
(.venv) $ python game.py

The gull flies its figure and the hotdog eats. The file is 267 lines. This episode is the biggest so far: it changes Gull and adds to Hotdog and Game.

The plan: a state machine

A gull is always in exactly one state, a string in self.state, and each state has its own few lines in update:

circle    flies the loop. When its wait is over (2.5 to 4 seconds, random), it aims, and the state becomes warn
warn      for WARN_TIME = 1.5 seconds the shadow slides from the loop to the target tile and the gull sinks; the ring is drawn
dive      0.3 seconds (DIVE_TIME) of falling to the ground
land      stays on the ground for 1 second (STAY_TIME). This is the only state in which it can hurt
leave     takes 0.7 seconds to fly back up to its loop, then back to circle

Every state ends by setting the next state and resetting self.timer to 0, which is how long it has been in this one. That is all a state machine is. It makes a long list of 'if this then that' easy to read, because each state only has to know how to leave itself.

Step 1: warn, dive, land

First the whole life cycle, without any damage. Make these changes to game.py:

Add this after line 46 of your file (LOOP_SPEED = 0.5  # how fast a gull flies round its loop)

DIVE_RADIUS = 1  # a dive covers the target tile and this many tiles around it: a 3 x 3 patch
DIVE_TIME = 0.3  # seconds from the warning ring to touchdown
STAY_TIME = 1.0  # seconds a gull stays on the ground
START_LIVES = 3
SAFE_TIME = 2.0  # seconds the hotdog blinks and cannot be hit after a respawn

- - -

Add this after line 47 of your file (GULL_COUNT = 1)

WARN_TIME = 1.5  # seconds of warning: the shadow shrinks onto the target and a red ring appears
PAUSE = (2.5, 4.0)  # a gull waits this long between dives

- - -

Add this after line 120 of your file (self.clock += dt)

    def where_in(self, seconds):
        """Where the hotdog will be if the player keeps doing what they are doing: the gulls aim here."""
        col, row = self.target if self.target is not None else (self.col, self.row)
        way = self.dir
        steps = int(seconds * HOTDOG_SPEED / TILE) - (1 if self.target is not None else 0)
        for _ in range(steps):
            if self.want != (0, 0) and is_open(col + self.want[0], row + self.want[1]):
                way = self.want
            if not is_open(col + way[0], row + way[1]):
                break
            col, row = col + way[0], row + way[1]
        return col, row

- - -

Replace line 131

    def __init__(self, phase):

with

    def __init__(self, phase, pause):

- - -

Add this after line 132 of your file (self.phase = phase  # where on the loop it starts)

        self.pause = pause

- - -

Add this after line 140 of your file (self.flap = 0)

        self.state = "circle"
        self.timer = 0
        self.wait = random.uniform(*self.pause)
        self.target = None

- - -

Replace lines 148-153

        self.t += dt
        ahead = self.path(self.t)
        move = ahead - self.shadow
        if move.length() > 0:
            self.heading = math.degrees(math.atan2(-move.y, move.x)) - 90
        self.shadow = ahead

with

        if self.state == "circle":
            self.t += dt
            ahead = self.path(self.t)
            move = ahead - self.shadow
            if move.length() > 0:
                self.heading = math.degrees(math.atan2(-move.y, move.x)) - 90
            self.shadow = ahead
            self.wait -= dt
            if self.wait <= 0:
                self.aim(game)
        elif self.state == "warn":
            self.timer += dt
            k = min(1, self.timer / game.warn_time)
            self.shadow = self.start.lerp(tile_center(*self.target), k * k * (3 - 2 * k))
            self.alt = 1 - 0.55 * k
            if self.timer >= game.warn_time:
                self.state, self.timer = "dive", 0
        elif self.state == "dive":
            self.timer += dt
            self.alt = 0.45 * (1 - min(1, self.timer / DIVE_TIME))
            if self.timer >= DIVE_TIME:
                self.state, self.timer, self.alt = "land", 0, 0
        elif self.state == "land":
            self.timer += dt
            if self.timer >= STAY_TIME:
                self.state, self.timer = "leave", 0
                self.start = pygame.Vector2(self.shadow)
        elif self.state == "leave":
            self.timer += dt
            k = min(1, self.timer / 0.7)
            self.alt = k
            self.shadow = self.start.lerp(self.path(self.t), k)
            if k >= 1:
                self.state, self.wait = "circle", random.uniform(*self.pause)

    def aim(self, game):
        """Aim where the hotdog will be when the warning runs out, if the player does not change course."""
        self.target = game.player.where_in(game.warn_time)
        self.start = pygame.Vector2(self.shadow)
        self.state, self.timer = "warn", 0

    def on_ground(self):
        return self.state == "land"

- - -

Add this after line 160 of your file (surf.blit(image, image.get_rect(center=self.shadow)))

        if self.state == "warn":  # the red ring on the tile it is about to hit
            col, row = self.target
            pulse = 3 + int(2 * math.sin(self.timer * 18))
            reach = DIVE_RADIUS * TILE
            pygame.draw.rect(surf, (255, 70, 60), (col * TILE - reach - 2, row * TILE - reach - 2, TILE + 2 * reach + 4, TILE + 2 * reach + 4), pulse, border_radius=16)

- - -

Replace line 163

        name = f"gull_{[0, 1, 2, 1][int(self.flap * 9) % 4]}"

with

        name = "gull_land" if self.on_ground() else f"gull_{[0, 1, 2, 1][int(self.flap * 9) % 4]}"

- - -

Replace line 193

        self.gulls = [Gull(i * 2.1) for i in range(GULL_COUNT)]

with

        self.gulls = [Gull(i * 2.1, PAUSE) for i in range(GULL_COUNT)]
        self.warn_time = WARN_TIME

What is new:

DIVE_RADIUS = 1              the dive covers the target tile and one tile all round it: a 3 by 3 patch, 144 pixels wide. Fair, because you can see the ring
WARN_TIME, PAUSE             the warning time, and the range of the wait between dives. They are in Game as self.warn_time and passed to each gull, so episode 8 can make them different in each level
START_LIVES, SAFE_TIME       constants for step 2 and 3, put here with the rest
where_in(seconds)            the clever part. It walks the hotdog forward in whole tiles for that many seconds, the way the hotdog will walk if the player does nothing new: continue in the wanted direction when it is open, otherwise straight on, stop at a wall. A gull aims at the tile where the hotdog will be when the warning is over, so a hotdog that keeps running in a straight line is hit, and one that turns is not
self.start.lerp(goal, k)     lerp is linear interpolation: k = 0 is the start, k = 1 is the goal, and 0.5 is halfway. Here it slides the shadow from the loop to the target
k * k * (3 - 2 * k)          smoothstep. It bends k so the shadow starts slowly, speeds up in the middle and arrives slowly. It looks like something with weight
self.alt = 1 - 0.55 * k      the gull sinks while the warning runs, from 1.0 to 0.45, and then 0.45 to 0 in the dive. That is the third dimension
pulse = 3 + int(2 * sin(...)) the line width of the ring changes between 1 and 5 pixels, 18 radians a second, so it throbs
border_radius=16             the corners of the ring are rounded
gull_land                    a different picture when it is on the ground, folded wings and no flapping

Run it:

(.venv) $ python game.py

Every few seconds the shadow leaves the loop, a red ring appears on the floor and the shadow slides into it while the gull sinks. Then the gull drops, stands on the ring for a second and flies away. Nothing hurts yet. (Checked: with the hotdog standing still, the first dive was warned at 2.87 s, the dive began 1.5 s later, the gull landed 0.3 s after that, left after a second and was back on its loop 0.7 s after that. A hotdog that has just started running right from the middle of the maze is aimed at six tiles ahead; one that stands still is aimed at where it stands.)

Step 2: lives and hits

Now the part that hurts. Make these changes:

Add this after line 86 of your file (self.clock = 0)

        self.safe = 0

- - -

Add this after line 102 of your file (self.arrived = False)

        self.safe -= dt

- - -

Add this after line 249 of your file (self.fill_packets())

        self.lives = START_LIVES

- - -

Add this after line 279 of your file (self.fill_packets())

    def check_gulls(self):
        for gull in self.gulls:
            tile = self.player.tile()
            under = gull.state == "land" and abs(tile[0] - gull.target[0]) <= DIVE_RADIUS and abs(tile[1] - gull.target[1]) <= DIVE_RADIUS
            on_it = under and self.player.safe <= 0
            if on_it:
                self.hit()
                return

    def hit(self):
        self.lives -= 1
        if self.lives <= 0:
            self.game_over()
            return
        self.player.reset()
        self.player.safe = SAFE_TIME
        for gull in self.gulls:
            gull.reset()

    def game_over(self):
        self.lives = START_LIVES
        self.score = 0
        self.fill_packets()
        self.player.reset()
        self.player.safe = SAFE_TIME
        for gull in self.gulls:
            gull.reset()

- - -

Add this after line 285 of your file (gull.update(dt, self))

        self.check_gulls()

- - -

Add this after line 306 of your file (surf.blit(self.score_font.render(f"{self.score:05d}", True, TEXT_COLOR), (MAZE_W + 26, 118)))

        surf.blit(self.font.render("LIVES", True, (190, 190, 215)), (MAZE_W + 26, 200))
        for i in range(self.lives):
            surf.blit(pygame.transform.smoothscale(IMG["life"], (48, 33)), (MAZE_W + 26 + i * 60, 232))

What is new:

START_LIVES                  a game starts with three lives, shown by three small hotdogs on the panel
under = ...                  the landed gull and the hotdog's tile, the same tile or within DIVE_RADIUS of it in both directions: the hotdog is under the gull if it stands in the 3 by 3 patch
on_it                        under, and not safe. The safe time comes next
hit()                        take a life; when none are left, game_over(); else put the hotdog back on its start tile, make it safe for SAFE_TIME seconds and send the gulls back to their loops, so the player is not hit again straight away
game_over()                  for now it just starts again: full lives, zero score, a full maze. Episode 8 gives the game a proper game over screen and a high score
self.safe                    set to SAFE_TIME (2 seconds) after a hit. It is counted down in update, and the hotdog cannot be hit while it is above zero
return after self.hit()      only one hit per frame, even if two gulls land on the same tile
LIVES on the panel           a loop that draws one small hotdog for each life left

Run it:

(.venv) $ python game.py

Stand still and wait. When the gull lands on the ring, the hotdog loses a life, jumps back to the start and the panel shows two lives. Run the maze, and the gull aims ahead of you, so a hotdog that keeps going straight is caught. Turn before the warning ends, and the ring lands where you would have been. (Checked: a hotdog standing still lost its first life at 4.68 seconds, the moment the gull landed, was back on its start tile with safe time 2.0, and the lives went from 3 to 2.)
After a hit the hotdog cannot be hit for two seconds, but nothing shows it. One more change, in Hotdog.draw, makes it blink:

Add this after line 143 of your file (def draw(self, surf):)

        if self.safe > 0 and int(self.safe * 10) % 2:
            return  # blink while safe

What is new:

int(self.safe * 10) % 2      the safe time times ten, rounded down, and then its remainder after division by two: 0, 1, 0, 1, ... ten times a second. When it is 1, draw returns without drawing anything, so the hotdog blinks five times a second
if self.safe > 0             only while the safe time is left

Run it:

(.venv) $ python game.py

Get hit. The hotdog reappears at the start, blinking, for two seconds. The whole file after step 3 is also hotdog-dash-ep05.zip.
Hotdog Dash episode 5 running
Episode 5 running (a screenshot of the finished step).

Tuning the feel

The feel of the dive is in four numbers, and they are what episode 8 changes level by level:

WARN_TIME = 1.5   the shorter it is, the harder. Under a second and the player cannot react
PAUSE = (2.5, 4.0)   how long the gull waits between dives
DIVE_RADIUS = 1   0 is a single tile, 2 a patch of 5 by 5. 1 is a good size for a maze whose lanes are one tile wide
STAY_TIME = 1.0   how long the gull stays on the ground. It matters in episode 7, when you can stun it

Try it yourself

Three small changes before episode 6:

1  Make the warning 0.8 seconds and play. When does it stop being fair?
2  Draw the ring in another color. (Hint: the tuple of three numbers in draw_shadow.)
3  Make the gull aim at the tile where the hotdog is now, not where it will be: replace where_in(...) with the player's tile(). How easy is the game now?

Episode 6 gives the hotdog a place to hide.

Check your work

If something is different:

NameError: name 'tile_center' is not defined     tile_center is defined above class Hotdog, in episode 2. Check that nothing was deleted
AttributeError: 'NoneType' object is not subscriptable    the ring is drawn when target is None: draw the ring only when the state is 'warn'
TypeError: __init__() missing 1 required positional argument: 'pause'    Gull(i * 2.1, PAUSE) needs both arguments in start_level
the gull dives straight away every time          the wait line: self.wait = random.uniform(*self.pause), and wait -= dt in circle
the hotdog is hit the moment the game starts     the gull state is 'land' only after a dive: check the state names are spelled the same everywhere
the hotdog never loses a life                    check_gulls() is missing from Game.update, after the gull updates

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