๐Ÿ”Š Burger Blaster, Episode 8

Make a sound from nothing, play it, and add the little extras that make a game feel good. Three small steps, each one run before it was written down.

Video: Burger Blaster, Episode 8 (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 8 ends with this: a pew for every fry, a splat for every hit, a hit sound when the burger is hit, a short jingle for a new wave, a bass riff looping under everything, dots that spray out of a hit shake in the flavor's color, and a screen that shakes.

You will need: your project from episode 7 (a game.py, an art folder and the .venv), or the starter files below. You need no sound files: the sound effects are made by a script, and the music is in the starter zip.
You will make: a script that writes a sound file, and changes to game.py that play sounds and add particles and screen shake.
You will learn: what a sound is as numbers, writing a WAV file with the standard library, the pygame mixer, a particle, and shaking a canvas.
Starter files: burger-blaster-ep07.zip is where this episode begins, burger-blaster-ep08.zip is where it ends. The ep08 zip has the art, the four sounds, the music loop, and make_sounds.py with all four sounds in it.

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 step was run on its own, and what it does is described below. The sounds were heard on the lab machine only through a virtual sound card, so how they sound is for you to judge.

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 game has a title screen, waves, a score and a saved high score, and it is completely silent. The file is 317 lines.

Step 1: make a sound with Python

A sound is a list of numbers: how far a speaker cone is pushed out or pulled in, many thousands of times a second. 44100 numbers for each second is the standard for CD quality sound. A WAV file is those numbers, written one after the other, with a short header. Python's standard library has a module for it, wave, so no packages are needed.

Make a new file in the project called make_sounds.py. This is the whole file for one sound, the pew:

import struct
import wave
from pathlib import Path

RATE = 44100
ROOT = Path(__file__).resolve().parent


def write(path, samples):
    path.parent.mkdir(exist_ok=True)
    with wave.open(str(path), "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(RATE)
        w.writeframes(b"".join(struct.pack("<h", int(max(-1, min(1, s)) * 32000)) for s in samples))


def square(phase):
    return 1.0 if (phase % 1) < 0.5 else -1.0


def sweep(f0, f1, dur, wavefn, vol=0.5):
    out, phase, n = [], 0.0, int(RATE * dur)
    for i in range(n):
        t = i / n
        phase += (f0 + (f1 - f0) * t) / RATE
        out.append(wavefn(phase) * vol * (1 - t) ** 1.5)
    return out


if __name__ == "__main__":
    write(ROOT / "sounds" / "pew.wav", sweep(1500, 500, 0.12, square, 0.28))

What each part does:

RATE = 44100                       samples per second
write(path, samples)               writes a list of numbers between -1 and 1 as a WAV file: 1 channel (mono), 2 bytes (16 bits) per sample, at RATE
struct.pack("<h", ...)             turns each number into a signed 16-bit integer (2 bytes). The number is first clamped between -1 and 1 and then scaled to 32000, a little under the 32767 maximum, so it cannot overflow
square(phase)                      a square wave: +1 for the first half of each cycle, -1 for the second half. It sounds buzzy, like an old game console. phase is how far through the cycle we are, as a number that goes 0 to 1 and then wraps
sweep(f0, f1, dur, wavefn, vol)    one sound with a pitch that slides from f0 to f1 hertz over dur seconds. The phase grows by (frequency / RATE) for each sample, and the volume (1 - t) ** 1.5 fades to nothing at the end, so there is no click
sweep(1500, 500, 0.12, square, 0.28)   the pew: a high buzz that falls from 1500 Hz to 500 Hz in an eighth of a second, at 28 percent volume
path.parent.mkdir(exist_ok=True)   makes the sounds folder if it is not there

Run it:

(.venv) $ python make_sounds.py
(.venv) $ ls -la sounds
-rw-rw-r-- 1 ubuntu ubuntu 10628 ... pew.wav

(Checked in the lab: pew.wav has 5292 samples, which is 0.12 seconds, and is 10628 bytes: 44 bytes of header and 2 bytes for each sample.) The other three sounds are made with the same two functions, plus a noise function for the splat and the hit. The make_sounds.py in the ep08 zip makes all four, and the files it writes are byte for byte the ones in the zip.

Step 2: play sounds and music

Copy the sounds folder and the music folder from the starter zip into the project (they contain the other three sounds and the music loop):

(.venv) $ unzip -o -q ~/Downloads/burger-blaster-ep08.zip 'burger-blaster/sounds/*' 'burger-blaster/music/*' -d ~

(This puts them into ~/burger-blaster, if your project is there. Otherwise copy the two folders by hand.) The music is a bass riff recorded for this series. Then make these changes to game.py: constants for the folders, a load_sounds function, a play method in Game, and a call to play in four places. The whole file after step 2:

#!/usr/bin/env python3
"""Burger Blaster: a hamburger shoots french fries at angry milkshakes."""
import json
import os
import random
import sys
from pathlib import Path

import pygame

WIDTH, HEIGHT = 1280, 720
FPS = 60
HERE = Path(__file__).resolve().parent
ART = HERE / "art"
SOUNDS = HERE / "sounds"
MUSIC = HERE / "music" / "loop.wav"
SAVE = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "burger-blaster" / "highscore.json"

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 load_sounds():
    try:
        pygame.mixer.init()
    except pygame.error:  # no sound card: the game still runs
        return {}
    return {p.stem: pygame.mixer.Sound(p) for p in SOUNDS.glob("*.wav")}


def load_high():
    try:
        return json.loads(SAVE.read_text())["high"]
    except (OSError, ValueError, KeyError):
        return 0


def save_high(score):
    SAVE.parent.mkdir(parents=True, exist_ok=True)
    SAVE.write_text(json.dumps({"high": score}))


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
        self.invulnerable = 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
        self.invulnerable -= 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):
        if self.invulnerable > 0 and int(self.invulnerable * 10) % 2:
            return  # blink while safe
        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.font = pygame.font.Font(None, 52)
        self.big_font = pygame.font.Font(None, 150)
        self.high = load_high()
        self.state = "title"
        self.sounds = load_sounds()
        if self.sounds:
            pygame.mixer.music.load(MUSIC)
            pygame.mixer.music.set_volume(0.35)
            pygame.mixer.music.play(-1)
        self.new_game()

    def new_game(self):
        self.score = 0
        self.lives = 3
        self.wave = 0
        self.wave_timer = 0
        self.player.reset()
        self.fries.clear()
        self.shakes.clear()
        self.splats.clear()

    def play(self, name):
        if name in self.sounds:
            self.sounds[name].play()

    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
            boost = 1 + 0.12 * (self.wave - 1)
            self.shakes.append(Shake(pos, "big", random.choice(FLAVORS), boost))

    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))
        self.score += 20 if shake.size == "big" else 50
        self.play("splat")
        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 check_player_hit(self):
        player = self.player
        if player.invulnerable > 0:
            return
        for shake in self.shakes:
            if player.pos.distance_to(shake.pos) < player.radius + shake.radius * 0.8:
                self.splats.append(Splat(player.pos, "chocolate"))
                self.lives -= 1
                self.play("hit")
                player.reset()
                player.invulnerable = 2.0
                if self.lives == 0:
                    self.game_over()
                return

    def game_over(self):
        self.state = "over"
        if self.score > self.high:
            self.high = self.score
            save_high(self.high)

    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
                elif event.key == pygame.K_RETURN and self.state != "play":
                    self.new_game()
                    self.state = "play"

    def update(self, dt):
        if self.state == "play":
            self.update_play(dt)
        for splat in self.splats:
            splat.update(dt)
        self.splats = [s for s in self.splats if s.age < Splat.DURATION]

    def update_play(self, dt):
        keys = pygame.key.get_pressed()
        self.player.update(dt, keys)
        fry = self.player.shoot(keys)
        if fry:
            self.fries.append(fry)
            self.play("pew")
        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)
        self.wave_timer -= dt if not self.shakes else 0
        if not self.shakes and self.wave_timer <= 0:
            self.wave += 1
            self.spawn_shakes(2 + self.wave)
            self.wave_timer = 1.5
            self.play("wave")
        self.check_fry_hits()
        self.check_player_hit()

    def draw_text(self, surf, text, font, center, color=(255, 255, 255)):
        shadow = font.render(text, True, (20, 20, 40))
        surf.blit(shadow, shadow.get_rect(center=(center[0] + 3, center[1] + 4)))
        label = font.render(text, True, color)
        surf.blit(label, label.get_rect(center=center))

    def draw_hud(self, surf):
        self.draw_text(surf, f"Score {self.score}", self.font, (130, 36))
        self.draw_text(surf, f"Wave {self.wave}", self.font, (WIDTH / 2, 36))
        self.draw_text(surf, f"Best {self.high}", self.font, (WIDTH - 110, 36))
        for i in range(self.lives):
            surf.blit(IMG["life"], (24 + i * 46, HEIGHT - 60))

    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)
        if self.state == "play":
            self.player.draw(surf)
        if self.state == "play":
            self.draw_hud(surf)
        elif self.state == "title":
            self.draw_text(surf, "BURGER BLASTER", self.big_font, (WIDTH / 2, 250))
            self.draw_text(surf, "Arrow keys fly, Space fires", self.font, (WIDTH / 2, 380))
            self.draw_text(surf, "Press Enter to start", self.font, (WIDTH / 2, 450), (255, 220, 90))
        else:
            self.draw_text(surf, "GAME OVER", self.big_font, (WIDTH / 2, 250))
            self.draw_text(surf, f"Score {self.score}   Best {self.high}", self.font, (WIDTH / 2, 380))
            self.draw_text(surf, "Press Enter to play again", self.font, (WIDTH / 2, 450), (255, 220, 90))
        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:

pygame.mixer.init()                starts the mixer: the part of pygame that plays sound. It fails with pygame.error on a machine without sound, and load_sounds catches that and returns an empty dictionary, so the game is silent and does not crash
pygame.mixer.Sound(path)           loads a WAV file into memory, ready to play at once. All the files in the sounds folder are loaded, under their file name without .wav: 'pew', 'splat', 'hit', 'wave'
self.sounds[name].play()           plays a sound. The same sound can play several times at once, so a fast stream of fries makes a stream of pews
play(name)                         one method for all of it, and it does nothing if the sound is not loaded, so a missing file or no sound card never stops the game
pygame.mixer.music                 a second player, for one long piece of music. load, set_volume(0.35) and play(-1), where -1 means loop for ever. 0.35 keeps it under the sound effects
the four calls                     pew when a fry is shot, splat in pop, hit when the burger is hit, wave when a new wave starts

Run it:

(.venv) $ python game.py

Press Enter. Every shot goes pew, every hit goes splat, and the bass riff loops underneath. (Checked in the lab, with a silent test audio driver: all four sounds were loaded, the music was playing, play('nothing') did nothing, and a hit on a shake called the splat sound, and a new wave called the wave sound.)

Step 3: particles and screen shake

This is what game makers call juice: small things that change nothing about the rules and a lot about how the game feels. Two of them: particles, and a shaking screen. The whole file after step 3, which is also the file in burger-blaster-ep08.zip:

#!/usr/bin/env python3
"""Burger Blaster: a hamburger shoots french fries at angry milkshakes."""
import json
import os
import random
import sys
from pathlib import Path

import pygame

WIDTH, HEIGHT = 1280, 720
FPS = 60
HERE = Path(__file__).resolve().parent
ART = HERE / "art"
SOUNDS = HERE / "sounds"
MUSIC = HERE / "music" / "loop.wav"
SAVE = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "burger-blaster" / "highscore.json"

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"]
FLAVOR_COLORS = {"strawberry": (255, 120, 160), "chocolate": (150, 95, 65), "mint": (120, 220, 185)}

IMG = {}


def load_images():
    return {p.stem: pygame.image.load(p).convert_alpha() for p in ART.glob("*.png")}


def load_sounds():
    try:
        pygame.mixer.init()
    except pygame.error:  # no sound card: the game still runs
        return {}
    return {p.stem: pygame.mixer.Sound(p) for p in SOUNDS.glob("*.wav")}


def load_high():
    try:
        return json.loads(SAVE.read_text())["high"]
    except (OSError, ValueError, KeyError):
        return 0


def save_high(score):
    SAVE.parent.mkdir(parents=True, exist_ok=True)
    SAVE.write_text(json.dumps({"high": score}))


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
        self.invulnerable = 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
        self.invulnerable -= 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):
        if self.invulnerable > 0 and int(self.invulnerable * 10) % 2:
            return  # blink while safe
        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 Particle:
    def __init__(self, pos, color):
        self.pos = pygame.Vector2(pos)
        self.vel = pygame.Vector2(random.uniform(80, 280), 0).rotate(random.uniform(0, 360))
        self.color = color
        self.life = random.uniform(0.3, 0.6)

    def update(self, dt):
        self.pos += self.vel * dt
        self.vel *= 0.92
        self.life -= dt

    def draw(self, surf):
        pygame.draw.circle(surf, self.color, self.pos, max(1, int(self.life * 9)))


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.font = pygame.font.Font(None, 52)
        self.big_font = pygame.font.Font(None, 150)
        self.high = load_high()
        self.state = "title"
        self.sounds = load_sounds()
        self.particles = []
        self.shake_time = 0
        self.canvas = self.screen.copy()
        if self.sounds:
            pygame.mixer.music.load(MUSIC)
            pygame.mixer.music.set_volume(0.35)
            pygame.mixer.music.play(-1)
        self.new_game()

    def new_game(self):
        self.score = 0
        self.lives = 3
        self.wave = 0
        self.wave_timer = 0
        self.player.reset()
        self.fries.clear()
        self.shakes.clear()
        self.splats.clear()
        self.particles.clear()

    def play(self, name):
        if name in self.sounds:
            self.sounds[name].play()

    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
            boost = 1 + 0.12 * (self.wave - 1)
            self.shakes.append(Shake(pos, "big", random.choice(FLAVORS), boost))

    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))
        self.score += 20 if shake.size == "big" else 50
        self.play("splat")
        self.shake_time = max(self.shake_time, 0.12)
        for _ in range(14):
            self.particles.append(Particle(shake.pos, FLAVOR_COLORS[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 check_player_hit(self):
        player = self.player
        if player.invulnerable > 0:
            return
        for shake in self.shakes:
            if player.pos.distance_to(shake.pos) < player.radius + shake.radius * 0.8:
                self.splats.append(Splat(player.pos, "chocolate"))
                self.lives -= 1
                self.play("hit")
                self.shake_time = 0.35
                player.reset()
                player.invulnerable = 2.0
                if self.lives == 0:
                    self.game_over()
                return

    def game_over(self):
        self.state = "over"
        if self.score > self.high:
            self.high = self.score
            save_high(self.high)

    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
                elif event.key == pygame.K_RETURN and self.state != "play":
                    self.new_game()
                    self.state = "play"

    def update(self, dt):
        if self.state == "play":
            self.update_play(dt)
        for splat in self.splats:
            splat.update(dt)
        self.splats = [s for s in self.splats if s.age < Splat.DURATION]

    def update_play(self, dt):
        keys = pygame.key.get_pressed()
        self.player.update(dt, keys)
        fry = self.player.shoot(keys)
        if fry:
            self.fries.append(fry)
            self.play("pew")
        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)
        self.wave_timer -= dt if not self.shakes else 0
        if not self.shakes and self.wave_timer <= 0:
            self.wave += 1
            self.spawn_shakes(2 + self.wave)
            self.wave_timer = 1.5
            self.play("wave")
        self.check_fry_hits()
        self.check_player_hit()

    def update_effects(self, dt):
        for particle in self.particles:
            particle.update(dt)
        self.particles = [p for p in self.particles if p.life > 0]
        self.shake_time = max(0, self.shake_time - dt)

    def draw_text(self, surf, text, font, center, color=(255, 255, 255)):
        shadow = font.render(text, True, (20, 20, 40))
        surf.blit(shadow, shadow.get_rect(center=(center[0] + 3, center[1] + 4)))
        label = font.render(text, True, color)
        surf.blit(label, label.get_rect(center=center))

    def draw_hud(self, surf):
        self.draw_text(surf, f"Score {self.score}", self.font, (130, 36))
        self.draw_text(surf, f"Wave {self.wave}", self.font, (WIDTH / 2, 36))
        self.draw_text(surf, f"Best {self.high}", self.font, (WIDTH - 110, 36))
        for i in range(self.lives):
            surf.blit(IMG["life"], (24 + i * 46, HEIGHT - 60))

    def draw(self):
        surf = self.canvas
        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)
        if self.state == "play":
            self.player.draw(surf)
        for particle in self.particles:
            particle.draw(surf)
        if self.state == "play":
            self.draw_hud(surf)
        elif self.state == "title":
            self.draw_text(surf, "BURGER BLASTER", self.big_font, (WIDTH / 2, 250))
            self.draw_text(surf, "Arrow keys fly, Space fires", self.font, (WIDTH / 2, 380))
            self.draw_text(surf, "Press Enter to start", self.font, (WIDTH / 2, 450), (255, 220, 90))
        else:
            self.draw_text(surf, "GAME OVER", self.big_font, (WIDTH / 2, 250))
            self.draw_text(surf, f"Score {self.score}   Best {self.high}", self.font, (WIDTH / 2, 380))
            self.draw_text(surf, "Press Enter to play again", self.font, (WIDTH / 2, 450), (255, 220, 90))
        offset = (0, 0)
        if self.shake_time > 0:
            amount = int(self.shake_time * 40)
            offset = (random.randint(-amount, amount), random.randint(-amount, amount))
        self.screen.blit(surf, offset)
        pygame.display.flip()

    def run(self):
        while self.running:
            dt = self.clock.tick(FPS) / 1000
            self.handle_events()
            self.update(dt)
            self.update_effects(dt)
            self.draw()
        pygame.quit()


if __name__ == "__main__":
    Game().run()
    sys.exit(0)

What is new:

FLAVOR_COLORS                      a color for each flavor, the color of the particles
class Particle                     a tiny dot with a position, a velocity in a random direction and with a random speed, a color and a life of 0.3 to 0.6 seconds
self.vel *= 0.92                   in update: the dot loses 8 percent of its speed every frame, so it flies out quickly and slows down
max(1, int(self.life * 9))         the radius of the dot, from about 5 pixels down to 1 as its life runs out, so it shrinks away
14 particles in pop                one burst for every hit shake, in the color of its flavor
update_effects                     moves all the particles, removes the dead ones, and counts the shake timer down. It runs every frame, in every state
shake_time                         a timer in seconds: 0.12 when a shake is hit, 0.35 when the burger is hit
self.canvas = self.screen.copy()   a spare surface of the same size. The whole game is drawn on the canvas and not on the window
amount = int(self.shake_time * 40)   the biggest shift in pixels: 14 right after the burger is hit, and smaller as the timer runs down
self.screen.blit(surf, offset)     the last step: the canvas is copied to the window, moved by a random offset. With no shake the offset is (0, 0) and nothing moves

Run it:

(.venv) $ python game.py

Hit a shake: a spray of dots in its color, and a small jolt. Get hit yourself: a bigger jolt. Nothing in the rules has changed. (Checked: a hit made 14 particles and set the shake timer to 0.12; one second later there were no particles left and the timer was 0; a hit on the burger set the timer to 0.35.)
Burger Blaster episode 8 running
Episode 8 running.

Tuning the feel

The feel is in a handful of numbers:

1500, 500 and 0.12 in the pew       the sound of the shot. Try 800 to 200 for something heavier, or 0.3 seconds for something longer
0.35 for the music                  how loud the bass is next to the effects
14 particles and the speed range 80 to 280    the size of the burst
0.12 and 0.35 in shake_time, and * 40    the strength of the shake

A good rule for juice is that the bigger the event, the bigger the reaction. A small hit gets a small jolt, being hit gets a big one.

Try it yourself

Four small changes before the last episode:

1  Change the pew into a lower, longer sound: sweep(600, 200, 0.2, square, 0.28), run make_sounds.py again and play.
2  Make the music louder and quieter. Is 0.35 right for you?
3  Give the particles 40 pieces. Is it better, or just messy?
4  Make the screen shake only when the burger is hit.

Episode 9 is the last one: a launcher for the GNOME menu, an icon, a man page and a .deb package that anyone can install.

Check your work

If something is different:

pygame.error: mixer not initialized / no sound at all     the machine has no sound device. The game continues in silence, which is what load_sounds is for
FileNotFoundError: music/loop.wav                          the music folder is missing: unpack the starter zip
no pew                                                     sounds/pew.wav is missing: run make_sounds.py, and check that the folder is called sounds
the screen does not shake                                  self.screen.blit(surf, offset) must be the last thing before display.flip, and draw must draw on self.canvas
the dots are all one color                                 FLAVOR_COLORS[shake.flavor] is the color, and the flavor must be passed on
TypeError: 'NoneType' ... in play                          play() has to be a method of Game: self.play("pew")

Not run in the lab: other Linux distributions, Wayland-only sessions, a real sound card and pygame older than 2.6. The numbers in the checks come from running the stages with a silent audio driver.