🐧 Waddle Run, Episode 7

Jump on the crab. It goes flat, Tux bounces. Touch it from the side and you lose a heart. Stomp three in a row for a bonus.

Video: Waddle Run, Episode 7 (Waddle Run 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 7 ends with this: crabs and grumpy snowballs walk back and forth along the ground. Land on one from above and it squashes flat (with swirly eyes and stars), Tux bounces up (higher if you hold jump), and you score 100 points, then 200, 400 and 800 for stomps in a row without touching the ground. Run into one from the side and you lose a heart, get knocked back and blink for a moment. Three hearts, and the game starts over when they are gone.

You will need: your project from episode 6, or the starter files below.
You will make: hearts, a hurt method with invincibility, an Enemy class, stomp detection and a combo.
You will learn: how to tell a stomp from a hit, simple patrol AI, and timers for effects.
Starter files: waddle-run-ep06.zip is where this episode begins, waddle-run-ep07.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.5.2, and the numbers quoted below were measured by running it at 60 frames per second. Indentation matters in Python: the new lines on this page keep the indentation they need, so copy it exactly.

Where we start

$ cd waddle-run
$ source .venv/bin/activate
(.venv) $ python game.py

Fish to collect, a score, solid ground. The c and o in the level text (crabs and snowballs) are still just letters.

Step 1: hearts, and getting hurt

Before we have enemies we make the thing they will take away. Make these changes:

Add this after line 49 of your file (STAND_W, STAND_H = 30, 60  # the hitbox is smaller than the picture)

BOUNCE = 560
BOUNCE_HELD = 820
HURT_TIME = 1.6

- - -

Add this after line 72 of your file (art["gold"] = load("fish_gold.png"))

    art["heart"] = load("heart.png")
    art["heart_empty"] = load("heart_empty.png")
    art["crab"] = [load("crab_0.png"), load("crab_1.png")]
    art["crab_squash"] = load("crab_squash.png")
    art["ball"] = load("snowball.png")
    art["ball_squash"] = load("snowball_squash.png")
    art["hurt"] = load("penguin_hurt.png")

- - -

Add this after line 153 of your file (self.buffer = 0.0)

        self.hearts = 3
        self.invincible = 0.0
        self.combo = 0
        self.prev_bottom = y

- - -

Add this after line 194 of your file (self.vy = -JUMP_CUT)

        self.prev_bottom = self.y

- - -

Add this after line 196 of your file (self.move_y(self.vy * dt))

        if self.on_ground:
            self.combo = 0
        self.invincible = max(0.0, self.invincible - dt)

- - -

Add this after line 200 of your file (self.buffer = BUFFER)

    def hurt(self):
        if self.invincible > 0:
            return False
        self.hearts -= 1
        self.invincible = HURT_TIME
        self.vy = -450
        self.vx = -self.facing * 320
        return True

- - -

Add this after line 207 of your file (img = art["jump"])

        if self.invincible > HURT_TIME - 0.4:
            img = art["hurt"]

- - -

Add this after line 209 of your file (img = pygame.transform.flip(img, True, False))

        if int(self.invincible * 14) % 2 == 1 and self.invincible < HURT_TIME - 0.4:
            return  # blink while invincible

- - -

Add this after line 275 of your file (draw_text(screen, self.font, f"Score {self.score}", (WIDTH - 230, 20)))

        for i in range(3):
            screen.blit(self.art["heart" if i < self.tux.hearts else "heart_empty"], (24 + i * 38, 20))

What is new:

HURT_TIME = 1.6         how long Tux is invincible after a hit. Without it one touch would take all three hearts in three frames
BOUNCE, BOUNCE_HELD     the upward speed after a stomp: 560, or 820 if you are holding jump. We use them in step 2
self.hearts, self.invincible   three hearts, and a timer that counts down in update
self.prev_bottom        where Tux's feet were at the start of the frame. A stomp is decided by where he was, not where he is: we need it in step 2
self.combo              how many stomps in a row; reset to 0 whenever Tux touches the ground
hurt()                  does nothing if he is invincible (returns False). Otherwise: lose a heart, start the timer, throw him up and back (vy = -450, vx opposite to the way he faces)
the hurt picture        for the first 0.4 seconds he shows the ouch face
blinking                the rest of the time he is invincible, int(timer * 14) % 2 flips between 0 and 1, fourteen times a second, and when it is 1 the draw returns early and draws nothing. Blinking is a signal everyone knows
the heart icons         three hearts in the corner: red for each heart he has, grey for each he has lost

Run it:

(.venv) $ python game.py

Three hearts appear in the top left. Nothing can hurt Tux yet, so they stay full. (Checked: Tux starts with 3 hearts.)

Step 2: crabs and snowballs

Now the enemies. Make these changes:

Add this after line 257 of your file (screen.blit(img, (self.x - cam_x - img.get_width() / 2, self.y + bob - img.get_height() / 2)))

class Enemy:
    """A crab or a grumpy snowball: walks back and forth, turns at walls and at edges. Stomp it from above."""

    def __init__(self, tx, ty, kind):
        self.kind = kind
        self.x, self.y = tx * TILE + TILE / 2, (ty + 1) * TILE
        self.vx = -60 if kind == "crab" else -90
        self.squash = 0.0
        self.alive = True
        self.t = 0.0

    def rect(self):
        w, h = (40, 28) if self.kind == "crab" else (36, 36)
        return pygame.Rect(round(self.x - w / 2), round(self.y - h), w, h)

    def update(self, dt, tux_x):
        self.t += dt
        if abs(self.x - tux_x) > WIDTH // 2 + 160:  # asleep until it is just off screen, so it waits where the level put it
            return
        if self.squash > 0:
            self.squash -= dt
            if self.squash <= 0:
                self.alive = False
            return
        ahead = self.x + (24 if self.vx > 0 else -24)
        wall = tile_at(int(ahead // TILE), int((self.y - 8) // TILE)) in "#=B"
        edge = tile_at(int(ahead // TILE), int(self.y // TILE)) not in "#=B"
        if wall or edge:
            self.vx = -self.vx
        self.x += self.vx * dt

    def stomp(self):
        self.squash = 0.4

    def draw(self, screen, art, cam_x):
        if self.kind == "crab":
            img = art["crab_squash"] if self.squash > 0 else art["crab"][int(self.t * 6) % 2]
        else:
            img = art["ball_squash"] if self.squash > 0 else pygame.transform.rotate(art["ball"], -self.t * 200 * (1 if self.vx > 0 else -1) % 360)
        screen.blit(img, (self.x - cam_x - img.get_width() / 2, self.y - img.get_height()))

- - -

Add this after line 273 of your file (self.tux = Tux(*self.start))

        self.enemies = [Enemy(tx, ty, "crab" if ch == "c" else "ball") for ty, row in enumerate(LEVEL) for tx, ch in enumerate(row) if ch in "co"]

- - -

Add this after line 290 of your file (self.score += 50 if fish.gold else 10)

        for enemy in self.enemies:
            enemy.update(dt, tux.x)
            if enemy.squash > 0 or not enemy.alive or not tux.rect().colliderect(enemy.rect()):
                continue
            if tux.vy > 0 and tux.prev_bottom <= enemy.rect().top + 16:  # landing on it from above
                enemy.stomp()
                tux.vy = -(BOUNCE_HELD if keys[pygame.K_SPACE] or keys[pygame.K_UP] else BOUNCE)
                tux.combo += 1
                self.score += 100 * 2 ** min(tux.combo - 1, 3)  # chained stomps without touching the ground: 100, 200, 400, 800
            else:
                self.hit()
        self.enemies = [e for e in self.enemies if e.alive]

- - -

Add this after line 292 of your file (def fall(self):)

        self.tux.invincible = 0.0  # falling always costs a heart
        self.hit()

- - -

Add this after line 294 of your file (self.tux.vx = self.tux.vy = 0.0)

    def hit(self):
        if self.tux.hurt():
            if self.tux.hearts <= 0:
                self.lose()

    def lose(self):
        self.reset()

- - -

Add this after line 301 of your file (fish.draw(screen, self.art, self.cam_x, self.t))

        for enemy in self.enemies:
            enemy.draw(screen, self.art, self.cam_x)

What is new:

class Enemy             one class for both kinds. A crab walks at 60 pixels a second and a snowball at 90. Their hitboxes differ: 40 by 28 and 36 by 36
asleep until near       update does nothing when the enemy is more than half a window plus 160 pixels away from Tux. Enemies stay exactly where the level put them until they are about to appear, so the designer decides where you meet them
wall and edge           before moving, look one step ahead: if the tile ahead is solid, it is a wall, and if the tile under it is not solid, it is an edge. At either, turn round. Crabs patrol the ground between obstacles and never walk into the water
the stomp test          touching an enemy is a stomp if Tux is falling (vy > 0) AND his feet at the start of the frame were above the enemy's top (plus 16 pixels of forgiveness). Everything else is a hit
enemy.stomp()           sets a timer: 0.4 seconds of squashed picture, then it is removed
tux.vy = -BOUNCE        the bounce. Holding jump gives the bigger one: BOUNCE_HELD
the combo               each stomp adds 1 to combo and scores 100 * 2 ** (combo - 1), capped at 800. combo goes back to 0 when Tux lands
hit()                   hurt Tux. If he has no hearts left, start over (episode 9 turns this into a game over screen)
fall()                  falling in the water now costs a heart as well
a list rebuilt          self.enemies = [e for e in self.enemies if e.alive] removes the squashed ones after the loop. We never remove from a list while looping over it

Run it:

(.venv) $ python game.py

Crabs patrol the ground; the grumpy snowball rolls along the ice. Jump on a crab: it goes flat with stars, Tux bounces and you score 100. Stomp two without landing and the second is worth 200. Run into one from the side: Tux loses a heart, flies back and blinks. Lose all three and the level starts again. (Checked: 8 crabs and 3 snowballs in the level. A stomp squashes the crab for 0.4 seconds, throws Tux up at 560 pixels per second, which is a bounce of 65 pixels, or 140 if jump is held, and scores 100. Touching a crab from the side leaves 2 hearts and 1.6 seconds of invincibility.) The whole file after step 2 is also waddle-run-ep07.zip.
Waddle Run episode 7 running
Episode 7 running (a screenshot of the finished episode).

Tuning the feel

Enemies are a few numbers:

the +16 in the stomp test      how forgiving a stomp is. 0 means your feet must be exactly above the top of the enemy; larger forgives a late jump. Try 40
BOUNCE and BOUNCE_HELD         560 is a small bounce and 820 a big one. The big one reaches 140 pixels, enough to chain a stomp onto another crab
HURT_TIME                      too short and enemies chew you up; too long and the penguin feels invincible
crab speed 60, snowball 90     the snowball is faster, so it is harder to time

Try it yourself

Three small changes before episode 8:

1  Make the crabs twice as fast. Is the level still fun?
2  Give Tux five hearts. (The drawing loop uses range(3): change it too.)
3  Make a stomp give a bigger bounce when Tux is moving fast. (Hint: use abs(tux.vx).)

Episode 8 makes the ground slippery.

Check your work

If something is different:

KeyError: 'crab'                         the enemy pictures are missing from load_art
a stomp counts as a hit                  prev_bottom is not being set at the start of Tux.update, or the check uses the current y
the crab never moves                     Tux is too far away: enemies sleep until they are almost on screen
a crab walks off the edge                the edge test looks at the tile under the next step: check the int(self.y // TILE) line
the second stomp scores the same         combo is reset every frame: it must reset only when Tux is on the ground
losing all hearts does nothing           hit() must call lose() when hearts reach 0

Not run in the lab: more than the 11 enemies of the level, and enemies that jump or shoot.