"""Zombie Town: hold out for ten waves in a walled-in town. Buy guns between waves.

    python make_art.py      once: draws stand-in art into game-assets/
    python make_sfx.py      once: makes the sound effects
    python main.py          play solo in a desktop window
    python build.py         then serve the folder to play in a browser

Co-op (two players) runs in the browser only, over a direct WebRTC link. No server:
the two players swap two short invite codes once (see peer.py).

The rules live in rules.py. This file draws them and turns keys, clicks and taps
into decisions. In co-op the host's machine runs the rules; the friend's machine
sends its decisions and draws the host's picture of the town.
"""
import asyncio
import math
import random
import time
import traceback

import rules as R
import storage
from settings import *
from support import import_audio, import_folder_dict, import_sub_folders

CHARACTERS = ('player', 'walker', 'runner', 'brute', 'spitter', 'boss')
GUN_LENGTH = {'pistol': 14, 'shotgun': 22, 'smg': 18, 'rifle': 27}
GUN_KEYS = {pygame.K_1: 0, pygame.K_2: 1, pygame.K_3: 2, pygame.K_4: 3,
            pygame.K_KP1: 0, pygame.K_KP2: 1, pygame.K_KP3: 2, pygame.K_KP4: 3}
SHAKE = {'pistol': 1.5, 'smg': 1.2, 'shotgun': 5, 'rifle': 3.5}
BLOOD = {'walker': (110, 22, 24), 'runner': (120, 20, 24), 'brute': (96, 20, 22),
         'spitter': (120, 176, 40), 'boss': (100, 24, 60)}
COLOUR_CHOICES = [('red', (236, 80, 72)), ('blue', (110, 210, 255)),
                  ('green', (155, 225, 93)), ('yellow', (255, 204, 64))]
COLOUR_RGB = dict(COLOUR_CHOICES)
NAME_MAX = 10
MAX_PLAYERS = 6                                        # teams only
NON_TEAM_PLAYERS = 4                                   # co-op and versus: one colour each, so four players
LOBBY_SCENES = ('lobby', 'pick_team', 'view_teams')     # the screens that keep the room list up to date
TEAM_COLOURS = {'A': 'red', 'B': 'blue'}                 # teams mode: the team is the colour, not the player
SEND_EVERY = 1 / 15                                   # how often the two machines talk

INK = (232, 238, 222)
DIM = (150, 160, 146)
GREEN = (155, 225, 93)
GOLD = (255, 204, 64)
RED = (236, 80, 72)
PANEL = (16, 22, 18)
EDGE = (70, 96, 66)


def loading(percent, message=''):
    """Move the page's loading bar (index.html). Does nothing on desktop."""
    if IS_WEB:
        from pyscript import window
        window.loadingStep(percent, message)


def is_touch_device():
    """A phone or tablet: no mouse to hover with, so no keyboard either."""
    if not IS_WEB:
        return False
    try:
        from js import window
        return bool(window.matchMedia('(hover: none) and (pointer: coarse)').matches)
    except Exception:
        return False


def saved_number(key):
    try:
        return int(storage.load(key, '0'))
    except ValueError:
        return 0


def with_left_frames(frames):
    """Make every '..._left' animation by flipping the '..._right' one, once at load."""
    for name in [n for n in frames if n.endswith('_right')]:
        left = name[:-len('right')] + 'left'
        if left not in frames:
            frames[left] = [pygame.transform.flip(frame, True, False) for frame in frames[name]]
    return frames


def wrap(font, text, width):
    """Split text into lines that fit `width` pixels in `font`."""
    lines, line = [], ''
    for word in text.split():
        test = f'{line} {word}'.strip()
        if font.size(test)[0] > width and line:
            lines.append(line)
            line = word
        else:
            line = test
    if line:
        lines.append(line)
    return lines


def facing_of(direction):
    if abs(direction.x) > abs(direction.y):
        return 'right' if direction.x > 0 else 'left'
    return 'down' if direction.y > 0 else 'up'


class Button:
    def __init__(self, label, rect, action, enabled=True, key_hint=''):
        self.label = label
        self.rect = pygame.Rect(rect)
        self.action = action
        self.enabled = enabled
        self.key_hint = key_hint

    def draw(self, screen, font, mouse, small=None):
        hover = self.enabled and self.rect.collidepoint(mouse)
        fill = (44, 66, 40) if hover else (26, 36, 26)
        if not self.enabled:
            fill = (24, 26, 24)
        pygame.draw.rect(screen, fill, self.rect, border_radius=10)
        pygame.draw.rect(screen, GREEN if hover else (EDGE if self.enabled else (50, 54, 50)), self.rect, 2, border_radius=10)
        text = font.render(self.label, True, INK if self.enabled else (100, 104, 100))
        screen.blit(text, text.get_rect(center=self.rect.center))
        if self.key_hint and small:
            hint = small.render(self.key_hint, True, DIM)
            screen.blit(hint, hint.get_rect(midright=(self.rect.right - 10, self.rect.centery)))


class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
        pygame.display.set_caption('Zombie Town')
        self.clock = pygame.time.Clock()
        self.fonts = {size: pygame.font.Font(None, size) for size in (20, 24, 28, 34, 44, 64, 96)}
        self.import_assets()                    # after set_mode: convert_alpha() needs a display
        self.paint_ground()
        self.touch = is_touch_device()
        self.muted = storage.load('muted', '0') == '1'
        self.difficulty = storage.load('difficulty', 'normal')
        if self.difficulty not in R.DIFFICULTY:
            self.difficulty = 'normal'
        self.scene = 'title'            # title, help, friends, invite, lobby, play, paused, over
        self.rules = None
        self.me = 0                     # which hero is mine
        self.peer = None                # the WebRTC link, co-op only
        self.is_host = True
        self.connected_once = False
        self.pending = []               # host: events not yet sent to the friend
        self.send_clock = 0.0
        self.dirty = self.ground.copy()
        self.time = 0.0
        self.mouse = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)
        self.offset = vector()
        self.reset_effects()
        self.sound_times = {}
        self.muzzle = {}                # hero id → seconds of muzzle flash left
        self.shop_note = ''
        self.end_timer = 0.0
        self.result = None
        self.press = None               # touch: (time, screen pos, walking?)
        self.note = ''
        self.invite_pending = False
        self.my_name = storage.load('name', '')[:NAME_MAX]
        self.my_colour = ''
        self.roster = {}                # friend's view of the room: slot → {'name', 'colour'}
        self.seat_of = {}               # host: friend's slot → their hero number
        self.players = []               # [{'name', 'colour'}] in hero order, for the match
        self.mode = 'coop'              # 'coop', 'versus' or 'teams': the host chooses in the lobby
        self.my_team = ''               # teams: 'A' or 'B', picked in the lobby
        self.shop_open = True           # with a friend: the shop panel is closed while you walk about
        self.shop_tab = 'supply'        # versus: 'supply' or 'sabotage'
        self.room_code = ''
        self.name_cursor = 0.0
        self.online = False
        self.last_move = None
        self.show_timing = False        # F3: how long each part of a frame takes
        self.timings = {}

    # ── loading ─────────────────────────────────────────────────────
    def import_assets(self):
        self.tiles = import_folder_dict('game-assets', 'tiles')
        self.items = import_folder_dict('game-assets', 'items')
        self.frames = {}
        for name in CHARACTERS:
            frames = import_sub_folders('game-assets', name)
            if name == 'brute':                 # brutes use walker-sized art, shown bigger
                frames = {k: [pygame.transform.scale_by(f, 1.4) for f in v] for k, v in frames.items()}
            self.frames[name] = with_left_frames(frames)
        self.tinted = {}                        # (image, colour) → solid-colour silhouette
        try:
            self.sounds = import_audio('game-assets', 'audio')
        except Exception:                       # no sound device: play in silence
            self.sounds = {}
        for name, sound in self.sounds.items():
            sound.set_volume(0.22 if name in ('smg', 'coin', 'hit') else 0.35)
        self.shadows = {}
        for size in (24, 30, 40, 64):
            shadow = pygame.Surface((size, size // 2), pygame.SRCALPHA)
            pygame.draw.ellipse(shadow, (0, 0, 0, 80), shadow.get_rect())
            self.shadows[size] = shadow
        self.hurt_overlay = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT), pygame.SRCALPHA)
        self.hurt_overlay.fill((200, 0, 0, 70))

    def paint_ground(self):
        """Every tile that never changes, painted once onto one big picture."""
        ground = pygame.Surface((R.MAP_W, R.MAP_H))
        T = R.TILE
        rows = R.LEVEL_MAP
        base = {'.': 'road', 'S': 'road', 'C': 'road', ',': 'sidewalk', '"': 'grass', 'P': 'grass',
                'T': 'grass', 'B': 'roof'}

        def at(c, r):
            return rows[r][c] if 0 <= r < R.ROWS and 0 <= c < R.COLS else 'B'

        for r, row in enumerate(rows):
            for c, ch in enumerate(row):
                ground.blit(self.tiles[base[ch]], (c * T, r * T))
        road = set('.SC')
        for r, row in enumerate(rows):                      # lane markings
            for c, ch in enumerate(row):
                if ch in road and at(c, r + 1) in road and at(c, r - 1) not in road:
                    for x in range(c * T + 8, c * T + T, 32):
                        pygame.draw.rect(ground, (214, 186, 70), (x, (r + 1) * T - 2, 16, 4))
                if ch in road and at(c + 1, r) in road and at(c - 1, r) not in road:
                    for y in range(r * T + 8, r * T + T, 32):
                        pygame.draw.rect(ground, (214, 186, 70), ((c + 1) * T - 2, y, 4, 16))
        for r, row in enumerate(rows):                      # building walls and edges
            for c, ch in enumerate(row):
                if ch != 'B':
                    continue
                x, y = c * T, r * T
                if at(c, r + 1) != 'B':
                    pygame.draw.rect(ground, (124, 108, 96), (x, y + T - 18, T, 18))
                    pygame.draw.line(ground, (70, 58, 52), (x, y + T - 18), (x + T, y + T - 18), 2)
                    for wx in (x + 10, x + 38):
                        pygame.draw.rect(ground, (40, 44, 56), (wx, y + T - 14, 14, 9))
                        pygame.draw.rect(ground, (90, 110, 130), (wx + 2, y + T - 12, 4, 3))
                if at(c, r - 1) != 'B':
                    pygame.draw.line(ground, (60, 44, 40), (x, y + 1), (x + T, y + 1), 3)
                if at(c - 1, r) != 'B':
                    pygame.draw.line(ground, (60, 44, 40), (x + 1, y), (x + 1, y + T), 3)
                if at(c + 1, r) != 'B':
                    pygame.draw.line(ground, (60, 44, 40), (x + T - 2, y), (x + T - 2, y + T), 3)
        shade = pygame.Surface((T, 8), pygame.SRCALPHA)
        shade.fill((0, 0, 0, 60))
        for r, row in enumerate(rows):                      # buildings cast a short shadow
            for c, ch in enumerate(row):
                if ch == 'B' and at(c, r + 1) != 'B' and r + 1 < R.ROWS:
                    ground.blit(shade, (c * T, (r + 1) * T))
        cars = ['car_red', 'car_blue', 'car_white']
        n = 0
        for r, row in enumerate(rows):
            for c, ch in enumerate(row):
                if ch == 'C':
                    ground.blit(self.tiles[cars[n % 3]], (c * T, r * T))
                    n += 1
                elif ch == 'T':
                    ground.blit(self.tiles['tree'], (c * T, r * T))
        rng = random.Random(3)                              # old stains: this town has seen trouble
        for _ in range(26):
            c, r = rng.randrange(R.COLS), rng.randrange(R.ROWS)
            if rows[r][c] not in 'BCT':
                self.splat(ground, vector(c * T + rng.randrange(T), r * T + rng.randrange(T)),
                           (70, 30, 30), rng.randrange(6, 14), alpha=70, rng=rng)
        self.ground = ground.convert()

    # ── helpers ─────────────────────────────────────────────────────
    def reset_effects(self):
        self.particles = []
        self.floaters = []
        self.shake = 0.0
        self.hurt_flash = 0.0
        self.banner = None                      # (title, subtitle, seconds left, seconds total)

    def play(self, name):
        sound = self.sounds.get(name)           # a file not made yet is silence, not a crash
        if not sound or self.muted:
            return
        if self.time - self.sound_times.get(name, -1.0) < 0.045:
            return                              # forty of the same sound at once is just noise
        self.sound_times[name] = self.time
        sound.play()

    def text(self, string, size, colour, pos, anchor='topleft', shadow=True):
        key = (string, size, colour, shadow)
        drawn = self.text_cache.get(key) if hasattr(self, 'text_cache') else None
        if drawn is None:                       # the HUD says the same things most frames: draw once
            if not hasattr(self, 'text_cache') or len(self.text_cache) > 600:
                self.text_cache = {}
            font = self.fonts[size]
            drawn = (font.render(string, True, colour), font.render(string, True, (0, 0, 0)) if shadow else None)
            self.text_cache[key] = drawn
        image, dark = drawn
        rect = image.get_rect(**{anchor: pos})
        if dark:
            self.screen.blit(dark, rect.move(2, 2))
        self.screen.blit(image, rect)
        return rect

    def dim(self):
        """Darken everything behind a menu. A multiply fill: a see-through full-screen
        picture would cost ~30 ms a frame in the browser."""
        self.screen.fill((70, 78, 70), special_flags=pygame.BLEND_RGB_MULT)

    def world(self, screen_pos):
        return vector(screen_pos) - self.offset

    def tint(self, image, colour):
        key = (id(image), colour)
        if key not in self.tinted:
            self.tinted[key] = pygame.mask.from_surface(image).to_surface(setcolor=colour, unsetcolor=(0, 0, 0, 0))
        return self.tinted[key]

    def splat(self, surface, pos, colour, size, alpha=170, rng=random):
        blot = pygame.Surface((size * 4, size * 4), pygame.SRCALPHA)
        centre = size * 2
        for _ in range(7):
            r = rng.randint(max(2, size // 3), size)
            off = (rng.randint(-size, size), rng.randint(-size, size))
            pygame.draw.circle(blot, (*colour, alpha), (centre + off[0] // 2, centre + off[1] // 2), r)
        for _ in range(6):
            off = (rng.randint(-size * 2 + 2, size * 2 - 2), rng.randint(-size * 2 + 2, size * 2 - 2))
            pygame.draw.circle(blot, (*colour, alpha), (centre + off[0], centre + off[1]), rng.randint(1, 3))
        surface.blit(blot, (pos.x - centre, pos.y - centre))

    def burst(self, pos, colour, count, speed=160, size=3, life=0.45):
        for _ in range(count):
            angle = random.uniform(0, 2 * math.pi)
            v = vector(math.cos(angle), math.sin(angle)) * random.uniform(speed * 0.3, speed)
            self.particles.append([vector(pos), v, life * random.uniform(0.6, 1.0), life, colour, size])
        del self.particles[:-500]

    def floater(self, text, colour, pos):
        self.floaters.append([text, colour, vector(pos), 0.9])

    def panel(self, rect, alpha=200):
        key = (rect.size, alpha)
        if not hasattr(self, 'panels'):
            self.panels = {}
        if key not in self.panels:
            box = pygame.Surface(rect.size, pygame.SRCALPHA)
            pygame.draw.rect(box, (*PANEL, alpha), box.get_rect(), border_radius=10)
            pygame.draw.rect(box, (*EDGE, 255), box.get_rect(), 2, border_radius=10)
            self.panels[key] = box
        self.screen.blit(self.panels[key], rect)

    def wrap(self, string, size, colour, x, y, width):
        font = self.fonts[size]
        line = ''
        for word in string.split():
            test = f'{line} {word}'.strip()
            if font.size(test)[0] > width and line:
                self.screen.blit(font.render(line, True, colour), (x, y))
                y += size - 4
                line = word
            else:
                line = test
        if line:
            self.screen.blit(font.render(line, True, colour), (x, y))

    def draw_hearts(self, x, y, hero):
        for i in range(hero.max_hearts):
            image = self.items['heart' if i < hero.hearts else 'heart_empty']
            self.screen.blit(image, (x + i * 22, y))

    # ── who I am ────────────────────────────────────────────────────
    @property
    def hero(self):
        return self.rules.heroes[self.me]

    def do(self, kind, *args):
        """One decision by me. The host runs it here; a friend sends it to the host."""
        if self.online and not self.is_host:
            # JSON cannot hold a Vector2: send positions as plain [x, y] lists
            plain = [[a.x, a.y] if isinstance(a, vector) else a for a in args]
            self.peer.send({'t': 'act', 'a': [kind, *plain]})
            return True
        return self.rules.act(kind, *args, who=self.me)

    def start_run(self):
        """A solo run."""
        self.online = False
        self.peer = None
        self.me = 0
        self.rules = R.Rules(seed=random.randrange(1 << 30), difficulty=self.difficulty, players=1)
        self.begin_play()

    def begin_play(self):
        self.dirty = self.ground.copy()
        self.reset_effects()
        self.scene = 'play'
        self.end_timer = 0.0
        self.result = None
        self.shop_note = ''
        self.press = None
        self.note = ''
        self.muzzle = {}
        self.pending = []
        self.play('wave_start')

    def start_co_op(self, seed, difficulty, players, me, mode='coop'):
        """Everyone has the same seed and the same player list (hero order); the host's
        machine decides everything. `me` is my hero number."""
        self.online = True
        self.difficulty = difficulty
        self.players = players
        self.me = me
        self.mode = mode
        self.shop_tab = 'supply'
        teams = [p.get('team', 'A') for p in players] if mode == 'teams' else None
        self.rules = R.Rules(seed=seed, difficulty=difficulty, players=len(players), mode=mode, teams=teams)
        self.begin_play()

    def player_name(self, pid):
        if pid < len(self.players) and self.players[pid]['name']:
            return self.players[pid]['name']
        return f'Player {pid + 1}'

    def player_rgb(self, pid):
        if pid < len(self.players):
            return COLOUR_RGB.get(self.players[pid]['colour'], GOLD)
        return GOLD

    def send_identity(self):
        """Tell the room my name, colour and team. A friend tells the host, and the host
        sends the updated list to everyone."""
        if self.is_host:
            self.broadcast_roster()
        elif self.peer and self.peer.connected:
            self.peer.send({'t': 'hello', 'name': self.my_name, 'colour': self.my_colour, 'team': self.my_team})

    def my_slot(self):
        return 0 if self.is_host else (self.peer.slot if self.peer else None)

    def seat_list(self):
        """Everyone in the room, by slot: [(slot, {'name', 'colour', 'team'})]. Slot 0 is the host."""
        if self.is_host:
            entries = {0: {'name': self.my_name, 'colour': self.my_colour, 'team': self.my_team}}
            if self.peer:
                for slot in self.peer.friends_here():
                    entries[slot] = self.roster.get(slot, {'name': '', 'colour': '', 'team': ''})
            return sorted(entries.items())
        return sorted((slot, entry) for slot, entry in self.roster.items())

    def broadcast_roster(self):
        if self.is_host and self.peer:
            self.peer.send_all({'t': 'roster', 'mode': self.mode,
                                'roster': {str(slot): e for slot, e in self.seat_list()}})

    def toggle_mode(self):
        """Host: cycle co-op, versus, teams. The friends see the change at once."""
        if self.is_host:
            order = ['coop', 'versus', 'teams']
            nxt = order[(order.index(self.mode) + 1) % len(order)]
            if nxt != 'teams' and len(self.seat_list()) > NON_TEAM_PLAYERS:
                self.note = 'Co-op and versus are for up to 4 players. Keep teams for more.'
                return
            self.mode = nxt
            self.note = ''
            self.peer.max_friends = self.room_size() - 1
            if self.mode == 'teams':
                self.deal_teams()               # random teams to start; the host can change them
            self.broadcast_roster()

    def room_size(self):
        """How many can be in the room in this mode: teams fill six, co-op and versus four."""
        return MAX_PLAYERS if self.mode == 'teams' else NON_TEAM_PLAYERS

    def taken_colours(self):
        mine = self.my_slot()
        return {e['colour'] for slot, e in self.seat_list() if slot != mine and e['colour']}

    def ready_to_start(self):
        """Host only: at least two players, each with a colour and no two alike. In teams,
        everyone also has a team and both teams have someone on them."""
        if not self.is_host:
            return False
        seats = [e for _, e in self.seat_list()]
        if self.mode == 'teams':                # teams play in team colours: no colour to pick
            teams = [e.get('team') for e in seats]
            return len(seats) >= 2 and all(teams) and 'A' in teams and 'B' in teams
        colours = [e['colour'] for e in seats]
        return len(colours) >= 2 and all(colours) and len(set(colours)) == len(colours)

    def lobby_status(self):
        """One line under the room count: what the host is waiting for."""
        if not self.is_host:
            return 'waiting for the host to start the game'
        if self.note:                           # the host was told why something did not change
            return self.note
        if self.ready_to_start():
            return 'ready to start'
        seats = [e for _, e in self.seat_list()]
        if len(seats) < 2:
            return 'waiting for a friend to join'
        if self.mode != 'teams' and (not all(e['colour'] for e in seats)
                                     or len({e['colour'] for e in seats if e['colour']}) < len(seats)):
            return 'everyone needs a name and a different colour'
        return 'both teams need someone on them'

    def choose_colour(self, colour):
        if colour in self.taken_colours():
            return
        self.my_colour = colour
        storage.save('colour', colour)
        self.send_identity()

    def set_team(self, slot, team):
        if slot == 0:
            self.my_team = team
        elif slot in self.roster:
            self.roster[slot]['team'] = team

    def team_of(self, slot):
        for s, e in self.seat_list():
            if s == slot:
                return e.get('team', '')
        return ''

    def deal_teams(self):
        """Host: put everyone into two teams at random, as evenly as possible."""
        seats = [slot for slot, _ in self.seat_list()]
        random.shuffle(seats)
        for n, slot in enumerate(seats):
            self.set_team(slot, 'A' if n % 2 == 0 else 'B')
        self.broadcast_roster()

    def fill_teams(self):
        """Host: anyone who has no team yet (a friend just joined) goes on the smaller team."""
        seats = self.seat_list()
        for slot, e in seats:
            if e.get('team') in ('A', 'B'):
                continue
            counts = {'A': 0, 'B': 0}
            for _, other in seats:
                if other.get('team') in counts:
                    counts[other['team']] += 1
            if counts['A'] == counts['B']:
                team = random.choice('AB')
            else:
                team = 'A' if counts['A'] < counts['B'] else 'B'
            self.set_team(slot, team)

    def flip_team(self, slot):
        """Host, on the pick teams screen: move one player to the other team."""
        if not self.is_host:
            return
        self.set_team(slot, 'B' if self.team_of(slot) == 'A' else 'A')
        self.broadcast_roster()

    def seat_name(self, slot, entry):
        return entry['name'] or f'Player {slot + 1}'

    def colour_of(self, entry):
        """The colour a player shows: in teams mode, their team's colour; otherwise their own."""
        if self.mode == 'teams' and entry.get('team') in TEAM_COLOURS:
            return TEAM_COLOURS[entry['team']]
        return entry.get('colour', '')

    def team_rows(self):
        """One row per player on the pick teams screen: (slot, entry, rect)."""
        cx = WINDOW_WIDTH // 2
        return [(slot, e, pygame.Rect(cx - 200, 150 + i * 44, 400, 36))
                for i, (slot, e) in enumerate(self.seat_list())]

    def swatch_rects(self):
        cx = WINDOW_WIDTH // 2
        left = cx - (len(COLOUR_CHOICES) * 118 - 8) // 2       # centred row of swatches
        return [(name, pygame.Rect(left + i * 118, 232, 110, 50)) for i, (name, _) in enumerate(COLOUR_CHOICES)]

    def finish_run(self):
        r = self.rules
        mode = r.difficulty
        won = r.state == 'won'
        reached = r.wave
        new_best = reached > saved_number(f'best_wave_{mode}')
        if new_best:
            storage.save(f'best_wave_{mode}', str(reached))
        if won:
            storage.save(f'wins_{mode}', str(saved_number(f'wins_{mode}') + 1))
        self.result = {'won': won, 'wave': reached, 'new_best': new_best and not won,
                       'kills': r.stats['kills'], 'time': r.stats['time'], 'coins': r.stats['coins'],
                       'accuracy': r.stats['hits'] / max(1, r.stats['pellets'])}
        self.scene = 'over'

    def next_difficulty(self):
        order = R.DIFFICULTY_ORDER
        self.difficulty = order[(order.index(self.difficulty) + 1) % len(order)]
        storage.save('difficulty', self.difficulty)

    def toggle_sound(self):
        self.muted = not self.muted
        storage.save('muted', '1' if self.muted else '0')
        if not self.muted:
            self.play('coin')

    # ── the co-op handshake (no server: two short codes) ────────────
    def open_friends(self):
        self.scene = 'friends'
        self.note = ''

    def host_game(self):
        from peer import Peer
        self.is_host = True
        self.scene = 'invite'
        self.room_code = ''
        self.note = 'Making your room code...'
        try:
            self.peer = Peer(host=True)
        except Exception:
            self.note = 'Multiplayer is not ready yet. Reload the page and try again.'
            self.peer = None
            return
        self.peer.max_friends = self.room_size() - 1
        asyncio.ensure_future(self.make_room())

    async def make_room(self):
        code = await self.peer.host_room()
        if code:
            self.room_code = code
            self.note = 'Waiting for your friend to join...'
        else:
            self.note = self.peer.error

    def join_game(self):
        self.is_host = False
        self.peer = None
        self.code_text = ''
        self.scene = 'join_code'
        self.note = 'Type the four digits your friend shows.'

    async def join_room(self):
        from peer import Peer
        self.note = 'Connecting...'
        try:
            self.peer = Peer(host=False)
        except Exception:
            self.note = 'Multiplayer is not ready yet. Reload the page and try again.'
            return
        if await self.peer.join_room(self.code_text):
            self.room_code = self.code_text
        else:
            self.note = self.peer.error
            self.peer.close()
            self.peer = None

    def leave_co_op(self):
        if self.peer:
            self.peer.close()
        self.peer = None
        self.online = False
        self.rules = None
        self.room_code = ''
        self.roster = {}
        self.seat_of = {}

    def return_to_lobby(self):
        """Host: end the match for everyone and go back to the lobby. The room stays open."""
        if self.is_host and self.peer:
            self.peer.send_all({'t': 'lobby'})
        self.enter_lobby()

    def enter_lobby(self):
        self.rules = None
        self.result = None
        self.online = False
        self.pending = []
        self.end_timer = 0.0
        self.scene = 'lobby'
        self.note = ''
        if self.is_host and self.peer:
            self.peer.accepting = True          # the room is open again: more friends can join
            self.broadcast_roster()

    def watch_page_close(self):
        """Browser: closing this page ends the room, so the friends are told at once."""
        from js import window
        from pyodide.ffi import create_proxy
        self.page_close = create_proxy(lambda _event: self.leave_co_op())
        window.addEventListener('pagehide', self.page_close)

    def check_link(self):
        """Once connected, move on to the lobby. In the lobby, keep the room list up to date.
        A friend watches for the host leaving, and for the start."""
        if not self.peer:
            return
        if self.scene in LOBBY_SCENES:
            if self.is_host:
                self.host_lobby_update()
            else:
                for _, m in self.peer.poll():
                    if m.get('t') == 'roster':
                        self.roster = {int(k): v for k, v in m['roster'].items()}
                        self.mode = m.get('mode', self.mode)
                    elif m.get('t') == 'start':
                        self.start_co_op(m['seed'], m['difficulty'], m['players'], m['you'], m.get('mode', 'coop'))
                        return
                    elif m.get('t') == 'left':
                        self.back_to_title()
                        self.note = 'The host left the room.'
                        return
        elif not self.is_host and self.scene == 'over':       # the match is over: wait for the host
            for _, m in self.peer.poll():
                if m.get('t') == 'lobby':
                    self.enter_lobby()
                    return
                if m.get('t') == 'left':
                    self.back_to_title()
                    self.note = 'The host left the game.'
                    return
        if self.peer.connected and self.scene in ('invite', 'join_code'):
            self.connected_once = True
            self.scene = 'lobby'
            self.note = ''
            self.send_identity()
        elif not self.is_host and self.connected_once and not self.peer.connected and self.scene in LOBBY_SCENES + ('play',):
            self.note = 'Lost the connection to the host.'
            self.leave_co_op()
            self.connected_once = False
            self.scene = 'title'

    def host_lobby_update(self):
        """Host: friends joining, leaving or sending their name, colour and team."""
        here = set(self.peer.friends_here())
        changed = False
        for slot in list(self.roster):
            if slot not in here:
                del self.roster[slot]
                changed = True
        for slot in here:
            if slot not in self.roster:
                self.roster[slot] = {'name': '', 'colour': '', 'team': ''}
                changed = True
        for slot, m in self.peer.poll():
            if m.get('t') == 'hello' and slot in self.roster:
                team = self.roster[slot].get('team', '')       # the host's team choice, not the friend's
                self.roster[slot] = {'name': m.get('name', '')[:NAME_MAX], 'colour': m.get('colour', ''),
                                     'team': team}
                changed = True
        if changed and self.mode == 'teams':
            self.fill_teams()
        if changed:
            self.broadcast_roster()

    def host_start(self):
        """Host: everyone is here with a name and a colour. Number the heroes by seat and
        tell each friend their number."""
        if not self.ready_to_start():
            return
        seats = self.seat_list()
        players = [{'name': e['name'], 'colour': self.colour_of(e), 'team': e.get('team', 'A')} for _, e in seats]
        self.seat_of = {slot: hero for hero, (slot, _) in enumerate(seats)}
        seed = random.randrange(1 << 30)
        self.peer.accepting = False             # no one new joins while the match is on
        for slot, _ in seats[1:]:
            self.peer.send_to(slot, {'t': 'start', 'seed': seed, 'difficulty': self.difficulty,
                                     'players': players, 'you': self.seat_of[slot], 'mode': self.mode})
        self.start_co_op(seed, self.difficulty, players, 0, self.mode)

    def menu_buttons(self):
        cx = WINDOW_WIDTH // 2
        sound = 'SOUND: OFF' if self.muted else 'SOUND: ON'
        if self.scene == 'title':
            mode = R.DIFFICULTY[self.difficulty]['name'].upper()
            buttons = [Button('PLAY', (cx - 140, 258, 280, 50), self.start_run, key_hint='Enter'),
                       Button('Play with a Friend', (cx - 150, 316, 300, 44), self.open_friends, key_hint='F'),
                       Button(f'MODE: {mode}', (cx - 140, 368, 280, 44), self.next_difficulty, key_hint='D')]
            buttons += [Button('HOW TO PLAY', (cx - 140, 418, 280, 40), lambda: setattr(self, 'scene', 'help'), key_hint='H'),
                        Button(sound, (cx - 140, 464, 280, 40), self.toggle_sound, key_hint='M')]
            return buttons
        if self.scene == 'friends' and self.touch:       # taller buttons for a finger, evenly spaced
            return [Button('HOST A GAME', (cx - 140, 240, 280, 50), self.host_game, enabled=IS_WEB, key_hint='H'),
                    Button('JOIN A GAME', (cx - 140, 300, 280, 50), self.join_game, enabled=IS_WEB, key_hint='J'),
                    Button('Multiplayer Rules', (cx - 150, 360, 300, 50),
                           lambda: setattr(self, 'scene', 'mp_rules'), key_hint='R'),
                    Button('BACK', (cx - 110, 420, 220, 50), self.back_to_title, key_hint='Esc')]
        if self.scene == 'friends':
            return [Button('HOST A GAME', (cx - 140, 250, 280, 50), self.host_game, enabled=IS_WEB, key_hint='H'),
                    Button('JOIN A GAME', (cx - 140, 312, 280, 50), self.join_game, enabled=IS_WEB, key_hint='J'),
                    Button('Multiplayer Rules', (cx - 190, 374, 380, 40),
                           lambda: setattr(self, 'scene', 'mp_rules'), key_hint='R'),
                    Button('BACK', (cx - 110, 430, 220, 46), self.back_to_title, key_hint='Esc')]
        if self.scene == 'mp_rules':
            y = 484 if self.touch else 470
            return [Button('BACK', (cx - 110, y, 220, 44), lambda: setattr(self, 'scene', 'friends'), key_hint='Esc')]
        if self.scene == 'invite':
            return [Button('BACK', (cx - 110, 462, 220, 46), self.back_to_title, key_hint='Esc')]
        if self.scene == 'join_code':
            return [Button('JOIN', (cx - 150, 404, 300, 50), self.spawn(self.join_room), key_hint='Enter',
                           enabled=len(self.code_text) == 4),
                    Button('BACK', (cx - 110, 462, 220, 46), self.back_to_title, key_hint='Esc')]
        if self.scene == 'lobby':
            label = {'coop': 'MODE: CO-OP', 'versus': 'MODE: VERSUS', 'teams': 'MODE: TEAMS'}[self.mode]
            buttons = [Button('BACK', (cx - 110, 498, 220, 36), self.back_to_title, key_hint='Esc'),
                       Button(label, (cx - 150, 312, 300, 30), self.toggle_mode, enabled=self.is_host)]
            if self.mode == 'teams':
                if self.is_host:
                    buttons.append(Button('PICK TEAM', (cx - 150, 348, 300, 30),
                                          lambda: setattr(self, 'scene', 'pick_team')))
                else:
                    buttons.append(Button('VIEW TEAMS', (cx - 150, 348, 300, 30),
                                          lambda: setattr(self, 'scene', 'view_teams')))
            if self.is_host:
                buttons.insert(0, Button('START GAME', (cx - 150, 418, 300, 40), self.host_start,
                                         enabled=self.ready_to_start(), key_hint='Enter'))
            return buttons
        if self.scene == 'pick_team':
            buttons = [Button(f'{self.seat_name(slot, e)}   Team {e.get("team") or "?"}', rect,
                              lambda s=slot: self.flip_team(s))
                       for slot, e, rect in self.team_rows()]
            return buttons + [Button('DONE', (cx - 110, 462, 220, 46), lambda: setattr(self, 'scene', 'lobby'),
                                     key_hint='Esc')]
        if self.scene == 'view_teams':
            return [Button('BACK', (cx - 110, 462, 220, 46), lambda: setattr(self, 'scene', 'lobby'), key_hint='Esc')]
        if self.scene == 'help':
            return [Button('BACK', (cx - 110, 462, 220, 50), lambda: setattr(self, 'scene', 'title'), key_hint='Esc')]
        if self.scene == 'paused':
            return [Button('RESUME', (cx - 130, 230, 260, 54), self.resume, key_hint='Esc'),
                    Button(sound, (cx - 130, 296, 260, 48), self.toggle_sound, key_hint='M'),
                    Button('QUIT RUN', (cx - 130, 356, 260, 48), self.quit_run)]
        if self.scene == 'over':
            if self.online and self.is_host:            # the host sends everyone back to the lobby
                return [Button('END GAME', (cx - 270, 440, 250, 56), self.return_to_lobby),
                        Button('PLAY AGAIN', (cx + 20, 440, 250, 56), self.return_to_lobby)]
            if self.online:
                return [Button('MAIN MENU', (cx - 125, 440, 250, 56), self.back_to_title)]
            return [Button('PLAY AGAIN', (cx - 270, 440, 250, 56), self.start_run, key_hint='Enter'),
                    Button('MAIN MENU', (cx + 20, 440, 250, 56), self.back_to_title)]
        return []

    def spawn(self, coroutine_function):
        """A button that starts a coroutine (the codes are copied with awaits)."""
        return lambda: asyncio.ensure_future(coroutine_function())

    def back_to_title(self):
        if self.peer:
            self.leave_co_op()
        self.connected_once = False
        self.invite_pending = False
        self.scene = 'title'
        self.note = ''

    def resume(self):
        self.scene = 'play'

    def quit_run(self):
        if self.online:
            self.leave_co_op()
            self.connected_once = False
        self.scene = 'title'
        self.rules = None

    def play_buttons(self):
        """On-screen buttons during a wave: pause, and for touch screens the actions."""
        buttons = [Button('II', (WINDOW_WIDTH - 52, 50, 40, 36), self.pause)]
        if self.touch and self.rules:
            hero = self.hero
            y = WINDOW_HEIGHT - 66
            buttons += [Button('RELOAD', (14, y, 104, 52), lambda: self.do('reload')),
                        Button('SWAP', (126, y, 90, 52), lambda: self.do('switch')),
                        Button(f'BLOCK {hero.barricades_held}', (224, y, 104, 52),
                               lambda: self.do('barricade'), enabled=hero.barricades_held > 0)]
            if self.rules.versus:                  # sabotage carried into the wave
                buttons += [Button(f'MINE {hero.stock["mine"]}', (336, y, 104, 52),
                                   lambda: self.do('mine'), enabled=hero.stock['mine'] > 0),
                            Button(f'AMBUSH {hero.stock["ambush"]}', (448, y, 112, 52),
                                   lambda: self.do('ambush'), enabled=hero.stock['ambush'] > 0)]
        return buttons

    def pause(self):
        if self.scene == 'play' and self.rules and self.rules.state not in ('won', 'lost') and not self.online:
            self.scene = 'paused'

    # ── input ───────────────────────────────────────────────────────
    def handle_event(self, event):
        if event.type in (pygame.MOUSEMOTION, pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP):
            self.mouse = event.pos
        if event.type == pygame.KEYDOWN and event.key == pygame.K_F3:
            self.show_timing = not self.show_timing
            return
        if self.scene != 'play':
            self.menu_event(event)
            return
        if self.rules.state == 'shop':
            self.shop_event(event)
            return
        if event.type == pygame.KEYDOWN:
            key = event.key
            if key in (pygame.K_ESCAPE, pygame.K_p):
                self.pause()
            elif key == pygame.K_r:
                self.do('reload')
            elif key in GUN_KEYS:
                self.do('switch', R.GUN_ORDER[GUN_KEYS[key]])
            elif key in (pygame.K_q, pygame.K_TAB):
                self.do('switch')
            elif key in (pygame.K_f, pygame.K_e):
                self.do('barricade', self.world(self.mouse) if not self.touch else None)
            elif key == pygame.K_x:
                self.do('mine')                 # versus: lay a carried landmine
            elif key == pygame.K_v:
                self.do('ambush')               # versus: send a carried ambush
            elif key == pygame.K_m:
                self.toggle_sound()
        elif event.type == pygame.MOUSEWHEEL:
            self.do('switch', None, -1 if event.y > 0 else 1)
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button in (1, 3):
            for button in self.play_buttons():
                if button.enabled and button.rect.collidepoint(event.pos):
                    button.action()
                    return
            if event.button == 3:
                self.do('barricade', self.world(event.pos))
            elif self.touch:
                self.press = (self.time, vector(event.pos), False)
            else:
                self.do('shoot', self.world(event.pos))
        elif event.type == pygame.MOUSEBUTTONUP and event.button == 1 and self.press:
            walking = self.press[2]
            self.press = None
            if not walking:                     # a quick tap shoots at that spot
                self.do('shoot', self.world(event.pos))

    def set_name(self, name):
        self.my_name = name[:NAME_MAX]
        storage.save('name', self.my_name)
        self.send_identity()

    def menu_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.scene == 'lobby' and self.mode != 'teams':
                for colour, rect in self.swatch_rects():
                    if rect.collidepoint(event.pos):
                        self.play('switch')
                        self.choose_colour(colour)
                        return
            for button in self.menu_buttons():
                if button.enabled and button.rect.collidepoint(event.pos):
                    self.play('switch')
                    button.action()
                    return
        if event.type != pygame.KEYDOWN:
            return
        key = event.key
        if self.scene == 'title':
            if key in (pygame.K_RETURN, pygame.K_SPACE, pygame.K_KP_ENTER):
                self.start_run()
            elif key == pygame.K_h:
                self.scene = 'help'
            elif key == pygame.K_d:
                self.next_difficulty()
            elif key == pygame.K_f:
                self.open_friends()
            elif key == pygame.K_m:
                self.toggle_sound()
        elif self.scene == 'mp_rules':
            if key in (pygame.K_ESCAPE, pygame.K_RETURN, pygame.K_SPACE):
                self.scene = 'friends'
        elif self.scene == 'friends':
            if key == pygame.K_r:
                self.scene = 'mp_rules'
            elif key == pygame.K_ESCAPE:
                self.back_to_title()
            elif key == pygame.K_h and IS_WEB:
                self.host_game()
            elif key == pygame.K_j and IS_WEB:
                self.join_game()
        elif self.scene == 'invite':
            if key == pygame.K_ESCAPE:
                self.back_to_title()
        elif self.scene == 'join_code':
            if key == pygame.K_ESCAPE:
                self.back_to_title()
            elif key in (pygame.K_RETURN, pygame.K_KP_ENTER) and len(self.code_text) == 4:
                asyncio.ensure_future(self.join_room())
            elif key == pygame.K_BACKSPACE:
                self.code_text = self.code_text[:-1]
            elif event.unicode.isdigit() and len(event.unicode) == 1 and len(self.code_text) < 4:
                self.code_text += event.unicode
        elif self.scene in ('pick_team', 'view_teams'):
            if key == pygame.K_ESCAPE:
                self.scene = 'lobby'
        elif self.scene == 'lobby':
            if key == pygame.K_ESCAPE:
                self.back_to_title()
            elif key in (pygame.K_RETURN, pygame.K_KP_ENTER) and self.is_host:
                self.host_start()
            elif key == pygame.K_BACKSPACE:
                self.set_name(self.my_name[:-1])
            elif event.unicode and (event.unicode.isalnum() or event.unicode in ' _-') and len(event.unicode) == 1:
                self.set_name(self.my_name + event.unicode)
        elif self.scene == 'help' and key in (pygame.K_ESCAPE, pygame.K_RETURN, pygame.K_h, pygame.K_SPACE):
            self.scene = 'title'
        elif self.scene == 'paused':
            if key in (pygame.K_ESCAPE, pygame.K_p, pygame.K_RETURN):
                self.resume()
            elif key == pygame.K_m:
                self.toggle_sound()
        elif self.scene == 'over' and key in (pygame.K_RETURN, pygame.K_SPACE, pygame.K_KP_ENTER) and not self.online:
            self.start_run()

    # ── the shop ────────────────────────────────────────────────────
    def sabotage_tab(self):
        return self.rules is not None and self.rules.versus and self.shop_tab == 'sabotage'

    def shop_tab_rects(self):
        cx = WINDOW_WIDTH // 2
        y, h = (86, 30) if self.touch else (79, 24)      # taller tabs for a finger
        return [('supply', pygame.Rect(cx - 160, y, 150, h)), ('sabotage', pygame.Rect(cx + 10, y, 150, h))]

    def shop_cards(self):
        # On a phone the cards are a little shorter and start lower, so the tabs fit above them.
        w, h, gap = 286, (92 if self.touch else 98), (8 if self.touch else 12)
        top = 124 if self.touch else 104
        left = (WINDOW_WIDTH - (3 * w + 2 * gap)) // 2
        cards = []
        order = R.SABOTAGE_ORDER if self.sabotage_tab() else R.SHOP_ORDER
        for i, item in enumerate(order):
            col, row = i % 3, i // 3
            cards.append((item, pygame.Rect(left + col * (w + gap), top + row * (h + gap), w, h)))
        return cards

    def shop_toggle_shown(self):
        """Phones have no B key: a button in a friend game opens and closes the shop panel."""
        return bool(self.touch and self.online and self.scene == 'play' and self.rules
                    and self.rules.state == 'shop')

    def shop_toggle_button(self):
        label = 'CLOSE' if self.shop_open else 'SHOP'
        return Button(label, (WINDOW_WIDTH - 52 - 8 - 120, 56, 120, 36), self.toggle_shop)

    def toggle_shop(self):
        self.shop_open = not self.shop_open

    def start_button(self):
        r, me = self.rules, self.hero
        if self.online:
            if me.ready:
                label = 'WAITING FOR YOUR FRIEND'
            else:
                label = 'READY' if r.wave + 1 < R.WAVES else 'READY FOR THE BOSS'
        else:
            label = 'FACE THE BOSS' if r.wave + 1 == R.WAVES else f'START WAVE {r.wave + 1}'
        enabled = not me.ready
        return Button(label, (WINDOW_WIDTH // 2 - 170, WINDOW_HEIGHT - 72, 340, 56),
                      self.start_next_wave, enabled=enabled, key_hint='Enter' if enabled else '')

    def shop_ready_button(self):
        """The READY button during a break with the shop closed."""
        me = self.hero
        label = 'WAITING FOR YOUR FRIEND' if me.ready else 'READY'
        return Button(label, (WINDOW_WIDTH // 2 - 170, WINDOW_HEIGHT - 150, 340, 52),
                      self.start_next_wave, enabled=not me.ready, key_hint='Enter' if not me.ready else '')

    def start_next_wave(self):
        if self.do('start_wave'):
            self.shop_note = ''
            if not self.online:
                self.play('wave_start')

    def shop_event(self, event):
        versus = self.rules.versus
        if event.type == pygame.MOUSEBUTTONUP:
            self.press = None                           # a finger lifted: stop walking
        if self.online and event.type == pygame.KEYDOWN and event.key == pygame.K_b:
            self.shop_open = not self.shop_open         # walk about with the shop closed, or open it
            return
        if self.shop_toggle_shown() and event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 \
                and self.shop_toggle_button().rect.collidepoint(event.pos):
            self.toggle_shop()
            return
        if self.online and not self.shop_open:          # closed: only READY and walking
            if event.type == pygame.KEYDOWN and event.key in (pygame.K_RETURN, pygame.K_SPACE, pygame.K_KP_ENTER):
                self.start_next_wave()
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                ready = self.shop_ready_button()
                if ready.enabled and ready.rect.collidepoint(event.pos):
                    self.start_next_wave()
                elif self.touch:                        # a finger on the floor walks toward itself
                    self.press = (self.time, vector(event.pos), False)
            return
        if event.type == pygame.KEYDOWN:
            if event.key in (pygame.K_RETURN, pygame.K_SPACE, pygame.K_KP_ENTER):
                self.start_next_wave()
            elif event.key == pygame.K_m:
                self.toggle_sound()
            elif event.key == pygame.K_t and versus:
                self.shop_tab = 'sabotage' if self.shop_tab == 'supply' else 'supply'
            elif pygame.K_1 <= event.key <= pygame.K_9:
                cards = self.shop_cards()
                index = event.key - pygame.K_1
                if index < len(cards):
                    self.try_buy(cards[index][0])
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.start_button().rect.collidepoint(event.pos) and self.start_button().enabled:
                self.start_next_wave()
                return
            if versus:
                for tab, rect in self.shop_tab_rects():
                    if rect.collidepoint(event.pos):
                        self.shop_tab = tab
                        return
            for item, rect in self.shop_cards():
                if rect.collidepoint(event.pos):
                    self.try_buy(item)

    def try_buy(self, item):
        if self.sabotage_tab():
            offer = self.rules.sabotage_offer(self.hero, item)
            if offer['ok']:
                self.do('sabotage', item)
                self.shop_note = f'Bought: {offer["name"]} (aimed at your rival)'
            else:
                self.shop_note = offer['why']
                self.play('deny')
            return
        offer = self.rules.shop_offer(self.hero, item)
        if offer['ok']:
            self.do('buy', item)
            self.shop_note = f'Bought: {offer["name"]}'
        else:
            self.shop_note = offer['why']
            self.play('deny')

    # ── a frame ─────────────────────────────────────────────────────
    def read_keys(self):
        keys = pygame.key.get_pressed()
        return vector(int(keys[pygame.K_d] or keys[pygame.K_RIGHT]) - int(keys[pygame.K_a] or keys[pygame.K_LEFT]),
                      int(keys[pygame.K_s] or keys[pygame.K_DOWN]) - int(keys[pygame.K_w] or keys[pygame.K_UP]))

    def my_input(self):
        """(steering, aim) for my hero this frame."""
        move = self.read_keys()
        aim = None if self.touch else self.world(pygame.mouse.get_pos())
        if self.press:                          # touch: a held or dragged finger walks toward itself
            start, spot, walking = self.press
            here = vector(pygame.mouse.get_pos())
            if walking or self.time - start > 0.2 or here.distance_to(spot) > 24:
                self.press = (start, spot, True)
                target = self.world(here)
                if target.distance_to(self.hero.pos) > 12:
                    move = target - self.hero.pos
                    aim = target
        return move, aim

    def update(self, dt):
        self.time += dt
        self.update_effects(dt)
        if self.peer:
            self.check_link()
        if self.scene != 'play' or not self.rules:
            return
        started = time.perf_counter()
        if self.online and not self.is_host:
            self.friend_frame(dt)
        else:
            self.host_frame(dt)
        started = self.timed('update', started)
        if self.scene != 'play' or not self.rules:      # the frame may have left the match (host ended it)
            return
        r = self.rules
        if r.state in ('won', 'lost'):
            self.end_timer += dt
            if self.end_timer > (3.0 if r.state == 'won' else 2.2):
                self.finish_run()

    def host_frame(self, dt):
        """The machine that runs the rules: solo, or the host in co-op."""
        r = self.rules
        move, aim = self.my_input()
        r.set_input(self.me, move, aim)
        if self.online:
            for slot, m in self.peer.poll():
                hero = self.seat_of.get(slot)
                if hero is None:
                    continue
                if m.get('t') == 'in':
                    r.set_input(hero, m['m'], m['a'])
                elif m.get('t') == 'act':
                    r.act(m['a'][0], *m['a'][1:], who=hero)
                elif m.get('t') == 'left':
                    r.heroes[hero].gone = True
                    r.heroes[hero].hearts = 0
                    r.heroes[hero].revive = 0.0
                    self.pending.append(('down', hero, r.heroes[hero].pos.copy()))
        r.step(dt)
        if self.online:
            self.pending.extend(r.events)
            self.send_clock += dt
            if self.send_clock >= SEND_EVERY:
                self.send_clock = 0.0
                self.peer.send_all({'t': 'snap', 's': r.snapshot()})
                if self.pending:
                    self.peer.send_all({'t': 'ev', 'ev': [R.wire(e) for e in self.pending]})
                    self.pending = []
        self.consume_events()

    def friend_frame(self, dt):
        """A friend's machine: move my own hero at once, draw the host's picture."""
        r, me = self.rules, self.hero
        for _, m in self.peer.poll():
            if m.get('t') == 'snap':
                r.apply_snapshot(m['s'], mine=self.me)
            elif m.get('t') == 'ev':
                r.events.extend(R.unwire(e) for e in m['ev'])
            elif m.get('t') == 'lobby':
                self.enter_lobby()
                return
            elif m.get('t') == 'left':
                self.back_to_title()
                self.note = 'The host left the game.'
                return
        for z in r.zombies:                     # the host's picture comes in 15 times a second:
            z.pos += (z.target - z.pos) * min(1.0, dt * 12)     # glide between updates, no jumps
        for other in r.heroes:
            if other is not me:
                other.pos += (other.target - other.pos) * min(1.0, dt * 12)
        move, aim = self.my_input()
        me.move = vector(move)
        if aim is not None:
            me.aim = vector(aim)
        if r.state in R.FIGHTING or r.state == 'shop':
            r.move_player(me, dt)               # predicted: no waiting for the network
        gap = me.host_pos - me.pos              # then ease toward where the host has me
        if gap.length() > 60:
            me.pos = vector(me.host_pos)
        else:
            me.pos += gap * min(1.0, dt * 6)
        self.send_clock += dt
        current = (round(me.move.x, 1), round(me.move.y, 1))
        if self.send_clock >= SEND_EVERY or current != self.last_move:
            self.send_clock = 0.0
            self.last_move = current
            self.peer.send({'t': 'in', 'm': [me.move.x, me.move.y], 'a': [me.aim.x, me.aim.y]})
        self.consume_events()

    def update_effects(self, dt):
        for p in self.particles:
            p[0] += p[1] * dt
            p[1] *= max(0.0, 1 - 5 * dt)
            p[2] -= dt
        self.particles = [p for p in self.particles if p[2] > 0]
        for f in self.floaters:
            f[2].y -= 40 * dt
            f[3] -= dt
        self.floaters = [f for f in self.floaters if f[3] > 0]
        self.shake = max(0.0, self.shake - 30 * dt)
        self.hurt_flash = max(0.0, self.hurt_flash - dt)
        for key in list(self.muzzle):
            self.muzzle[key] = max(0.0, self.muzzle[key] - dt)
        if self.banner:
            title, sub, left, total = self.banner
            self.banner = (title, sub, left - dt, total) if left - dt > 0 else None

    def consume_events(self):
        r = self.rules
        if not r:
            return
        for event in r.events:
            kind = event[0]
            if kind == 'shot':
                self.play(event[1])
                self.muzzle[event[2]] = 0.06
                if event[2] == self.me:
                    self.shake = max(self.shake, SHAKE[event[1]])
            elif kind == 'empty':
                self.play('empty')
            elif kind == 'no_ammo':
                self.floater('Out of ammo!', RED, r.heroes[event[1]].pos + (0, -40))
            elif kind == 'reload':
                self.play('reload')
            elif kind == 'switch':
                self.play('switch')
            elif kind == 'hit':
                self.play('hit')
                self.burst(event[1], BLOOD[event[2]], 5, 140, 3, 0.35)
            elif kind == 'kill':
                pos, zkind = event[1], event[2]
                self.play('roar' if zkind == 'boss' else 'die')
                self.splat(self.dirty, pos, BLOOD[zkind], 34 if zkind == 'boss' else (18 if zkind == 'brute' else 12))
                self.burst(pos, BLOOD[zkind], 26 if zkind == 'boss' else 12, 220, 4, 0.6)
                if zkind == 'boss':
                    self.shake = 18
            elif kind == 'impact':
                self.burst(event[1], (200, 190, 160), 3, 90, 2, 0.2)
            elif kind == 'hurt':
                self.play('hurt')
                if event[2] == self.me:
                    self.shake = max(self.shake, 9)
                    self.hurt_flash = 0.35
            elif kind == 'down':
                self.play('thud')
                self.floater('DOWN!', RED, event[2] + (0, -30))
            elif kind == 'revived':
                self.play('heart')
                self.floater('BACK UP!', GREEN, event[2] + (0, -30))
            elif kind == 'coin':
                self.play('coin')
                self.floater(f'+{event[1]}', GOLD, event[3] + (random.uniform(-10, 10), -34))
            elif kind == 'ammo':
                self.play('ammo')
                self.floater('AMMO', GREEN, event[2] + (0, -40))
            elif kind == 'heart':
                self.play('heart')
                self.floater('+1 HEART', RED, event[2] + (0, -40))
            elif kind == 'wave_ready':
                wave = event[1]
                if wave == R.WAVES:
                    self.banner = ('THE ABOMINATION', 'Final wave. Kill it to save the town.', 2.6, 2.6)
                else:
                    self.banner = (f'WAVE {wave}', 'Get ready...', 2.4, 2.4)
            elif kind == 'shop':
                self.shop_open = not self.online      # with a friend, the shop starts closed
            elif kind == 'wave_clear':
                self.play('wave_clear')
                self.banner = ('WAVE CLEARED', 'Grabbing the loot...', 2.0, 2.0)
            elif kind == 'buy':
                self.play('buy')
            elif kind == 'spit':
                self.play('spit')
            elif kind == 'splash':
                self.play('splat')
                self.burst(event[1], (150, 230, 60), 7, 110, 3, 0.35)
            elif kind == 'barricade_hit':
                self.play('wood')
                self.burst(event[1], (150, 104, 58), 4, 90, 3, 0.3)
            elif kind == 'barricade_break':
                self.play('wood')
                self.burst(event[1], (150, 104, 58), 18, 200, 4, 0.6)
            elif kind == 'placed':
                self.play('wood')
            elif kind == 'cant_place':
                self.play('deny')
                self.floater("Can't place there", DIM, r.heroes[event[1]].pos + (0, -40))
            elif kind == 'boss_arrives':
                self.play('roar')
                self.shake = 10
            elif kind == 'boss_windup':
                self.play('roar')
            elif kind == 'boss_charge':
                self.shake = max(self.shake, 6)
            elif kind == 'boss_stun':
                self.play('thud')
                self.shake = 14
                self.burst(event[1], (200, 190, 160), 14, 200, 4, 0.5)
            elif kind == 'boss_summon':
                self.burst(event[1], (120, 40, 90), 16, 180, 4, 0.5)
            elif kind == 'mine_blast':
                self.play('thud')
                self.burst(event[1], (200, 60, 50), 14, 180, 4, 0.5)
            elif kind == 'mine_laid':
                self.play('switch')
            elif kind == 'ambush':
                self.play('roar')
                self.burst(event[2], BLOOD['walker'], 18, 200, 4, 0.5)
            elif kind == 'sabotage':
                self.play('buy')
            elif kind == 'lost':
                self.play('gameover')
            elif kind == 'won':
                self.play('victory')
                self.banner = ('THE TOWN IS SAFE', 'You beat the Abomination!', 3.0, 3.0)
        r.events.clear()

    def timed(self, part, started):
        took = (time.perf_counter() - started) * 1000
        self.timings[part] = self.timings.get(part, took) * 0.95 + took * 0.05
        return time.perf_counter()

    # ── drawing ─────────────────────────────────────────────────────
    def draw(self):
        if self.scene in ('play', 'paused') or (self.scene == 'over' and self.rules):
            started = time.perf_counter()
            self.draw_world()
            started = self.timed('world', started)
            if self.rules.state == 'shop' and self.scene == 'play' and (self.shop_open or not self.online):
                self.draw_shop()
            else:
                self.draw_hud()
                if self.rules.state == 'shop' and self.online:
                    hint = ('Walk about while you wait. Tap SHOP to open the shop.' if self.touch
                            else 'Walk about while you wait. Press B to open the shop.')
                    self.text(hint, 24, GOLD, (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 - 90), 'center')
                    self.shop_ready_button().draw(self.screen, self.fonts[34], self.mouse,
                                                  self.fonts[20] if not self.touch else None)
            if self.shop_toggle_shown():
                self.shop_toggle_button().draw(self.screen, self.fonts[24], self.mouse)
            self.timed('hud', started)
        else:
            self.draw_backdrop()
        if self.scene == 'title':
            self.draw_title()
        elif self.scene == 'help':
            self.draw_help()
        elif self.scene == 'friends':
            self.draw_friends()
        elif self.scene == 'mp_rules':
            self.draw_mp_rules()
        elif self.scene == 'invite':
            self.draw_invite()
        elif self.scene == 'join_code':
            self.draw_join_code()
        elif self.scene == 'lobby':
            self.draw_lobby()
        elif self.scene == 'pick_team':
            self.draw_pick_team()
        elif self.scene == 'view_teams':
            self.draw_view_teams()
        elif self.scene == 'paused':
            self.draw_paused()
        elif self.scene == 'over':
            self.draw_over()
        if self.scene == 'play' and self.rules.state in R.FIGHTING and not self.touch:
            self.draw_crosshair()
            pygame.mouse.set_visible(False)
        else:
            pygame.mouse.set_visible(True)
        if self.room_code and self.scene in ('lobby', 'play', 'paused', 'over'):
            self.text(f'ROOM {self.room_code}', 24, GOLD, (16, 40), shadow=True)

    def draw_backdrop(self):
        t = self.time * 0.08
        x = -(R.MAP_W - WINDOW_WIDTH) / 2 + math.sin(t) * 380
        y = -(R.MAP_H - WINDOW_HEIGHT) / 2 + math.cos(t * 0.7) * 200
        self.screen.blit(self.ground, (x, y))
        self.dim()

    def draw_world(self):
        r = self.rules
        screen = self.screen
        me = self.hero
        off = vector(WINDOW_WIDTH / 2 - me.pos.x, WINDOW_HEIGHT / 2 - me.pos.y)
        off.x = max(-(R.MAP_W - WINDOW_WIDTH), min(0, off.x))
        off.y = max(-(R.MAP_H - WINDOW_HEIGHT), min(0, off.y))
        self.offset = vector(off)
        if self.shake and self.scene == 'play':
            off += (random.uniform(-self.shake, self.shake), random.uniform(-self.shake, self.shake))
        screen.blit(self.dirty, off)

        for item in r.pickups:
            if item.life < 3 and int(self.time * 8) % 2:
                continue
            image = self.items[item.kind]
            bob = math.sin(self.time * 5 + item.id) * 2
            screen.blit(image, image.get_rect(center=item.pos + off + (0, bob)))
        for mine in r.mines:
            if mine.owner == self.me:           # hidden from the rival: only the layer sees it
                spot = mine.pos + off
                pygame.draw.circle(screen, (60, 40, 30), spot, 9, 2)
                pygame.draw.circle(screen, RED, spot, 3)
        for bar in r.barricades:
            image = self.items['barricade']
            spot = bar.centre + off
            screen.blit(image, image.get_rect(center=spot))
            if bar.hp < bar.max_hp:
                width = 44 * bar.hp / bar.max_hp
                pygame.draw.rect(screen, (30, 20, 16), (spot.x - 23, spot.y - 34, 46, 6))
                pygame.draw.rect(screen, (220, 160, 80), (spot.x - 22, spot.y - 33, width, 4))

        crowd = [(z.pos.y, z) for z in r.zombies]
        crowd += [(h.pos.y, h) for h in r.heroes]
        crowd.sort(key=lambda pair: pair[0])
        for _, thing in crowd:
            if isinstance(thing, R.Hero):
                self.draw_player(thing, off)
            else:
                self.draw_zombie(thing, off)

        for s in r.spits:
            pygame.draw.circle(screen, (60, 110, 20), s.pos + off, 7)
            pygame.draw.circle(screen, (170, 240, 70), s.pos + off, 5)
        for b in r.bullets:
            tail = b.pos - b.vel.normalize() * (22 if b.kind == 'rifle' else 12)
            pygame.draw.line(screen, (255, 230, 150), tail + off, b.pos + off, 3 if b.kind == 'rifle' else 2)
        for p in self.particles:
            size = max(1, round(p[5] * p[2] / p[3]))
            pygame.draw.rect(screen, p[4], (p[0].x + off.x - size / 2, p[0].y + off.y - size / 2, size, size))
        for text, colour, pos, life in self.floaters:
            self.text(text, 24, colour, pos + off, 'center')
        if self.hurt_flash > 0:
            width = round(4 + 14 * self.hurt_flash / 0.35)      # a red edge: cheap in the browser
            pygame.draw.rect(screen, (200, 30, 30), screen.get_rect(), width)

    def draw_player(self, hero, off):
        r = self.rules
        screen = self.screen
        pos = hero.pos
        aim = hero.aim - pos
        if aim.length_squared() < 1:
            aim = vector(0, 1)
        facing = facing_of(aim)
        moving = hero.moving and not hero.down
        state = f"{'walk' if moving else 'idle'}_{facing}"
        frames = self.frames['player'][state]
        image = frames[int(self.time * (9 if moving else 3)) % len(frames)]
        if hero.down:
            image = self.tint(image, (90, 40, 40))
        screen.blit(self.shadows[30], self.shadows[30].get_rect(center=pos + off + (0, 15)))
        hand = pos + off + (0, -2)
        tip = hand + aim.normalize() * GUN_LENGTH[hero.gun.kind]

        def gun():
            if hero.down:
                return
            pygame.draw.line(screen, (20, 20, 24), hand, tip, 7)
            pygame.draw.line(screen, (90, 92, 100), hand, tip, 3)
            if self.muzzle.get(hero.pid, 0) > 0:
                pygame.draw.circle(screen, (255, 210, 90), tip, 8)
                pygame.draw.circle(screen, (255, 250, 210), tip, 4)

        if facing == 'up':
            gun()
        rect = image.get_rect(midbottom=pos + off + (0, R.PLAYER_RADIUS + 4))
        if hero.safe > 0 and int(self.time * 14) % 2:
            screen.blit(self.tint(image, (255, 255, 255)), rect)
        else:
            screen.blit(image, rect)
        if facing != 'up':
            gun()
        if len(r.heroes) > 1:                   # who is who: a coloured arrow and their name
            tag = self.player_rgb(hero.pid)
            tip_y = rect.top - 4
            arrow = [(rect.centerx - 9, tip_y - 14), (rect.centerx + 9, tip_y - 14), (rect.centerx, tip_y)]
            pygame.draw.polygon(screen, tag, arrow)
            pygame.draw.polygon(screen, (10, 10, 10), arrow, 2)
            self.text(self.player_name(hero.pid), 20, tag, (rect.centerx, tip_y - 16), 'midbottom')
        if hero.down:
            if hero.revive > 0:                 # a friend is reviving them
                share = min(1.0, hero.revive / R.REVIVE_TIME)
                bar = pygame.Rect(0, 0, 60, 7)
                bar.midbottom = (rect.centerx, rect.top - 4)
                pygame.draw.rect(screen, (20, 20, 20), bar.inflate(2, 2))
                pygame.draw.rect(screen, GREEN, (bar.x, bar.y, bar.width * share, bar.height))
            else:
                self.text('DOWN', 20, RED, (rect.centerx, rect.top - 6), 'midbottom')
            return
        gun_now = hero.gun
        if gun_now.reloading > 0:
            share = 1 - gun_now.reloading / hero.reload_time(gun_now.kind)
            bar = pygame.Rect(0, 0, 40, 6)
            bar.midbottom = rect.midtop + vector(0, -2)
            pygame.draw.rect(screen, (20, 20, 20), bar.inflate(2, 2))
            pygame.draw.rect(screen, GOLD, (bar.x, bar.y, bar.width * share, bar.height))

    def draw_zombie(self, z, off):
        screen = self.screen
        moving = z.vel.length_squared() > 1
        facing = facing_of(z.vel) if moving else facing_of(self.rules.nearest_hero(z.pos).pos - z.pos)
        frames = self.frames[z.kind][f"{'walk' if moving else 'idle'}_{facing}"]
        speed = {'runner': 12, 'boss': 5, 'brute': 5}.get(z.kind, 7)
        image = frames[int(self.time * speed + z.id * 0.37) % len(frames)]
        shadow = self.shadows[64 if z.kind == 'boss' else (40 if z.kind == 'brute' else 30)]
        screen.blit(shadow, shadow.get_rect(center=z.pos + off + (0, z.radius)))
        rect = image.get_rect(midbottom=z.pos + off + (0, z.radius + 4))
        if z.flash > 0:
            image = self.tint(image, (255, 255, 255))
        elif z.kind == 'boss' and z.mode == 'windup' and int(self.time * 16) % 2:
            image = self.tint(image, (255, 90, 80))
        screen.blit(image, rect)
        if z.kind == 'spitter' and z.winding:
            pygame.draw.circle(screen, (170, 240, 70), rect.center + vector(0, -8), 6 + int(self.time * 20) % 3, 2)
        if z.kind == 'boss' and z.mode == 'stunned':
            for i in range(3):
                angle = self.time * 6 + i * 2.1
                star = vector(rect.centerx, rect.top + 4) + vector(math.cos(angle) * 22, math.sin(angle) * 6)
                pygame.draw.circle(screen, GOLD, star, 4)
        if z.kind == 'brute' and z.hp < z.max_hp:
            bar = pygame.Rect(0, 0, 34, 5)
            bar.midbottom = (rect.centerx, rect.top + 4)
            pygame.draw.rect(screen, (20, 20, 20), bar.inflate(2, 2))
            pygame.draw.rect(screen, RED, (bar.x, bar.y, bar.width * z.hp / z.max_hp, bar.height))

    def draw_crosshair(self):
        x, y = self.mouse
        screen = self.screen
        colour = (255, 255, 255)
        gun = self.hero.gun
        if gun.mag == 0 and gun.reloading == 0:
            colour = RED
        pygame.draw.circle(screen, (0, 0, 0), (x, y), 11, 3)
        pygame.draw.circle(screen, colour, (x, y), 10, 1)
        for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            pygame.draw.line(screen, colour, (x + dx * 5, y + dy * 5), (x + dx * 15, y + dy * 15), 2)
        if gun.reloading > 0:
            share = 1 - gun.reloading / self.hero.reload_time(gun.kind)
            pygame.draw.arc(screen, GOLD, (x - 16, y - 16, 32, 32), math.pi / 2, math.pi / 2 + share * 2 * math.pi, 3)

    def draw_hud(self):
        r, me = self.rules, self.hero
        screen = self.screen
        self.draw_hearts(16, 14, me)
        self.text(f'WAVE {r.wave} / {R.WAVES}', 34, INK, (WINDOW_WIDTH // 2, 10), 'midtop')
        if r.state in ('ready', 'wave'):
            left = r.zombies_left
            self.text(f'{left} zombie{"s" if left != 1 else ""} left', 24, DIM, (WINDOW_WIDTH // 2, 40), 'midtop')
        coin = self.items['coin']
        rect = self.text(str(me.coins), 34, GOLD, (WINDOW_WIDTH - 16, 12), 'topright')
        screen.blit(coin, coin.get_rect(midright=(rect.left - 6, rect.centery - 1)))
        if self.online:                         # everyone in the match, along the bottom
            if r.teamed:                        # teams: each side with its kill count, in its colour
                totals = dict(r.team_totals())
                entries = [(f'Team {team}  {totals[team][0]} kills', COLOUR_RGB[TEAM_COLOURS[team]])
                           for team in ('A', 'B')]
                self.draw_team_row(WINDOW_HEIGHT - 22, entries=entries)
            elif r.versus:                      # versus: each name with its kill count
                entries = [(f'{self.player_name(h.pid)}  {h.kills} kills', self.player_rgb(h.pid)) for h in r.heroes]
                self.draw_team_row(WINDOW_HEIGHT - 22, entries=entries)
            else:
                self.draw_team_row(WINDOW_HEIGHT - 22)
        if r.teamed:                                                 # teams: each side's score
            totals = '   '.join(f'Team {team}: {kills} kills' for team, (kills, _) in r.team_totals())
            self.text(totals, 20, GOLD, (16, 62), shadow=True)
        if r.versus and r.state in R.FIGHTING and not self.touch:     # phones have the buttons instead
            self.text(f'Mines {me.stock["mine"]} [X]   Ambush {me.stock["ambush"]} [V]', 20, (220, 170, 110),
                      (16, WINDOW_HEIGHT - 54))

        panel = pygame.Rect(WINDOW_WIDTH - 316, WINDOW_HEIGHT - 92, 302, 78)
        self.panel(panel)
        for i, kind in enumerate(R.GUN_ORDER):         # every gun, the ones you own lit up
            label = f'{i + 1} {R.WEAPONS[kind]["name"]}'
            colour = GOLD if kind == me.current else (DIM if kind in me.guns else (70, 74, 70))
            self.text(label, 20, colour, (panel.x + 10 + i * 73, panel.y + 9), shadow=False)
            if kind == me.current:
                width = self.fonts[20].size(label)[0]
                pygame.draw.line(screen, GOLD, (panel.x + 10 + i * 73, panel.y + 25), (panel.x + 10 + i * 73 + width, panel.y + 25), 2)
        gun = me.gun
        cap = me.mag_size(gun.kind)
        colour = RED if gun.mag == 0 else INK
        rect = self.text(f'{gun.mag}/{cap}', 44, colour, (panel.x + 12, panel.y + 32), shadow=False)
        spare = 'unlimited' if gun.reserve is None else f'+{gun.reserve} spare'
        self.text(spare, 24, DIM if gun.reserve != 0 else RED, (rect.right + 10, panel.y + 46), shadow=False)
        if gun.reloading > 0:
            share = 1 - gun.reloading / me.reload_time(gun.kind)
            pygame.draw.rect(screen, (40, 40, 30), (panel.x + 12, panel.bottom - 8, panel.width - 24, 4))
            pygame.draw.rect(screen, GOLD, (panel.x + 12, panel.bottom - 8, (panel.width - 24) * share, 4))
        elif gun.mag == 0 and r.state in R.FIGHTING and not me.down:
            if gun.reserve == 0:
                hint = 'Out of ammo: press 1' if not self.touch else 'Out of ammo: SWAP'
            else:
                hint = 'Press R to reload' if not self.touch else 'Tap RELOAD'
            if int(self.time * 3) % 2:
                self.text(hint, 28, RED, (WINDOW_WIDTH // 2, WINDOW_HEIGHT - 130), 'center')
        if me.down and r.state in R.FIGHTING:
            if r.teamed:
                message = 'YOU ARE DOWN. Your teammate can bring you back: stand beside them.'
            elif r.versus:
                message = 'YOU ARE DOWN. No revives in versus: you are back at the shop.'
            elif self.online:
                message = 'YOU ARE DOWN. Your friend can bring you back: stand beside them.'
            else:
                message = 'DOWN'
            self.text(message, 28, RED, (WINDOW_WIDTH // 2, WINDOW_HEIGHT - 170), 'center')
        if me.barricades_held and not self.touch:
            self.text(f'Barricades: {me.barricades_held}  (F / right-click)', 24, (220, 170, 110),
                      (16, WINDOW_HEIGHT - 32))

        boss = r.boss
        if boss:
            bar = pygame.Rect(WINDOW_WIDTH // 2 - 220, 66, 440, 16)
            pygame.draw.rect(screen, (20, 10, 16), bar.inflate(4, 4), border_radius=4)
            pygame.draw.rect(screen, (170, 40, 90), (bar.x, bar.y, bar.width * max(0, boss.hp) / boss.max_hp, bar.height), border_radius=4)
            self.text('THE ABOMINATION', 20, INK, bar.center, 'center')
            if boss.mode == 'stunned':
                self.text('STUNNED: double damage!', 24, GOLD, (WINDOW_WIDTH // 2, 92), 'midtop')

        if self.banner:
            title, sub, left, total = self.banner
            fade = min(1.0, left / 0.4, (total - left) / 0.25 + 0.2)
            big = self.fonts[64].render(title, True, GREEN if 'CLEARED' in title or 'SAFE' in title else INK)
            big.set_alpha(int(255 * fade))
            screen.blit(big, big.get_rect(center=(WINDOW_WIDTH // 2, 170)))
            small = self.fonts[28].render(sub, True, DIM)
            small.set_alpha(int(255 * fade))
            screen.blit(small, small.get_rect(center=(WINDOW_WIDTH // 2, 214)))

        for button in self.play_buttons():
            button.draw(screen, self.fonts[24], self.mouse)

    def draw_shop(self):
        r, me = self.rules, self.hero
        screen = self.screen
        self.dim()
        if r.versus:
            for tab, rect in self.shop_tab_rects():
                chosen = tab == self.shop_tab
                pygame.draw.rect(screen, (60, 80, 50) if chosen else (24, 32, 24), rect, border_radius=8)
                pygame.draw.rect(screen, GREEN if chosen else EDGE, rect, 2, border_radius=8)
                self.text('SUPPLY' if tab == 'supply' else 'SABOTAGE', 24 if self.touch else 20, INK, rect.center,
                          'center', shadow=False)
        self.text('SUPPLY SHOP', 64, GREEN, (WINDOW_WIDTH // 2, 14), 'midtop')
        nxt = r.wave + 1
        sub = f'Wave {r.wave} survived. ' + ('Next: THE ABOMINATION.' if nxt == R.WAVES else f'Next: wave {nxt} of {R.WAVES}.')
        self.text(sub, 24, DIM, (WINDOW_WIDTH // 2, 66), 'midtop')
        self.draw_hearts(16, 16, me)
        coin = self.items['coin']
        rect = self.text(str(me.coins), 44, GOLD, (WINDOW_WIDTH - 18, 14), 'topright')
        screen.blit(coin, coin.get_rect(midright=(rect.left - 6, rect.centery - 2)))

        for i, (item, rect) in enumerate(self.shop_cards()):
            offer = r.sabotage_offer(me, item) if self.sabotage_tab() else r.shop_offer(me, item)
            hover = rect.collidepoint(self.mouse)
            fill = (36, 54, 34) if hover and offer['ok'] else (22, 30, 22)
            pygame.draw.rect(screen, fill, rect, border_radius=10)
            pygame.draw.rect(screen, (GREEN if hover else EDGE) if offer['ok'] else (54, 58, 54), rect, 2, border_radius=10)
            title_colour = INK if offer['ok'] else (130, 134, 128)
            if not self.touch:
                self.text(str(i + 1), 20, (110, 120, 106), (rect.right - 10, rect.y + 8), 'topright', shadow=False)
            self.text(offer['name'], 28, title_colour, (rect.x + 12, rect.y + 10), shadow=False)
            self.wrap(offer['desc'], 20, DIM, rect.x + 12, rect.y + 36, rect.width - 24)
            price_colour = GOLD if offer['afford'] else RED
            screen.blit(coin, (rect.x + 12, rect.bottom - 26))
            self.text(str(offer['price']), 28, price_colour, (rect.x + 32, rect.bottom - 28), shadow=False)
            if offer['note']:
                self.text(offer['note'], 20, (200, 190, 150) if offer['ok'] else (130, 130, 120),
                          (rect.right - 12, rect.bottom - 24), 'topright', shadow=False)

        guns = ', '.join(R.WEAPONS[g.kind]['name'] + (f' {g.reserve}' if g.reserve is not None else '')
                         for g in me.owned())
        extras = []
        if me.barricades_held:
            extras.append(f'{me.barricades_held} barricade{"s" if me.barricades_held > 1 else ""}')
        if me.levels['mag']:
            extras.append(f'magazines +{me.levels["mag"]}')
        if me.levels['reload']:
            extras.append(f'fast hands +{me.levels["reload"]}')
        self.wrap(f'Guns (spare ammo): {guns}', 20, INK, 16, WINDOW_HEIGHT - 76, 290)
        if extras:
            self.wrap(', '.join(extras), 20, DIM, 16, WINDOW_HEIGHT - 34, 290)
        if self.online:
            waiting = [self.player_name(h.pid) for h in r.heroes if h is not me and not h.ready and not h.gone]
            if waiting:
                self.text('Waiting for ' + ', '.join(waiting), 24, INK,
                          (WINDOW_WIDTH // 2, WINDOW_HEIGHT - 100), 'midbottom')
        if self.shop_note:
            self.text(self.shop_note, 24, GOLD, (WINDOW_WIDTH // 2, WINDOW_HEIGHT - 92), 'center')
        self.start_button().draw(screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)

    def draw_title(self):
        cx = WINDOW_WIDTH // 2
        self.text('ZOMBIE TOWN', 96, GREEN, (cx, 92), 'midtop')
        self.text('Hold out for ten waves. Spend your coins between them.', 28, INK, (cx, 178), 'midtop')
        mode = R.DIFFICULTY[self.difficulty]
        best, wins = saved_number(f'best_wave_{self.difficulty}'), saved_number(f'wins_{self.difficulty}')
        record = f'{mode["name"]}: best wave {best}' if best else f'{mode["name"]}: no runs yet'
        if wins:
            record += f'   |   town saved {wins} time{"s" if wins > 1 else ""}'
        self.text(record, 24, GOLD, (cx, 208), 'midtop')
        about = [f'{mode["hearts"]} hearts']
        if mode['speed'] < 1:
            about.append('slower zombies')
        if mode['crowd'] != 1:
            about.append('fewer zombies' if mode['crowd'] < 1 else 'bigger hordes')
        if mode['speed'] > 1 or mode['hp'] > 1:
            about.append('faster, tougher zombies')
        if mode['coins'] > 1:
            about.append('extra coins')
        self.text(', '.join(about), 20, DIM, (cx, 234), 'midtop')
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)
        note = 'Multiplayer needs Chrome or Edge in a browser.' if not IS_WEB else 'Four digits and you are in.'
        self.text(note, 20, (100, 110, 96), (cx, WINDOW_HEIGHT - 26), 'midtop')

    def draw_friends(self):
        cx = WINDOW_WIDTH // 2
        self.dim()
        self.text('Play with a Friend', 64, GREEN, (cx, 60), 'midtop')
        lines = ['Two players share one town. Each keeps their own coins and guns.',
                 'The host makes a four-digit room code. The friend types it to join.',
                 'Game messages go straight between your two browsers.']
        y = 150
        for line in lines:
            self.text(line, 24, INK, (cx, y), 'midtop')
            y += 30
        if not IS_WEB:
            self.text('Multiplayer only works in the browser version.', 24, RED, (cx, 330), 'midtop')
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)
        if self.note:
            self.text(self.note, 24, GOLD, (cx, 484 if self.touch else 470), 'midtop')

    def draw_mp_rules(self):
        cx = WINDOW_WIDTH // 2
        self.dim()
        self.text('HOW IT WORKS', 64, GREEN, (cx, 8), 'midtop')
        if self.touch:
            walk = 'Between waves, walk about. Tap SHOP to open the shop, then READY when you are done.'
            sabotage = ('SABOTAGE shop tab: steal coins, ammo or kills, or carry landmines and ambushes into a wave. '
                        'Aimed at the rival with the most kills.')
        else:
            walk = 'Between waves, walk about. Press B for the shop, then READY when you are done.'
            sabotage = ('SABOTAGE shop tab: steal coins, ammo or kills, or carry landmines (X) and ambushes (V) into a wave. '
                        'Aimed at the rival with the most kills.')
        co_op = [
            'Everyone fights the same waves. Each player has their own coins, guns and shop.',
            'Zombies get 25% tougher for each extra player.',
            'Run out of hearts? A friend stands beside you for 3 seconds and brings you back.',
            'You lose only when everyone is down.',
            walk,
            'The next wave starts when everyone is ready.']
        versus = [
            'The same waves, but you race for kills. Kills go to whoever fires the last shot.',
            'The game ends when the boss dies or the town falls.',
            'Most kills wins. Coins break a tie.']
        teams = [
            'Two teams: A is red, B is blue. Dealt at random; the host can change them. Team kills add up.',
            'Teammates can revive you (stand beside them for 3 seconds). Plain versus: downed players return at the shop.']
        if self.touch:                          # a phone is too narrow for two columns: stack them, tighter
            short = dict(width=WINDOW_WIDTH - 80, head=30, line=23, gap=2)
            bottom = self.mp_column('CO-OP', GOLD, co_op, 40, 62, **short)
            bottom = self.mp_column('VERSUS', GOLD, versus + ['Sabotage shop tab: steal coins, ammo or kills, carry mines and ambushes.'],
                                    40, bottom + 4, **short)
            self.mp_column('TEAMS', GOLD, teams, 40, bottom + 4, **short)
        else:
            self.mp_column('CO-OP', GOLD, co_op, 40, 80)
            bottom = self.mp_column('VERSUS', GOLD, versus, WINDOW_WIDTH // 2 + 20, 80)
            bottom = self.mp_column('TEAMS', GOLD, teams, WINDOW_WIDTH // 2 + 20, bottom + 8)
            self.mp_lines(sabotage, 440, width=WINDOW_WIDTH - 80, line=24, x=40)
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)

    def mp_lines(self, text, y, width, line=24, x=None):
        """Wrapped text lines with no heading. Returns the y below them."""
        x = 40 if x is None else x
        font = self.fonts[24]
        for text_line in wrap(font, text, width):
            self.screen.blit(font.render(text_line, True, INK), (x, y))
            y += line
        return y

    def mp_column(self, title, colour, paragraphs, x, y, width=None, head=44, line=25, gap=10):
        """A heading, then wrapped paragraphs, in a column of fixed width. Returns the y below it."""
        width = width or WINDOW_WIDTH // 2 - 70
        self.text(title, 34, colour, (x, y), shadow=False)
        y += head
        font = self.fonts[24]
        for paragraph in paragraphs:
            for text_line in wrap(font, paragraph, width):
                self.screen.blit(font.render(text_line, True, INK), (x, y))
                y += line
            y += gap
        return y

    def draw_invite(self):
        cx = WINDOW_WIDTH // 2
        self.dim()
        self.text('ROOM CODE', 64, GREEN, (cx, 40), 'midtop')
        code = self.room_code or '----'
        self.text(code, 96, GOLD, (cx, 130), 'midtop')
        self.text('Tell your friend this code.', 28, INK, (cx, 270), 'midtop')
        self.text('They press Play with a Friend, then JOIN, and type the four digits.', 24, DIM, (cx, 310), 'midtop')
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)
        if self.note:
            self.text(self.note, 24, GOLD, (cx, 360), 'midtop')

    def draw_join_code(self):
        cx = WINDOW_WIDTH // 2
        self.dim()
        self.text('JOIN A GAME', 64, GREEN, (cx, 40), 'midtop')
        self.text('Type the four-digit room code.', 28, INK, (cx, 150), 'midtop')
        for i in range(4):
            digit = self.code_text[i] if i < len(self.code_text) else '_'
            self.text(digit, 96, GOLD, (cx - 150 + i * 100, 230), 'center')
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)
        if self.note:
            self.text(self.note, 24, GOLD, (cx, 360), 'midtop')

    def draw_lobby(self):
        cx = WINDOW_WIDTH // 2
        self.dim()
        self.text('CONNECTED', 64, GREEN, (cx, 12), 'midtop')
        # name
        self.text('Your name', 24, INK, (cx, 84), 'midtop')
        box = pygame.Rect(cx - 160, 110, 320, 40)
        pygame.draw.rect(self.screen, (22, 30, 22), box, border_radius=8)
        pygame.draw.rect(self.screen, EDGE, box, 2, border_radius=8)
        self.name_cursor += 1 / 60
        shown = self.my_name + ('|' if int(self.name_cursor * 2) % 2 else ' ')
        self.text(shown if self.my_name else 'Name...' + shown[-1], 28, INK if self.my_name else DIM,
                  (box.x + 12, box.y + 6), shadow=False)
        # colours: in teams mode the team is the colour, so there is nothing to pick
        if self.mode == 'teams':
            self.text('Team A is red, Team B is blue', 24, INK, (cx, 186), 'midtop')
            self.text('Your team is shown in the room below', 20, DIM, (cx, 218), 'midtop')
        else:
            self.text('Pick your colour', 24, INK, (cx, 186), 'midtop')
            taken = self.taken_colours()
            for colour, rect in self.swatch_rects():
                rgb = COLOUR_RGB[colour]
                dimmed = colour in taken
                fill = (60, 60, 60) if dimmed else rgb
                pygame.draw.rect(self.screen, fill, rect, border_radius=10)
                if colour == self.my_colour:
                    pygame.draw.rect(self.screen, INK, rect, 4, border_radius=10)
                label = 'taken' if dimmed else colour.upper()
                self.text(label, 20, (20, 20, 20) if not dimmed else (150, 150, 150), rect.center, 'center', shadow=False)
        # the room, and what the host is waiting for
        seats = self.seat_list()
        room = f'{len(seats)} of {self.room_size()} in the room: {self.lobby_status()}'
        self.text(room, 24, INK, (cx, 290), 'midtop')
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[34] if button.rect.height > 36 else self.fonts[24],
                        self.mouse, self.fonts[20] if not self.touch else None)
        entries = [(self.seat_name(slot, e) + (f' ({e["team"]})' if self.mode == 'teams' and e.get('team') else ''),
                    COLOUR_RGB.get(self.colour_of(e), DIM)) for slot, e in seats]
        self.draw_team_row(478, centred=True, entries=entries)

    def draw_pick_team(self):
        cx = WINDOW_WIDTH // 2
        self.screen.fill(PANEL)
        self.text('PICK TEAMS', 64, GOLD, (cx, 40), 'midtop')
        self.text('Click a player to move them to the other team', 24, INK, (cx, 102), 'midtop')
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[24], self.mouse, self.fonts[20] if not self.touch else None)
        for slot, e, rect in self.team_rows():           # the colour box, drawn over its button
            pygame.draw.rect(self.screen, COLOUR_RGB.get(self.colour_of(e), DIM), (rect.x + 10, rect.y + 9, 18, 18), border_radius=3)

    def draw_view_teams(self):
        cx = WINDOW_WIDTH // 2
        self.screen.fill(PANEL)
        self.text('TEAMS', 64, GOLD, (cx, 40), 'midtop')
        self.text('Only the host can change the teams', 24, INK, (cx, 102), 'midtop')
        for slot, e, rect in self.team_rows():
            pygame.draw.rect(self.screen, COLOUR_RGB.get(self.colour_of(e), DIM), (rect.x + 10, rect.y + 9, 18, 18), border_radius=3)
            self.text(f'{self.seat_name(slot, e)}   Team {e.get("team") or "?"}', 28, INK,
                      (rect.x + 40, rect.y + 18), 'midleft')
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)

    def draw_team_row(self, y, centred=False, entries=None):
        """Everyone in the match, along one line: a box of their colour, then their name."""
        if entries is None:
            entries = [(self.player_name(pid), self.player_rgb(pid)) for pid in range(len(self.players))]
        pieces = [(name, rgb, self.fonts[24].size(name)[0]) for name, rgb in entries]
        if not pieces:
            return
        total = sum(18 + 10 + w for _, _, w in pieces) + 30 * (len(pieces) - 1)
        x = (WINDOW_WIDTH - total) // 2 if centred else 16
        for name, rgb, width in pieces:
            pygame.draw.rect(self.screen, rgb, (x, y - 8, 18, 18), border_radius=3)
            pygame.draw.rect(self.screen, (10, 10, 10), (x, y - 8, 18, 18), 2, border_radius=3)
            self.text(name, 24, rgb, (x + 28, y), 'midleft')
            x += 18 + 10 + width + 30

    def draw_help(self):
        cx = WINDOW_WIDTH // 2
        self.text('HOW TO PLAY', 64, GREEN, (cx, 34), 'midtop')
        if self.touch:
            rows = [('Move', 'Hold or drag a finger'), ('Shoot', 'Quick tap where you want to fire'),
                    ('Reload / swap gun', 'RELOAD and SWAP buttons'), ('Barricade', 'BLOCK button')]
        else:
            rows = [('Move', 'W A S D or arrow keys'), ('Aim and shoot', 'Mouse. One click = one shot'),
                    ('Reload', 'R  (or click when empty)'), ('Pick a gun', '1-4, Q or the mouse wheel'),
                    ('Barricade', 'F or right-click'), ('Pause', 'Esc or P        Sound: M')]
        y = 116
        for label, keys in rows:
            self.text(label, 28, GOLD, (cx - 20, y), 'topright')
            self.text(keys, 28, INK, (cx + 10, y))
            y += 36
        tips = ['Zombies drop coins. Ammo boxes refill the guns you bought.',
                'You keep every gun you buy. The pistol never runs out; the others do.',
                'The shop opens after each wave. Wave 10 is the boss.',
                'Multiplayer: stand beside a downed friend for 3 seconds to bring them back.',
                'Make the boss charge into a wall: it is stunned and takes double damage.']
        y += 12
        for tip in tips:
            self.text(tip, 24, DIM, (cx, y), 'midtop')
            y += 28
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)

    def draw_paused(self):
        self.dim()
        self.text('PAUSED', 64, INK, (WINDOW_WIDTH // 2, 140), 'midtop')
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)

    def draw_over(self):
        res = self.result
        cx = WINDOW_WIDTH // 2
        self.dim()
        if self.rules and self.rules.teamed:
            totals = self.rules.team_totals()
            top = totals[0]
            tied = len(totals) > 1 and totals[1][1] == top[1]
            headline = 'A DRAW' if tied else f'TEAM {top[0]} WINS'
            self.text(headline, 64, GOLD, (cx, 40), 'midtop')
            y = 128
            for team, (kills, coins) in totals:
                self.text(f'Team {team}: {kills} kills   {coins} coins', 28, INK, (cx, y), 'midtop')
                y += 36
            names = [f'{self.player_name(h.pid)} ({h.team})  {h.kills}' for h in self.rules.winners()]
            self.text('   '.join(names), 20, DIM, (cx, y + 8), 'midtop')
            for button in self.menu_buttons():
                button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)
            return
        if self.rules and self.rules.versus:
            ranked = self.rules.winners()
            top = [h for h in ranked if (h.kills, h.coins) == (ranked[0].kills, ranked[0].coins)]
            headline = (f'WINNER: {self.player_name(top[0].pid)}' if len(top) == 1 else 'A DRAW')
            self.text(headline, 64, GOLD, (cx, 60), 'midtop')
            y = 150
            for h in ranked:
                self.text(f'{self.player_name(h.pid)}', 28, self.player_rgb(h.pid), (cx - 20, y), 'topright')
                self.text(f'{h.kills} kills   {h.coins} coins', 28, INK, (cx, y))
                y += 40
            for button in self.menu_buttons():
                button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)
            return
        if self.online and not res:
            res = {'won': self.rules.state == 'won', 'wave': self.rules.wave, 'new_best': False,
                   'kills': self.rules.stats['kills'], 'time': self.rules.stats['time'],
                   'coins': self.rules.stats['coins'], 'accuracy': self.rules.stats['hits'] / max(1, self.rules.stats['pellets'])}
        if res['won']:
            self.text('THE TOWN IS SAFE', 96, GREEN, (cx, 70), 'midtop')
            self.text('You held out for all ten waves and killed the Abomination.', 28, INK, (cx, 152), 'midtop')
        else:
            self.text('OVERRUN', 96, RED, (cx, 70), 'midtop')
            self.text(f'You fell on wave {res["wave"]} of {R.WAVES}.', 28, INK, (cx, 152), 'midtop')
            if res['new_best']:
                self.text('New best!', 34, GOLD, (cx, 186), 'midtop')
        minutes, seconds = divmod(int(res['time']), 60)
        stats = [('Zombies killed', str(res['kills'])), ('Coins collected', str(res['coins'])),
                 ('Accuracy', f'{res["accuracy"]:.0%}'), ('Time', f'{minutes}:{seconds:02d}')]
        y = 240
        for label, value in stats:
            self.text(label, 28, DIM, (cx - 12, y), 'topright')
            self.text(value, 28, INK, (cx + 12, y))
            y += 36
        for button in self.menu_buttons():
            button.draw(self.screen, self.fonts[34], self.mouse, self.fonts[20] if not self.touch else None)

    async def run(self):
        loading(100)                            # lift the loading screen
        if IS_WEB:
            self.watch_page_close()
        while True:
            # In the browser, clock.tick(FPS) would freeze the page: only measure there.
            dt = min(self.clock.tick(0 if IS_WEB else FPS) / 1000, 0.05)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.leave_co_op()
                    pygame.quit()
                    return
                self.handle_event(event)
            if self.scene == 'play':
                self.update(dt)
            else:
                self.time += dt
                self.update_effects(dt)
                if self.peer:
                    self.check_link()
            self.draw()
            pygame.display.update()
            await asyncio.sleep(1 / FPS if IS_WEB else 0)   # yield to the browser


async def main():
    try:
        loading(92, 'Almost ready...')
        await Game().run()
    except Exception:
        print(traceback.format_exc())           # the details, for you: the browser console (F12)
        if IS_WEB:                              # never leave players staring at a loading bar
            from pyscript import document
            document.getElementById('loading').style.display = 'none'
            box = document.getElementById('error')
            box.textContent = 'Sorry, the game hit a problem. Please reload the page.'
            box.style.display = 'block'
        raise


if __name__ == '__main__':
    try:
        asyncio.get_running_loop()              # PyScript: a loop is already running
        task = asyncio.create_task(main())
    except RuntimeError:
        asyncio.run(main())                     # desktop: python main.py
