4 Commits ae09b96d64 ... aa695a2afb

Auteur SHA1 Message Date
  Idleman aa695a2afb feat(maps): map catalog, lobby rotation, catch-up pick, modifiers, two new maps (M6) il y a 3 semaines
  Idleman 4939e09d8a feat(characters): Mamie Tricot, Pyromanchot and the character selection screen (M5) il y a 3 semaines
  Idleman c5620bd5a9 feat(rules): cherry, rising custard, spoon catapult, items, rounds and trophies (M4) il y a 4 semaines
  Idleman 699e8b7ce1 feat(net): LAN discovery, lobby with ready check, match start, hash check (M3) il y a 4 semaines
53 fichiers modifiés avec 4384 ajouts et 249 suppressions
  1. 25 0
      assets/characters/mamie/character.json
  2. 27 0
      assets/characters/pyromanchot/character.json
  3. BIN
      assets/maps/mille-feuille/background.png
  4. 14 0
      assets/maps/mille-feuille/map.json
  5. BIN
      assets/maps/mille-feuille/terrain.png
  6. BIN
      assets/maps/mille-feuille/thumb.png
  7. BIN
      assets/maps/piece-montee/background.png
  8. 14 0
      assets/maps/piece-montee/map.json
  9. BIN
      assets/maps/piece-montee/terrain.png
  10. BIN
      assets/maps/piece-montee/thumb.png
  11. 1 1
      package.json
  12. 21 2
      readme.md
  13. 158 61
      scripts/gen-maps.ts
  14. 67 0
      src/main/discovery.ts
  15. 31 5
      src/main/index.ts
  16. 20 2
      src/preload/api.ts
  17. 13 3
      src/preload/index.ts
  18. 104 0
      src/renderer/characters/painters.ts
  19. 4 0
      src/renderer/config.ts
  20. 13 1
      src/renderer/entities/PlayerView.ts
  21. 174 0
      src/renderer/entities/RoundViews.ts
  22. 98 5
      src/renderer/i18n/fr.ts
  23. 1 0
      src/renderer/input.ts
  24. 196 32
      src/renderer/main.ts
  25. 33 7
      src/renderer/net/interpolation.ts
  26. 528 0
      src/renderer/style.css
  27. 105 0
      src/renderer/ui/browser.ts
  28. 179 0
      src/renderer/ui/hud.ts
  29. 105 0
      src/renderer/ui/lobbyPanel.ts
  30. 72 6
      src/renderer/ui/menu.ts
  31. 10 1
      src/server/assets.ts
  32. 56 0
      src/server/discovery.ts
  33. 584 50
      src/server/game.ts
  34. 66 14
      src/server/index.ts
  35. 29 0
      src/server/modifiers/index.ts
  36. 34 0
      src/server/modifiers/randomCracks.ts
  37. 21 0
      src/server/modifiers/wind.ts
  38. 310 54
      src/server/net.ts
  39. 2 0
      src/server/physics/fallingChunk.ts
  40. 33 0
      src/server/rotation.ts
  41. 63 0
      src/server/stats.ts
  42. 23 0
      src/shared/characters/Character.ts
  43. 56 0
      src/shared/characters/Mamie.ts
  44. 66 0
      src/shared/characters/Pyromanchot.ts
  45. 7 2
      src/shared/characters/index.ts
  46. 68 1
      src/shared/constants.ts
  47. 2 0
      src/shared/input.ts
  48. 172 2
      src/shared/protocol.ts
  49. 140 0
      tests/characters.test.ts
  50. 46 0
      tests/discovery.test.ts
  51. 107 0
      tests/maps.test.ts
  52. 280 0
      tests/net.test.ts
  53. 206 0
      tests/rules.test.ts

+ 25 - 0
assets/characters/mamie/character.json

@@ -0,0 +1,25 @@
+{
+  "id": "mamie",
+  "name": "Mamie Tricot",
+  "speed": 175,
+  "acceleration": 1500,
+  "jump": 540,
+  "mass": 1.1,
+  "size": 20,
+  "cooldowns": { "attack": 0.32, "special": 1.1 },
+  "params": {
+    "needleReach": 14,
+    "needleRadius": 14,
+    "needleKnockback": 260,
+    "needleStun": 0.7,
+    "needleCarveRadius": 7,
+    "needlePower": 15,
+    "jabAnim": 0.15,
+    "yarnSpeed": 560,
+    "yarnStart": 8,
+    "yarnLife": 1.3,
+    "yarnTrailRadius": 5,
+    "yarnBlobRadius": 13,
+    "throwAnim": 0.25
+  }
+}

+ 27 - 0
assets/characters/pyromanchot/character.json

@@ -0,0 +1,27 @@
+{
+  "id": "pyromanchot",
+  "name": "Pyromanchot",
+  "speed": 250,
+  "acceleration": 2100,
+  "jump": 600,
+  "mass": 1,
+  "size": 19,
+  "cooldowns": { "attack": 0.45, "special": 2.4 },
+  "params": {
+    "crackerSpeed": 620,
+    "crackerLift": 120,
+    "crackerFuse": 0.75,
+    "crackerRadius": 26,
+    "crackerPower": 40,
+    "crackerKnockback": 520,
+    "crackerStun": 0.4,
+    "backfireEvery": 3,
+    "throwAnim": 0.2,
+    "slideSpeed": 620,
+    "slideTime": 0.55,
+    "slideBlastRadius": 42,
+    "slideBlastPower": 45,
+    "slideKnockback": 680,
+    "slideStun": 0.5
+  }
+}

BIN
assets/maps/mille-feuille/background.png


+ 14 - 0
assets/maps/mille-feuille/map.json

@@ -0,0 +1,14 @@
+{
+  "id": "mille-feuille",
+  "name": "Le Mille-Feuille",
+  "size": [2048, 1024],
+  "materialPalette": {
+    "#000000": 0, "#C8964B": 5, "#FFFFFF": 3, "#5A3A22": 2, "#8899AA": 255
+  },
+  "spawns": [[400, 300], [1650, 300], [800, 300], [1250, 300]],
+  "cherrySpawn": [1024, 200],
+  "custard": { "startY": 1000, "speed": 2.5, "finalRushSpeed": 8 },
+  "items": { "interval": [6, 12], "weights": { "candle": 3, "smarties": 2, "whisk": 1 } },
+  "music": "birthday-flute",
+  "modifiers": ["random-cracks"]
+}

BIN
assets/maps/mille-feuille/terrain.png


BIN
assets/maps/mille-feuille/thumb.png


BIN
assets/maps/piece-montee/background.png


+ 14 - 0
assets/maps/piece-montee/map.json

@@ -0,0 +1,14 @@
+{
+  "id": "piece-montee",
+  "name": "La Pièce Montée",
+  "size": [2048, 1024],
+  "materialPalette": {
+    "#000000": 0, "#F2C46D": 1, "#FFFFFF": 3, "#D98A1E": 6, "#8899AA": 255
+  },
+  "spawns": [[300, 600], [1750, 600], [1024, 250], [700, 300]],
+  "cherrySpawn": [1024, 150],
+  "custard": { "startY": 1000, "speed": 2.2, "finalRushSpeed": 7 },
+  "items": { "interval": [6, 12], "weights": { "candle": 4, "smarties": 2, "whisk": 1 } },
+  "music": "birthday-flute",
+  "modifiers": ["wind"]
+}

BIN
assets/maps/piece-montee/terrain.png


BIN
assets/maps/piece-montee/thumb.png


+ 1 - 1
package.json

@@ -12,7 +12,7 @@
     "lint": "eslint . && tsc --noEmit -p tsconfig.node.json && tsc --noEmit -p tsconfig.web.json",
     "build": "electron-vite build",
     "dist": "electron-vite build && electron-builder --win",
-    "gen:test-map": "tsx scripts/gen-test-map.ts"
+    "gen:maps": "tsx scripts/gen-maps.ts"
   },
   "dependencies": {
     "msgpackr": "^1.12.1",

+ 21 - 2
readme.md

@@ -39,9 +39,10 @@ Pas de nouvelle dépendance sans justification dans le message de commit.
 npm install
 npm run dev            # Electron en dev (HMR renderer)
 npm run server         # serveur headless en Node pur (tests, bots, debug)
+                       #   ex. : npm run server -- --name="Test" --round=30 --rounds=2 --pause=5
 npm test               # vitest
 npm run bench          # benchmarks vitest (budget terrain §5)
-npm run gen:test-map   # régénère les PNG placeholder de gateau-etages
+npm run gen:maps       # régénère les PNG placeholder des cartes intégrées
 npm run lint           # eslint + tsc --noEmit
 npm run build          # build de prod
 npm run dist           # installeur Windows (electron-builder)
@@ -288,18 +289,36 @@ Chaque étape doit être **jouable** avant de passer à la suivante.
 - Inputs vers le serveur, snapshots et ops vers les clients, interpolation.
 - Test de cohérence : hash du bitmap comparé entre serveur et clients toutes les 5 secondes, avec un log d'erreur en cas d'écart.
 - **Terminé quand :** 4 PC en LAN creusent le même gâteau sans aucune différence.
+- **État :** implémenté. Le serveur s'annonce sur chaque sous-réseau et en local. L'écran « Les goûters du coin » liste les parties, permet d'en créer une ou d'en rejoindre une par adresse. Pendant l'échauffement, chacun se déclare prêt ; quand tout le monde l'est, un compte à rebours de 3 s lance la partie sur une carte neuve. Le hash est vérifié toutes les 5 s et un écart est loggé côté serveur. Testé avec plusieurs clients en tests automatiques et avec 2 instances sur le même PC. **Reste à valider sur 4 vrais PC** (pare-feu Windows à autoriser au premier lancement).
 ### M4 : Règles de jeu
  
 - Cerise, score, crème qui monte, cuillère de réapparition, objets, manches, partie, écran de score.
 - **Terminé quand :** une partie complète se joue du lobby aux trophées.
+- **État :** implémenté.
+  - **Échauffement :** la carte sert de salle d'attente. Pas de chrono, de cerise ni d'objets, et la crème ne monte pas, mais on peut y tomber.
+  - **Mort :** tomber dans la crème ou être écrasé par un bloc. On revient 5 s plus tard par la cuillère, lancée depuis une colonne de vide vers le point d'apparition le plus proche.
+  - **Objets :** Smarties et fouet agissent au ramassage. La bougie se garde et se lance avec **F** ; son explosion touche tout le monde, le lanceur compris.
+  - **Trophées** (`server/stats.ts`) : Le Glouton, Le Kamikaze, Le Promoteur Immobilier, Pas Sa Faute, L'Artificier, Le Cueilleur.
+  - **Reste en M7 :** le rattrapage (le dernier choisit la carte et impose un personnage).
 ### M5 : Trois personnages
  
 - Castor Glouton (déjà jouable depuis M1), Mamie Tricot, Pyromanchot (le trio creuser / construire / exploser).
-- Écran de sélection des personnages (une version minimale existe dans l'écran titre).
+- Écran de sélection des personnages.
+- **État :** implémenté.
+  - **Mamie Tricot :** ses aiguilles assomment longtemps. Sa pelote tisse un fil de Laine qui s'accroche où elle touche : ancré aux deux bouts, c'est un pont ou un filet, sinon il tombe. Toute explosion brûle la laine dans `WOOL_BURN_RADIUS_FACTOR` fois son rayon.
+  - **Pyromanchot :** ses pétards explosent au contact, sauf un sur trois qui lui explose dessus. Sa glissade sur le ventre se termine par une explosion qui l'épargne.
+  - **Objets lancés :** bougie, pétards et pelotes partagent un même système de projectiles côté serveur.
+  - **Écran de sélection :** une fiche par personnage (attaque, spécial, défaut) avec des barres Vitesse / Saut / Poids lues dans `character.json`.
 ### M6 : Plusieurs cartes
  
 - Loader validé, rotation configurable dans le lobby, choix par le dernier, `modifiers`.
 - Cartes `mille-feuille` et `piece-montee` en plus de `gateau-etages`.
+- **État :** implémenté.
+  - **Validation :** au démarrage, le serveur valide chaque dossier de `assets/maps/`, modificateurs inconnus compris. Une carte invalide est écartée avec un message explicite dans le journal.
+  - **Rotation :** l'hôte (👑, le premier arrivé) la règle dans le panneau d'échauffement : toutes dans l'ordre, au hasard, ou une sélection. L'échauffement se fait sur la première carte de la rotation.
+  - **Choix par le dernier :** pendant l'écran de fin de manche, le dernier choisit la carte suivante parmi la rotation (logique dans `server/rotation.ts`). Sans choix, la rotation décide.
+  - **Modificateurs** (`server/modifiers/`) : `wind` (rafales latérales, indicateur dans le bandeau) et `random-cracks` (fissures en zigzag dans le biscuit). Ils ne jouent que pendant les manches. Pour les tester dès maintenant, `random-cracks` est sur le Mille-Feuille et `wind` sur la Pièce Montée ; à redistribuer sur la Tarte et les Crêpes en M7.
+  - **Cartes :** générées par `npm run gen:maps`. Sur la Pièce Montée, chaque chou n'est collé qu'à celui du dessous, donc en retirer un fait tomber toute la colonne au-dessus.
 ### M7 et suite
  
 - Les 5 autres personnages, les 3 autres cartes, le rattrapage complet, les trophées, la DA finale, l'audio, l'éditeur de cartes, l'installeur Windows.

+ 158 - 61
scripts/gen-test-map.ts → scripts/gen-maps.ts

@@ -1,12 +1,12 @@
-// Generates the placeholder PNGs of the reference map "gateau-etages".
-// Usage: npm run gen:test-map
+// Generates the placeholder PNGs (terrain, background, thumbnail) of every built-in map.
+// Usage: npm run gen:maps
 import { mkdirSync, writeFileSync } from 'node:fs';
 import { resolve } from 'node:path';
 import { PNG } from 'pngjs';
 
 const W = 2048;
 const H = 1024;
-const outDir = resolve(import.meta.dirname, '../assets/maps/gateau-etages');
+const mapsDir = resolve(import.meta.dirname, '../assets/maps');
 
 const VOID = 0x000000;
 const SPONGE = 0xf2c46d;
@@ -14,60 +14,135 @@ const CHOCOLATE = 0x5a3a22;
 const CREAM = 0xffffff;
 const JELLY = 0xd93a5b;
 const BISCUIT = 0xc8964b;
+const CARAMEL = 0xd98a1e;
 const PLATE = 0x8899aa;
 
-const terrain = new Uint32Array(W * H).fill(VOID);
-const put = (x: number, y: number, c: number): void => {
-  if (x >= 0 && y >= 0 && x < W && y < H) terrain[y * W + x] = c;
-};
-const rect = (x0: number, y0: number, x1: number, y1: number, c: number): void => {
-  for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) put(x, y, c);
-};
+/** A terrain image being drawn, one 0xRRGGBB color per pixel (colors map to materials in map.json). */
+class Canvas {
+  readonly px = new Uint32Array(W * H).fill(VOID);
+
+  put(x: number, y: number, c: number): void {
+    if (x >= 0 && y >= 0 && x < W && y < H) this.px[y * W + x] = c;
+  }
 
-// Plate: a wide dish with a raised rim.
-rect(180, 960, 1868, 990, PLATE);
-rect(150, 940, 200, 975, PLATE);
-rect(1848, 940, 1898, 975, PLATE);
+  rect(x0: number, y0: number, x1: number, y1: number, c: number): void {
+    for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) this.put(x, y, c);
+  }
+
+  disc(cx: number, cy: number, r: number, c: number): void {
+    for (let y = Math.floor(cy - r); y <= cy + r; y++) {
+      for (let x = Math.floor(cx - r); x <= cx + r; x++) if ((x - cx) ** 2 + (y - cy) ** 2 <= r * r) this.put(x, y, c);
+    }
+  }
 
-interface Tier {
-  x0: number;
-  x1: number;
-  top: number;
-  bottom: number;
+  /** The dish everything stands on (the anchor). */
+  plate(): void {
+    this.rect(180, 960, 1868, 990, PLATE);
+    this.rect(150, 940, 200, 975, PLATE);
+    this.rect(1848, 940, 1898, 975, PLATE);
+  }
+
+  /** Whipped cream along the top of [x0, x1) at `top`, with drips. */
+  frosting(x0: number, x1: number, top: number): void {
+    for (let x = x0 - 6; x < x1 + 6; x++) {
+      const wave = Math.round(6 + 4 * Math.sin(x / 23));
+      for (let y = top - wave; y < top + 12; y++) this.put(x, y, CREAM);
+      const drip = (x * 7919) % 97 < 6 ? 18 + ((x * 31) % 22) : 0;
+      if (x >= x0 && x < x1) for (let y = top + 12; y < top + 12 + drip; y++) this.put(x, y, CREAM);
+    }
+    for (let y = top; y < top + 60; y++) {
+      const len = Math.max(0, 6 - Math.floor((y - top) / 10));
+      for (let i = 0; i < len; i++) {
+        this.put(x0 - 6 + i, y, CREAM);
+        this.put(x1 + 5 - i, y, CREAM);
+      }
+    }
+  }
 }
-const tiers: Tier[] = [
-  { x0: 280, x1: 1768, top: 700, bottom: 960 },
-  { x0: 520, x1: 1528, top: 470, bottom: 700 },
-  { x0: 780, x1: 1268, top: 270, bottom: 470 },
-];
-
-for (const t of tiers) {
-  const h = t.bottom - t.top;
-  rect(t.x0, t.top, t.x1, t.bottom, SPONGE);
-  // Biscuit base, jelly layer and chocolate layer.
-  rect(t.x0, t.bottom - Math.round(h * 0.12), t.x1, t.bottom, BISCUIT);
-  rect(t.x0, t.top + Math.round(h * 0.55), t.x1, t.top + Math.round(h * 0.62), JELLY);
-  rect(t.x0, t.top + Math.round(h * 0.3), t.x1, t.top + Math.round(h * 0.36), CHOCOLATE);
-  // Chocolate pillar in the middle, a hard core to dig around.
-  const mid = Math.round((t.x0 + t.x1) / 2);
-  rect(mid - 20, t.top + 20, mid + 20, t.bottom - Math.round(h * 0.12), CHOCOLATE);
-  // Whipped cream frosting with drips.
-  for (let x = t.x0 - 6; x < t.x1 + 6; x++) {
-    const wave = Math.round(6 + 4 * Math.sin(x / 23));
-    for (let y = t.top - wave; y < t.top + 12; y++) put(x, y, CREAM);
-    const drip = (x * 7919) % 97 < 6 ? 18 + ((x * 31) % 22) : 0;
-    if (x >= t.x0 && x < t.x1) for (let y = t.top + 12; y < t.top + 12 + drip; y++) put(x, y, CREAM);
+
+/** Le Gâteau à Étages: three tiers of sponge with chocolate and jelly layers. */
+function gateauEtages(): Canvas {
+  const c = new Canvas();
+  c.plate();
+  const tiers = [
+    { x0: 280, x1: 1768, top: 700, bottom: 960 },
+    { x0: 520, x1: 1528, top: 470, bottom: 700 },
+    { x0: 780, x1: 1268, top: 270, bottom: 470 },
+  ];
+  for (const t of tiers) {
+    const h = t.bottom - t.top;
+    c.rect(t.x0, t.top, t.x1, t.bottom, SPONGE);
+    // Biscuit base, jelly layer and chocolate layer.
+    c.rect(t.x0, t.bottom - Math.round(h * 0.12), t.x1, t.bottom, BISCUIT);
+    c.rect(t.x0, t.top + Math.round(h * 0.55), t.x1, t.top + Math.round(h * 0.62), JELLY);
+    c.rect(t.x0, t.top + Math.round(h * 0.3), t.x1, t.top + Math.round(h * 0.36), CHOCOLATE);
+    // Chocolate pillar in the middle, a hard core to dig around.
+    const mid = Math.round((t.x0 + t.x1) / 2);
+    c.rect(mid - 20, t.top + 20, mid + 20, t.bottom - Math.round(h * 0.12), CHOCOLATE);
+    c.frosting(t.x0, t.x1, t.top);
   }
-  for (let y = t.top; y < t.top + 60; y++) {
-    const len = Math.max(0, 6 - Math.floor((y - t.top) / 10));
-    for (let i = 0; i < len; i++) {
-      put(t.x0 - 6 + i, y, CREAM);
-      put(t.x1 + 5 - i, y, CREAM);
+  return c;
+}
+
+/**
+ * Le Mille-Feuille: thin brittle pastry sheets alternating with thick soft cream, so digging
+ * down is quick while every pastry sheet makes tunnelling sideways a chore. A slice is missing
+ * in the middle: two towers on a common base.
+ */
+function milleFeuille(): Canvas {
+  const c = new Canvas();
+  c.plate();
+  const x0 = 260;
+  const x1 = 1788;
+  const top = 440;
+  const bottom = 960;
+  const PASTRY = 16;
+  const FILLING = 44;
+  for (let y = top; y < bottom; y++) {
+    const layer = (y - top) % (PASTRY + FILLING);
+    c.rect(x0, y, x1, y + 1, layer < PASTRY ? BISCUIT : CREAM);
+  }
+  // Fondant icing with the classic chocolate feathering.
+  c.rect(x0 - 4, top - 18, x1 + 4, top, CREAM);
+  for (let x = x0; x < x1; x++) {
+    for (const row of [top - 14, top - 8]) if (Math.abs(((x + row * 3) % 60) - 30) < 2) c.rect(x, row, x + 1, row + 3, CHOCOLATE);
+    if (x % 60 < 3) c.rect(x, top - 16, x + 1, top - 2, CHOCOLATE);
+  }
+  // The missing slice: a trench down to the third pastry sheet.
+  c.rect(954, top - 18, 1094, top + 2 * (PASTRY + FILLING) + PASTRY, VOID);
+  return c;
+}
+
+/**
+ * La Pièce Montée: a stepped pyramid of choux on a nougatine base. Each chou is glued with
+ * caramel to the one under it only, so taking one out drops the whole column above it.
+ */
+function pieceMontee(): Canvas {
+  const c = new Canvas();
+  c.plate();
+  // Nougatine base.
+  c.rect(470, 905, 1578, 960, CARAMEL);
+  const R = 40;
+  const STEP_X = 82; // 2 px gap between neighbours: they never touch sideways
+  const STEP_Y = 82;
+  const base = 13;
+  const cx0 = 1024;
+  for (let row = 0; 2 * row < base; row++) {
+    const count = base - 2 * row;
+    const cy = 905 - R - 2 - row * STEP_Y;
+    for (let i = 0; i < count; i++) {
+      const cx = cx0 + (i - (count - 1) / 2) * STEP_X;
+      c.disc(cx, cy, R, SPONGE);
+      c.disc(cx, cy, R - 14, CREAM);
+      // Caramel glaze on top and the glue joint with what is below.
+      for (let a = -2.4; a <= -0.7; a += 0.02) c.disc(cx + Math.cos(a) * (R - 4), cy + Math.sin(a) * (R - 4), 5, CARAMEL);
+      c.disc(cx, cy + R + 1, 11, CARAMEL);
     }
   }
+  return c;
 }
 
-function writePng(name: string, w: number, h: number, pixel: (x: number, y: number) => number): void {
+function writePng(dir: string, name: string, w: number, h: number, pixel: (x: number, y: number) => number): void {
   const png = new PNG({ width: w, height: h });
   for (let y = 0; y < h; y++) {
     for (let x = 0; x < w; x++) {
@@ -79,7 +154,7 @@ function writePng(name: string, w: number, h: number, pixel: (x: number, y: numb
       png.data[i + 3] = 0xff;
     }
   }
-  writeFileSync(resolve(outDir, name), PNG.sync.write(png));
+  writeFileSync(resolve(dir, name), PNG.sync.write(png));
 }
 
 const lerp = (a: number, b: number, t: number): number => Math.round(a + (b - a) * t);
@@ -97,7 +172,19 @@ function hash(x: number, y: number): number {
   return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
 }
 
-function paintBackground(): Uint32Array {
+interface Theme {
+  stripe: number;
+  cloth: [number, number, number];
+  flags: number[];
+}
+
+const THEMES: Record<string, Theme> = {
+  'gateau-etages': { stripe: 0xffdbe3, cloth: [0xe85d75, 0xf7a8b8, 0xfff3f5], flags: [0xff6f91, 0xffe14d, 0x4dc4ff, 0x9be15d, 0xb18cff] },
+  'mille-feuille': { stripe: 0xd9ecff, cloth: [0x4d8fd9, 0xa8cdf7, 0xf3f8ff], flags: [0x4dc4ff, 0xffffff, 0xffe14d, 0x9be15d, 0x4dc4ff] },
+  'piece-montee': { stripe: 0xfff0c2, cloth: [0xd9a01e, 0xf7d98a, 0xfffaf0], flags: [0xffe14d, 0xff9a2e, 0xffffff, 0xff6f91, 0xffd27a] },
+};
+
+function paintBackground(theme: Theme): Uint32Array {
   const img = new Uint32Array(W * H);
   type Inside = (x: number, y: number) => boolean;
   /** Fills a shape (inside test over a bounding box) with a color function and a felt outline. */
@@ -119,7 +206,7 @@ function paintBackground(): Uint32Array {
   shape(0, 0, W, TABLE_Y, () => true, (x, y) => {
     const stripe = x % 96 < 30;
     const dot = !stripe && ((x + (Math.floor(y / 40) % 2) * 24) % 48) ** 2 / 9 + ((y % 40) - 20) ** 2 / 9 < 4;
-    const base = stripe ? 0xffdbe3 : dot ? 0xf7c9a8 : 0xfff3dc;
+    const base = stripe ? theme.stripe : dot ? 0xf7c9a8 : 0xfff3dc;
     return mix(base, 0xf6d7b0, Math.max(0, (y - 300) / 900));
   }, 0);
   // Skirting board.
@@ -182,7 +269,7 @@ function paintBackground(): Uint32Array {
   // Bunting garland across the top.
   const sag = (x: number): number => 30 + 70 * Math.sin((x / W) * Math.PI);
   shape(0, 0, W, 130, (x, y) => Math.abs(y - sag(x)) < 3, solid(INK), 0);
-  const flagColors = [0xff6f91, 0xffe14d, 0x4dc4ff, 0x9be15d, 0xb18cff];
+  const flagColors = theme.flags;
   for (let i = 0, fx = 20; fx < W; i++, fx += 110) {
     const top = sag(fx + 35);
     const inside: Inside = (x, y) => {
@@ -200,21 +287,31 @@ function paintBackground(): Uint32Array {
     const cy = Math.floor((y - TABLE_Y) / (cell * 0.6));
     const a = (cx & 1) === 0;
     const b = (cy & 1) === 0;
-    const base = a && b ? 0xe85d75 : a || b ? 0xf7a8b8 : 0xfff3f5;
+    const base = a && b ? theme.cloth[0] : a || b ? theme.cloth[1] : theme.cloth[2];
     return mix(base, 0x7a3a2a, depth * 0.25);
   });
   shape(0, TABLE_Y - 6, W, TABLE_Y + 30, (x, y) => y >= TABLE_Y - 6 && y < TABLE_Y + 14 + 12 * Math.abs(Math.sin((x / 40) * Math.PI)), (x, y) => (((x % 40) - 20) ** 2 + (y - TABLE_Y - 8) ** 2 < 25 ? 0xf3dfe3 : 0xffffff), 3);
   return img;
 }
 
-mkdirSync(outDir, { recursive: true });
-writePng('terrain.png', W, H, (x, y) => terrain[y * W + x]);
-const background = paintBackground();
-writePng('background.png', W, H, (x, y) => background[y * W + x]);
+const MAPS: Record<string, () => Canvas> = {
+  'gateau-etages': gateauEtages,
+  'mille-feuille': milleFeuille,
+  'piece-montee': pieceMontee,
+};
+
 const TW = 256;
 const TH = 128;
-writePng('thumb.png', TW, TH, (x, y) => {
-  const c = terrain[Math.floor((y * H) / TH) * W + Math.floor((x * W) / TW)];
-  return c === VOID ? 0xbfe6ff : c;
-});
-console.log(`Wrote terrain.png, background.png and thumb.png to ${outDir}`);
+for (const [id, build] of Object.entries(MAPS)) {
+  const dir = resolve(mapsDir, id);
+  mkdirSync(dir, { recursive: true });
+  const terrain = build().px;
+  writePng(dir, 'terrain.png', W, H, (x, y) => terrain[y * W + x]);
+  const background = paintBackground(THEMES[id]);
+  writePng(dir, 'background.png', W, H, (x, y) => background[y * W + x]);
+  writePng(dir, 'thumb.png', TW, TH, (x, y) => {
+    const c = terrain[Math.floor((y * H) / TH) * W + Math.floor((x * W) / TW)];
+    return c === VOID ? 0xbfe6ff : c;
+  });
+  console.log(`Wrote ${id}: terrain.png, background.png, thumb.png`);
+}

+ 67 - 0
src/main/discovery.ts

@@ -0,0 +1,67 @@
+import { createSocket, type Socket } from 'node:dgram';
+import { DISCOVERY_PORT, DISCOVERY_TTL_MS } from '../shared/constants';
+import { isAnnouncement, type Announcement } from '../shared/protocol';
+import type { LanGame } from '../preload/api';
+
+interface Seen {
+  announcement: Announcement;
+  address: string;
+  lastSeen: number;
+}
+
+/** Listens for UDP announcements and keeps the list of games currently visible on the LAN. */
+export class DiscoveryListener {
+  private socket: Socket | null = null;
+  private readonly games = new Map<string, Seen>();
+
+  start(onError: (err: Error) => void): void {
+    if (this.socket) return;
+    const socket = createSocket({ type: 'udp4', reuseAddr: true });
+    socket.on('error', onError);
+    socket.on('message', (data, rinfo) => {
+      let msg: unknown;
+      try {
+        msg = JSON.parse(data.toString('utf8'));
+      } catch {
+        return;
+      }
+      if (!isAnnouncement(msg)) return;
+      const known = this.games.get(msg.serverId);
+      // The same server is heard on loopback and on the LAN: keep the LAN address when we have one.
+      const address = known && rinfo.address === '127.0.0.1' && known.address !== '127.0.0.1' ? known.address : rinfo.address;
+      this.games.set(msg.serverId, { announcement: msg, address, lastSeen: Date.now() });
+    });
+    socket.bind(DISCOVERY_PORT);
+    this.socket = socket;
+  }
+
+  stop(): void {
+    this.socket?.close();
+    this.socket = null;
+    this.games.clear();
+  }
+
+  list(): LanGame[] {
+    const now = Date.now();
+    const out: LanGame[] = [];
+    for (const [id, seen] of this.games) {
+      if (now - seen.lastSeen > DISCOVERY_TTL_MS) {
+        this.games.delete(id);
+        continue;
+      }
+      const a = seen.announcement;
+      out.push({
+        serverId: a.serverId,
+        name: a.name,
+        mapId: a.mapId,
+        players: a.players,
+        maxPlayers: a.maxPlayers,
+        phase: a.phase,
+        version: a.version,
+        address: seen.address,
+        port: a.port,
+      });
+    }
+    return out.sort((x, y) => x.name.localeCompare(y.name));
+  }
+}

+ 31 - 5
src/main/index.ts

@@ -1,8 +1,11 @@
 import { join } from 'node:path';
-import { app, BrowserWindow, ipcMain, utilityProcess, type UtilityProcess } from 'electron';
+import { app, BrowserWindow, ipcMain, utilityProcess, type UtilityProcess, type WebContents } from 'electron';
 import { readFileSync } from 'node:fs';
 import type { HostResult, MapFiles } from '../preload/api';
-import { readMapFiles, readMapImage, resolveAssetsDir } from '../server/assets';
+import { DISCOVERY_INTERVAL_MS } from '../shared/constants';
+import { loadCharacterStats, readMapFiles, readMapImage, resolveAssetsDir } from '../server/assets';
+import { CHARACTER_IDS } from '../shared/characters';
+import { DiscoveryListener } from './discovery';
 
 const assetsDir = app.isPackaged ? join(process.resourcesPath, 'assets') : join(app.getAppPath(), 'assets');
 process.env.GOUTER_ASSETS = assetsDir;
@@ -11,10 +14,10 @@ let server: UtilityProcess | null = null;
 let serverReady: Promise<HostResult> | null = null;
 
 /** Forks the authoritative server in a utilityProcess (once) and waits for it to listen. */
-function hostServer(): Promise<HostResult> {
+function hostServer(name: string): Promise<HostResult> {
   if (serverReady) return serverReady;
   serverReady = new Promise<HostResult>((resolveReady, reject) => {
-    const proc = utilityProcess.fork(join(__dirname, 'server.js'), [], {
+    const proc = utilityProcess.fork(join(__dirname, 'server.js'), [`--name=${String(name).slice(0, 40)}`], {
       serviceName: 'goutermageddon-server',
       env: { ...process.env, GOUTER_ASSETS: assetsDir },
       stdio: 'inherit',
@@ -51,8 +54,30 @@ function createWindow(): void {
   else void win.loadFile(join(__dirname, '../renderer/index.html'));
 }
 
-ipcMain.handle('lan:host', () => hostServer());
+// LAN discovery: one listener for the app, pushed to the renderer that asked for it.
+const discovery = new DiscoveryListener();
+let discoveryTimer: NodeJS.Timeout | null = null;
+function startDiscovery(target: WebContents): void {
+  stopDiscovery();
+  discovery.start((err) => console.error('[discovery] cannot listen:', err.message));
+  const push = (): void => {
+    if (target.isDestroyed()) return stopDiscovery();
+    target.send('lan:games', discovery.list());
+  };
+  push();
+  discoveryTimer = setInterval(push, DISCOVERY_INTERVAL_MS);
+}
+function stopDiscovery(): void {
+  if (discoveryTimer) clearInterval(discoveryTimer);
+  discoveryTimer = null;
+  discovery.stop();
+}
+
+ipcMain.handle('lan:host', (_event, name: string) => hostServer(name));
+ipcMain.handle('lan:discover-start', (event) => startDiscovery(event.sender));
+ipcMain.handle('lan:discover-stop', () => stopDiscovery());
 ipcMain.handle('assets:materials', () => JSON.parse(readFileSync(join(resolveAssetsDir(), 'materials', 'materials.json'), 'utf8')));
+ipcMain.handle('assets:characters', () => CHARACTER_IDS.map((id) => loadCharacterStats(resolveAssetsDir(), id)));
 ipcMain.handle('assets:map', (_event, mapId: string): MapFiles => {
   const dir = resolveAssetsDir();
   const { definition, terrain } = readMapFiles(dir, mapId);
@@ -67,6 +92,7 @@ void app.whenReady().then(() => {
 });
 
 app.on('window-all-closed', () => {
+  stopDiscovery();
   server?.kill();
   app.quit();
 });

+ 20 - 2
src/preload/api.ts

@@ -1,5 +1,6 @@
 // Typed API exposed to the renderer by the preload script. Type-only: shared by preload and renderer.
 import type { RgbaImage } from '../shared/maps/loader';
+import type { Phase } from '../shared/protocol';
 
 export interface MapFiles {
   /** Raw map.json, validated by the renderer with shared/maps/loader. */
@@ -13,13 +14,30 @@ export interface HostResult {
   port: number;
 }
 
+/** A game seen on the LAN. */
+export interface LanGame {
+  serverId: string;
+  name: string;
+  mapId: string;
+  players: number;
+  maxPlayers: number;
+  phase: Phase;
+  version: number;
+  address: string;
+  port: number;
+}
+
 export interface LanApi {
-  /** Starts the local authoritative server and resolves once it listens. */
-  host(): Promise<HostResult>;
+  /** Starts the local authoritative server (once) and resolves once it listens. */
+  host(name: string): Promise<HostResult>;
+  /** Starts listening for LAN games; `onGames` receives the full list about once per second. Returns a stop function. */
+  discover(onGames: (games: LanGame[]) => void): () => void;
 }
 
 export interface AssetsApi {
   materials(): Promise<unknown>;
+  /** Raw character.json of every playable character. */
+  characters(): Promise<unknown[]>;
   map(mapId: string): Promise<MapFiles>;
 }
 

+ 13 - 3
src/preload/index.ts

@@ -1,12 +1,22 @@
-import { contextBridge, ipcRenderer } from 'electron';
-import type { AssetsApi, LanApi } from './api';
+import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron';
+import type { AssetsApi, LanApi, LanGame } from './api';
 
 const lan: LanApi = {
-  host: () => ipcRenderer.invoke('lan:host'),
+  host: (name) => ipcRenderer.invoke('lan:host', name),
+  discover: (onGames) => {
+    const listener = (_event: IpcRendererEvent, games: LanGame[]): void => onGames(games);
+    ipcRenderer.on('lan:games', listener);
+    void ipcRenderer.invoke('lan:discover-start');
+    return () => {
+      ipcRenderer.removeListener('lan:games', listener);
+      void ipcRenderer.invoke('lan:discover-stop');
+    };
+  },
 };
 
 const assets: AssetsApi = {
   materials: () => ipcRenderer.invoke('assets:materials'),
+  characters: () => ipcRenderer.invoke('assets:characters'),
   map: (mapId) => ipcRenderer.invoke('assets:map', mapId),
 };
 

+ 104 - 0
src/renderer/characters/painters.ts

@@ -178,7 +178,111 @@ function darken(color: number, k: number): number {
   return (Math.round((color >> 16) * k) << 16) | (Math.round(((color >> 8) & 0xff) * k) << 8) | Math.round((color & 0xff) * k);
 }
 
+/** Mamie Tricot: lilac dress, pink shawl, grey bun skewered with knitting needles, round glasses. */
+export const paintMamie: Painter = (g, r, pose) => {
+  const step = pose.moving && pose.grounded ? Math.sin(pose.walk) : 0;
+  foot(g, -0.35 * r - step * 0.15 * r, 0.93 * r, r, 0x8a5fc9, pose.ink);
+
+  // Bun with crossed needles (behind the head).
+  g.moveTo(-0.75 * r, -1.35 * r).lineTo(0.05 * r, -0.85 * r).moveTo(-0.65 * r, -0.8 * r).lineTo(0.0 * r, -1.4 * r).stroke({ width: pose.ink * 0.8, color: 0xc0c8d0 });
+  g.circle(-0.75 * r, -1.35 * r, 0.07 * r).fill(0xff6f91);
+  g.circle(0.0 * r, -1.4 * r, 0.07 * r).fill(0x4dc4ff);
+  g.circle(-0.32 * r, -1.08 * r, 0.3 * r).fill(0xe8e8f0).stroke({ width: pose.ink, color: INK });
+
+  // Dress, face, hair cap.
+  g.circle(0, 0, r).fill(0xb18cff).stroke({ width: pose.ink, color: INK });
+  g.ellipse(0.18 * r, -0.2 * r, 0.68 * r, 0.6 * r).fill(0xffd9b8);
+  g.ellipse(-0.1 * r, -0.72 * r, 0.85 * r, 0.38 * r).fill(0xe8e8f0).stroke({ width: pose.ink * 0.7, color: INK });
+  for (let i = 0; i < 4; i++) g.moveTo(-0.7 * r + i * 0.3 * r, -0.8 * r).quadraticCurveTo(-0.6 * r + i * 0.3 * r, -0.6 * r, -0.5 * r + i * 0.3 * r, -0.75 * r).stroke({ width: pose.ink * 0.4, color: 0xa0a8b0 });
+
+  // Shawl draped over the shoulders.
+  g.poly([-0.95 * r, 0.05 * r, 0.9 * r, 0.25 * r, 0.3 * r, 0.75 * r, -0.6 * r, 0.6 * r]).fill(0xff8fab).stroke({ width: pose.ink * 0.8, color: INK });
+  for (let i = 0; i < 3; i++) g.circle(-0.4 * r + i * 0.35 * r, 0.42 * r, 0.06 * r).fill(0xffffff);
+
+  eyes(
+    g,
+    pose,
+    [
+      [0.2 * r, -0.22 * r],
+      [0.56 * r, -0.2 * r],
+    ],
+    0.12 * r,
+  );
+  // Round glasses.
+  for (const ex of [0.2, 0.56]) g.circle(ex * r, -0.21 * r, 0.19 * r).stroke({ width: pose.ink * 0.6, color: INK });
+  g.moveTo(0.39 * r, -0.22 * r).lineTo(0.37 * r, -0.22 * r).stroke({ width: pose.ink * 0.6, color: INK });
+  g.circle(0.68 * r, 0.02 * r, 0.11 * r).fill({ color: 0xff3b6b, alpha: 0.4 });
+  if (pose.attack) {
+    g.circle(0.42 * r, 0.1 * r, 0.08 * r).fill(0x5a1e1e);
+    // Needles poking forward.
+    g.moveTo(0.75 * r, 0.25 * r).lineTo(1.55 * r, 0.1 * r).moveTo(0.75 * r, 0.32 * r).lineTo(1.5 * r, 0.3 * r).stroke({ width: pose.ink * 0.7, color: 0xc0c8d0 });
+  } else {
+    g.moveTo(0.3 * r, 0.08 * r).quadraticCurveTo(0.45 * r, 0.16 * r, 0.6 * r, 0.06 * r).stroke({ width: pose.ink * 0.6, color: INK, cap: 'round' });
+  }
+  if (pose.special) {
+    // Arm flung forward, a fresh ball of yarn.
+    g.circle(1.05 * r, -0.1 * r, 0.25 * r).fill(0x9b6bd9).stroke({ width: pose.ink * 0.7, color: INK });
+    g.moveTo(0.9 * r, -0.2 * r).quadraticCurveTo(1.05 * r, 0, 1.2 * r, -0.2 * r).stroke({ width: pose.ink * 0.4, color: INK });
+  }
+  foot(g, 0.35 * r + step * 0.15 * r, 0.93 * r, r, 0x8a5fc9, pose.ink);
+  stars(g, r, pose);
+};
+
+/** Pyromanchot: a penguin with a red headband and a fizzing fuse; lies flat during the belly slide. */
+export const paintPyromanchot: Painter = (g, r, pose) => {
+  const black = 0x2a2a3a;
+  const orange = 0xff9a2e;
+  const spark = Math.sin(pose.time * 30) > 0;
+  if (pose.special) {
+    // Belly slide: flat, beak first, speed lines behind.
+    for (let i = 0; i < 3; i++) g.moveTo(-1.9 * r, (0.05 + i * 0.25) * r).lineTo(-1.35 * r, (0.05 + i * 0.25) * r).stroke({ width: pose.ink * 0.6, color: INK });
+    g.ellipse(0, 0.35 * r, 1.25 * r, 0.65 * r).fill(black).stroke({ width: pose.ink, color: INK });
+    g.ellipse(0.05 * r, 0.62 * r, 1.0 * r, 0.32 * r).fill(0xffffff);
+    g.poly([1.15 * r, 0.1 * r, 1.6 * r, 0.25 * r, 1.15 * r, 0.42 * r]).fill(orange).stroke({ width: pose.ink * 0.7, color: INK });
+    eyes(g, { ...pose, lookX: 1, lookY: 0 }, [[0.85 * r, 0.05 * r]], 0.15 * r);
+    g.rect(-0.2 * r, -0.28 * r, 0.9 * r, 0.16 * r).fill(0xe0123a);
+    return;
+  }
+  const step = pose.moving && pose.grounded ? Math.sin(pose.walk) : 0;
+  const waddle = pose.moving ? Math.sin(pose.walk) * 0.08 : 0;
+  foot(g, -0.3 * r - step * 0.12 * r, 0.95 * r, r, orange, pose.ink);
+
+  // Fuse sticking out of the headband, fizzing.
+  g.moveTo(-0.6 * r, -0.62 * r).quadraticCurveTo(-1.0 * r, -0.9 * r, -0.85 * r, -1.25 * r).stroke({ width: pose.ink * 0.6, color: INK });
+  if (spark) {
+    g.circle(-0.85 * r, -1.28 * r, 0.12 * r).fill(0xffe14d);
+    g.circle(-0.85 * r, -1.28 * r, 0.06 * r).fill(0xffffff);
+  }
+
+  g.ellipse(0, 0, r * (1 - waddle * 0.3), r * 1.05).fill(black).stroke({ width: pose.ink, color: INK });
+  g.ellipse(0.25 * r, 0.18 * r, 0.6 * r, 0.75 * r).fill(0xffffff);
+  // Flippers.
+  const raise = pose.attack ? -0.6 : 0;
+  g.poly(ellipsePoly(0.75 * r, (0.15 + raise * 0.4) * r, 0.18 * r, 0.42 * r, 0.5 + raise)).fill(black).stroke({ width: pose.ink * 0.8, color: INK });
+  if (pose.attack) {
+    // A firecracker in the flipper.
+    g.roundRect(0.85 * r, -0.65 * r, 0.18 * r, 0.45 * r, 0.05 * r).fill(0xe0123a).stroke({ width: pose.ink * 0.6, color: INK });
+    if (spark) g.circle(0.94 * r, -0.72 * r, 0.09 * r).fill(0xffe14d);
+  }
+  // Headband.
+  g.rect(-0.95 * r, -0.68 * r, 1.85 * r, 0.2 * r).fill(0xe0123a).stroke({ width: pose.ink * 0.6, color: INK });
+  eyes(
+    g,
+    pose,
+    [
+      [0.28 * r, -0.3 * r],
+      [0.6 * r, -0.28 * r],
+    ],
+    0.15 * r,
+  );
+  g.poly([0.85 * r, -0.12 * r, 1.35 * r, 0.0 * r, 0.85 * r, 0.12 * r]).fill(orange).stroke({ width: pose.ink * 0.7, color: INK });
+  foot(g, 0.3 * r + step * 0.12 * r, 0.95 * r, r, orange, pose.ink);
+  stars(g, r, pose);
+};
+
 export const PAINTERS: Record<string, Painter> = {
   castor: paintCastor,
+  mamie: paintMamie,
+  pyromanchot: paintPyromanchot,
   generic: paintGeneric,
 };

+ 4 - 0
src/renderer/config.ts

@@ -24,6 +24,10 @@ export const HIT_SHAKE = 8;
 export const MERGE_SHAKE = 6;
 export const CRUSH_SHAKE = 12;
 export const PLAYER_SPLAT_COLOR = 0xff6f91;
+export const CUSTARD_COLOR = 0xf7d774;
+export const CUSTARD_DARK = 0xd9a93a;
+export const EXPLOSION_SHAKE = 14;
+export const WHISK_SHAKE = 10;
 export const FREEZE_FRAME_MS = 50;
 export const PARTICLES_PER_100_PX = 6;
 export const PARTICLE_MAX = 700;

+ 13 - 1
src/renderer/entities/PlayerView.ts

@@ -2,6 +2,7 @@ import { Container, Graphics, Text } from 'pixi.js';
 import { Anim } from '../../shared/characters';
 import type { PlayerInfo, PlayerState } from '../../shared/protocol';
 import { PAINTERS, paintGeneric, type Painter, type Pose } from '../characters/painters';
+import { paintItem } from './RoundViews';
 import { OUTLINE_COLOR, OUTLINE_WIDTH, PLAYER_COLORS, SQUASH_RECOVERY } from '../config';
 
 /** Max size the fat ratio is normalized against (castor maxSize is in its JSON; this only drives the cheeks). */
@@ -17,6 +18,8 @@ export interface PlayerEvents {
 export class PlayerView {
   readonly container = new Container();
   private readonly body = new Graphics();
+  /** Carried item (candle) held up next to the character. */
+  private readonly held = new Graphics();
   private readonly name: Text;
   private readonly paint: Painter;
   private readonly color: number;
@@ -35,7 +38,8 @@ export class PlayerView {
       style: { fontFamily: 'Comic Sans MS', fontSize: 15, fill: this.color, fontWeight: 'bold', stroke: { color: OUTLINE_COLOR, width: 4 } },
     });
     this.name.anchor.set(0.5, 1);
-    this.container.addChild(this.body, this.name);
+    this.held.scale.set(0.8);
+    this.container.addChild(this.body, this.held, this.name);
   }
 
   /** Draws a static pose (menu portraits). */
@@ -47,6 +51,14 @@ export class PlayerView {
     this.time += dt;
     const size = state.size;
     this.container.position.set(state.x, state.y);
+    // In the custard, waiting for the spoon.
+    this.container.visible = (state.anim & Anim.Dead) === 0;
+    this.held.clear();
+    if (state.item) {
+      paintItem(this.held, state.item, false, this.time);
+      this.held.position.set(-state.facing * size * 0.95, -size * 0.35);
+      this.held.rotation = -state.facing * 0.4;
+    }
 
     // Landing squashes, jumping stretches.
     const events: PlayerEvents = { landed: false, landingSpeed: 0, stunnedNow: false };

+ 174 - 0
src/renderer/entities/RoundViews.ts

@@ -0,0 +1,174 @@
+import { Container, Graphics } from 'pixi.js';
+import type { CherryState, EntityKind, ItemState } from '../../shared/protocol';
+import { CUSTARD_COLOR, CUSTARD_DARK, OUTLINE_COLOR, OUTLINE_WIDTH } from '../config';
+
+const INK = OUTLINE_COLOR;
+const W = OUTLINE_WIDTH;
+
+/** The rising custard: a wobbly yellow sea with a felt outline and lazy bubbles. Drawn above players. */
+export class CustardView {
+  readonly graphics = new Graphics();
+  private time = 0;
+
+  update(level: number, mapWidth: number, mapHeight: number, dt: number, rush: boolean): void {
+    this.time += dt * (rush ? 2.2 : 1);
+    const g = this.graphics;
+    g.clear();
+    const bottom = mapHeight + 400;
+    const pts: number[] = [];
+    for (let x = -40; x <= mapWidth + 40; x += 16) {
+      const wave = Math.sin(x / 70 + this.time * 2) * 6 + Math.sin(x / 23 - this.time * 3.1) * 2.5;
+      pts.push(x, level + wave);
+    }
+    pts.push(mapWidth + 40, bottom, -40, bottom);
+    g.poly(pts).fill(CUSTARD_COLOR);
+    // Darker depth band and the felt line on the surface.
+    g.rect(-40, level + 40, mapWidth + 80, bottom - level).fill({ color: CUSTARD_DARK, alpha: 0.35 });
+    const surface = pts.slice(0, pts.length - 4);
+    g.moveTo(surface[0], surface[1]);
+    for (let i = 2; i < surface.length; i += 2) g.lineTo(surface[i], surface[i + 1]);
+    g.stroke({ width: W + 1, color: INK });
+    // Shine and bubbles.
+    for (let i = 0; i < 18; i++) {
+      const bx = ((i * 211 + this.time * 30 * ((i % 3) + 1)) % (mapWidth + 80)) - 40;
+      const by = level + 14 + ((i * 37) % 60);
+      const r = 3 + (i % 4) * 1.5;
+      g.circle(bx, by, r).fill({ color: 0xfffbe0, alpha: 0.7 }).stroke({ width: 1.5, color: CUSTARD_DARK });
+    }
+  }
+}
+
+/** The cherry, with a stem and a leaf, bobbing a little; glows when someone holds it. */
+export class CherryView {
+  readonly graphics = new Graphics();
+  private time = 0;
+
+  update(cherry: CherryState | null, dt: number): void {
+    this.time += dt;
+    const g = this.graphics;
+    g.clear();
+    if (!cherry) return;
+    const bob = cherry.holder ? Math.sin(this.time * 6) * 3 : 0;
+    const x = cherry.x;
+    const y = cherry.y + bob;
+    if (cherry.holder) g.circle(x, y, 22 + Math.sin(this.time * 8) * 2).fill({ color: 0xffe14d, alpha: 0.35 });
+    g.moveTo(x + 2, y - 10).quadraticCurveTo(x + 6, y - 22, x + 12, y - 26).stroke({ width: 3, color: 0x4a7a2a });
+    g.ellipse(x + 15, y - 24, 8, 4).fill(0x7ccf5a).stroke({ width: 2, color: INK });
+    g.circle(x, y, 12).fill(0xe0123a).stroke({ width: W, color: INK });
+    g.ellipse(x - 4, y - 4, 4, 3).fill({ color: 0xffffff, alpha: 0.75 });
+  }
+}
+
+/** Draws one item in local coordinates (origin at its center). */
+export function paintItem(g: Graphics, kind: EntityKind, lit: boolean, time: number): void {
+  if (kind === 'firecracker') {
+    g.roundRect(-4, -11, 8, 20, 2).fill(0xe0123a).stroke({ width: 2, color: INK });
+    g.rect(-4, -3, 8, 4).fill(0xffe14d);
+    g.moveTo(0, -11).quadraticCurveTo(4, -15, 2, -19).stroke({ width: 1.5, color: INK });
+    if (Math.sin(time * 45) > -0.3) {
+      g.circle(2, -20, 3.5).fill(0xffe14d);
+      g.circle(2, -20, 1.6).fill(0xffffff);
+    }
+  } else if (kind === 'yarn') {
+    g.circle(0, 0, 10).fill(0x9b6bd9).stroke({ width: 2.5, color: INK });
+    g.moveTo(-8, -4).quadraticCurveTo(0, -10, 8, -3).moveTo(-9, 2).quadraticCurveTo(0, -4, 9, 3).moveTo(-6, 7).quadraticCurveTo(0, 2, 6, 8).stroke({ width: 1.5, color: 0x6e44b0 });
+  } else if (kind === 'candle') {
+    g.roundRect(-5, -14, 10, 26, 3).fill(0xffffff).stroke({ width: 2.5, color: INK });
+    for (let i = 0; i < 3; i++) g.rect(-5, -12 + i * 9, 10, 4).fill(0xff6f91);
+    g.moveTo(0, -14).lineTo(0, -19).stroke({ width: 2, color: INK });
+    if (lit) {
+      const f = 1 + Math.sin(time * 40) * 0.2;
+      g.ellipse(0, -24, 4 * f, 7 * f).fill(0xffb02e).stroke({ width: 1.5, color: INK });
+      g.ellipse(0, -22, 2, 3.5).fill(0xfff3a0);
+    }
+  } else if (kind === 'smarties') {
+    g.roundRect(-14, -6, 28, 12, 6).fill(0xfff6e4).stroke({ width: 2.5, color: INK });
+    const colors = [0xff3b6b, 0xffe14d, 0x4dc4ff, 0x9be15d, 0xb18cff];
+    colors.forEach((c, i) => g.circle(-10 + i * 5, 0, 3.4).fill(c).stroke({ width: 1, color: INK }));
+  } else {
+    g.roundRect(-3, 2, 6, 14, 2).fill(0x9c6b3a).stroke({ width: 2, color: INK });
+    for (const k of [-1, 0, 1]) g.ellipse(k * 3, -8, 5 - Math.abs(k), 11).stroke({ width: 2, color: 0x8899aa });
+    if (Math.sin(time * 25) > 0) {
+      g.moveTo(-10, -18).lineTo(-6, -12).lineTo(-11, -10).stroke({ width: 2, color: 0x4dc4ff });
+      g.moveTo(10, -16).lineTo(6, -11).lineTo(11, -8).stroke({ width: 2, color: 0x4dc4ff });
+    }
+  }
+}
+
+/** Items lying around or flying. */
+export class ItemsView {
+  readonly container = new Container();
+  private readonly views = new Map<number, Graphics>();
+  private time = 0;
+
+  update(items: Map<number, ItemState>, dt: number): void {
+    this.time += dt;
+    for (const [id, g] of this.views) {
+      if (items.has(id)) continue;
+      g.destroy();
+      this.views.delete(id);
+    }
+    for (const [id, item] of items) {
+      let g = this.views.get(id);
+      if (!g) {
+        g = new Graphics();
+        this.views.set(id, g);
+        this.container.addChild(g);
+      }
+      g.clear();
+      // A gentle sparkle so pickups catch the eye.
+      if (!item.lit) g.circle(0, 0, 18 + Math.sin(this.time * 5 + id) * 2).fill({ color: 0xffffff, alpha: 0.35 });
+      paintItem(g, item.kind, item.lit, this.time);
+      g.position.set(item.x, item.y);
+      g.rotation = item.angle;
+    }
+  }
+
+  clear(): void {
+    for (const g of this.views.values()) g.destroy();
+    this.views.clear();
+  }
+}
+
+interface Spoon {
+  g: Graphics;
+  x: number;
+  y: number;
+  age: number;
+}
+
+const SPOON_LIFE = 0.8;
+
+/** The spoon catapult flicking a player back onto the cake. */
+export class SpoonsView {
+  readonly container = new Container();
+  private spoons: Spoon[] = [];
+
+  spawn(x: number, y: number): void {
+    const g = new Graphics();
+    this.container.addChild(g);
+    this.spoons.push({ g, x, y, age: 0 });
+  }
+
+  update(dt: number): void {
+    this.spoons = this.spoons.filter((s) => {
+      s.age += dt;
+      if (s.age > SPOON_LIFE) {
+        s.g.destroy();
+        return false;
+      }
+      const t = s.age / SPOON_LIFE;
+      // Flick: the bowl swings up fast, then sinks back.
+      const angle = t < 0.25 ? -0.2 - (t / 0.25) * 1.4 : -1.6 + (t - 0.25) * 2;
+      const g = s.g;
+      g.clear();
+      g.roundRect(0, -5, 90, 10, 5).fill(0xc9d3dd).stroke({ width: W, color: INK });
+      g.ellipse(100, 0, 22, 15).fill(0xdfe7ee).stroke({ width: W, color: INK });
+      g.ellipse(96, -4, 8, 5).fill({ color: 0xffffff, alpha: 0.8 });
+      g.position.set(s.x - 100 * Math.cos(angle), s.y + 10);
+      g.rotation = angle;
+      g.alpha = t > 0.8 ? (1 - t) / 0.2 : 1;
+      return true;
+    });
+  }
+}

+ 98 - 5
src/renderer/i18n/fr.ts

@@ -14,18 +14,111 @@ export const fr = {
   rejectedCharacter: 'Ce personnage n’existe pas sur ce serveur.',
   loadError: (msg: string) => `Impossible de charger la partie : ${msg}`,
   help: {
-    generic: 'Q/D : courir · Espace/Z : sauter · Clic gauche : croquer le décor',
-    castor: 'Q/D : courir · Espace/Z : sauter · Clic gauche : coup de dents · Clic droit (maintenu) : manger le décor',
+    mamie: 'Q/D : courir · Espace/Z : sauter · Clic gauche : aiguilles · Clic droit : lancer une pelote · F : lancer la bougie',
+    pyromanchot: 'Q/D : courir · Espace/Z : sauter · Clic gauche : pétard · Clic droit : glissade explosive · F : lancer la bougie',
+    generic: 'Q/D : courir · Espace/Z : sauter · Clic gauche : croquer le décor · F : lancer la bougie',
+    castor: 'Q/D : courir · Espace/Z : sauter · Clic gauche : coup de dents · Clic droit (maintenu) : manger · F : lancer la bougie',
   } as Record<string, string>,
   fps: (n: number) => `${n} FPS`,
+  browser: {
+    title: 'Les goûters du coin',
+    searching: 'On renifle le réseau… Aucune partie pour l’instant.',
+    host: 'Créer une partie',
+    join: 'Rejoindre',
+    back: 'Retour',
+    players: (n: number, max: number) => `${n}/${max} gourmands`,
+    phase: { lobby: 'à l’échauffement', playing: 'en pleine baston' } as Record<string, string>,
+    incompatible: 'version différente',
+    full: 'complet',
+    manualLabel: 'Ou par adresse :',
+    manualPlaceholder: '192.168.1.42',
+    gameName: (name: string) => `Goûter de ${name}`,
+  },
+  lobby: {
+    title: 'Échauffement',
+    hint: 'Croquez le décor en attendant tout le monde !',
+    ready: 'Je suis prêt !',
+    notReady: 'Attends, pas encore !',
+    countdown: (n: number) => `Ça commence dans ${n}…`,
+    waiting: (n: number) => `En attente de ${n} gourmand${n > 1 ? 's' : ''}`,
+    started: 'C’est parti !',
+  },
+  rotation: {
+    title: 'Cartes de la partie',
+    modes: { all: 'Toutes, dans l’ordre', random: 'Toutes, au hasard', selection: 'Ma sélection' } as Record<string, string>,
+    hostOnly: 'C’est l’hôte (👑) qui choisit.',
+  },
+  pick: {
+    you: 'Tu es dernier : à toi de choisir la prochaine carte !',
+    other: (name: string) => `${name} est dernier et choisit la prochaine carte…`,
+    picked: (map: string) => `Prochaine carte : ${map}`,
+  },
+  desync: 'Oups, ton gâteau ne ressemble plus à celui du serveur (désynchronisation).',
+  hud: {
+    round: (n: number, total: number) => `Manche ${n}/${total}`,
+    warmup: 'Échauffement',
+    rush: 'LA CRÈME MONTE !',
+    candleHint: 'F : lancer la bougie !',
+  },
+  items: { candle: 'Bougie !', smarties: 'Smarties !', whisk: 'Fouet électrique !', cherry: 'La cerise !' } as Record<string, string>,
+  fxWords: {
+    splash: ['PLOUF !', 'SPLOTCH !', 'GLOUB !'],
+    explosion: ['BOUM !', 'KABOUM !', 'BADABOUM !'],
+    whisk: ['BZZZT !', 'VRRRRR !'],
+    drop: ['OUPS !', 'AÏE !', 'NOOON !'],
+  },
+  results: {
+    roundTitle: (n: number, total: number) => `Fin de la manche ${n}/${total}`,
+    matchTitle: 'Le grand classement',
+    player: 'Gourmand',
+    round: 'Manche',
+    total: 'Total',
+    next: (s: number) => `Manche suivante dans ${s} s…`,
+    lobby: (s: number) => `Retour à l’échauffement dans ${s} s… (« Je suis prêt ! » pour rejouer)`,
+    trophies: 'Les trophées',
+    noTrophy: 'Personne n’a rien fait de remarquable. Bravo.',
+    winner: (name: string) => `${name} remporte le goûter !`,
+  },
+  trophies: {
+    glutton: { name: 'Le Glouton', desc: (v: number) => `${v.toLocaleString('fr-FR')} pixels de gâteau engloutis` },
+    kamikaze: { name: 'Le Kamikaze', desc: (v: number) => `${v} plongeon${v > 1 ? 's' : ''} dans la crème` },
+    developer: { name: 'Le Promoteur Immobilier', desc: (v: number) => `${v} pan${v > 1 ? 's' : ''} de gâteau effondré${v > 1 ? 's' : ''}` },
+    notMyFault: { name: 'Pas Sa Faute', desc: (v: number) => `${v} coup${v > 1 ? 's' : ''} et écrasement${v > 1 ? 's' : ''} encaissés` },
+    pyromaniac: { name: 'L’Artificier', desc: (v: number) => `${v} bougie${v > 1 ? 's' : ''} lancée${v > 1 ? 's' : ''}` },
+    cherryPicker: { name: 'Le Cueilleur', desc: (v: number) => `${v} s avec la cerise` },
+  } as Record<string, { name: string; desc: (v: number) => string }>,
   defaultName: 'Gourmand',
   characters: {
-    generic: { name: 'Le Testeur', desc: 'Court, saute, croque. Rien de plus, rien de moins.' },
     castor: {
       name: 'Castor Glouton',
-      desc: 'Mange le décor en avançant. Mais plus il mange, plus il grossit… jusqu’à passer à travers le sol.',
+      desc: 'Creuse en mangeant tout ce qui passe.',
+      attack: 'Coup de dents',
+      special: 'Mange le décor en avançant (maintenu)',
+      flaw: 'Grossit en mangeant, jusqu’à passer à travers le sol',
+    },
+    mamie: {
+      name: 'Mamie Tricot',
+      desc: 'Construit des ponts et des filets en laine.',
+      attack: 'Aiguilles : pousse peu, assomme longtemps',
+      special: 'Pelote : un fil de laine qui s’accroche où il touche',
+      flaw: 'Lente, et ses constructions brûlent',
+    },
+    pyromanchot: {
+      name: 'Pyromanchot',
+      desc: 'Un manchot qui adore les feux d’artifice.',
+      attack: 'Pétards qui explosent au contact',
+      special: 'Glissade sur le ventre, explosion à l’arrivée',
+      flaw: '1 pétard sur 3 lui explose dessus',
+    },
+    generic: {
+      name: 'Le Testeur',
+      desc: 'Court, saute, croque. Rien de plus.',
+      attack: 'Croque le décor',
+      special: '—',
+      flaw: 'Aucun charisme',
     },
-  } as Record<string, { name: string; desc: string }>,
+  } as Record<string, { name: string; desc: string; attack: string; special: string; flaw: string }>,
+  stats: { speed: 'Vitesse', jump: 'Saut', mass: 'Poids' },
   /** Comic-book sound effects shown on impacts. */
   onomatopoeia: {
     crunch: ['CROC !', 'CRUNCH !', 'SCRONCH !', 'CRAC !'],

+ 1 - 0
src/renderer/input.ts

@@ -12,6 +12,7 @@ const KEYMAP: Record<string, number> = {
   KeyS: Button.Down,
   ArrowDown: Button.Down,
   KeyE: Button.Special,
+  KeyF: Button.Use,
 };
 
 /** Tracks keyboard/mouse state as a button bitmask plus the mouse position in screen pixels. */

+ 196 - 32
src/renderer/main.ts

@@ -1,10 +1,10 @@
 import 'pixi.js/unsafe-eval'; // Pixi without eval, required by our Content-Security-Policy
 import { Application, CanvasSource, Container, ImageSource, Sprite, Texture } from 'pixi.js';
-import { Anim, CHARACTER_IDS } from '../shared/characters';
+import { Anim, CHARACTER_IDS, parseCharacterStats } from '../shared/characters';
 import { DEFAULT_CHARACTER_ID, INTERPOLATION_DELAY_MS, PROTOCOL_VERSION } from '../shared/constants';
 import { buildTerrain, parseMapDefinition } from '../shared/maps/loader';
 import { parseHexColor, parseMaterials, type MaterialRegistry } from '../shared/materials';
-import { hello, type ChunkState, type PlayerInfo, type PlayerState, type ServerMessage } from '../shared/protocol';
+import { hello, type ChunkInfo, type ChunkState, type FxEvent, type PlayerInfo, type PlayerState, type ServerMessage } from '../shared/protocol';
 import type { TerrainBitmap } from '../shared/terrain/bitmap';
 import { applyTerrainEvent, type SequencedEvent, type TerrainEvent } from '../shared/terrain/events';
 import { rleDecode } from '../shared/terrain/rle';
@@ -13,6 +13,8 @@ import {
   CAMERA_FOLLOW_SPEED,
   CAMERA_VIEW_HEIGHT,
   CRUSH_SHAKE,
+  CUSTARD_COLOR,
+  EXPLOSION_SHAKE,
   FREEZE_FRAME_MS,
   HIT_SHAKE,
   INPUT_SEND_HZ,
@@ -25,9 +27,11 @@ import {
   SHAKE_DECAY,
   SHAKE_MAX,
   SHAKE_PER_PIXEL,
+  WHISK_SHAKE,
 } from './config';
 import { ChunkView } from './entities/ChunkView';
 import { PlayerView } from './entities/PlayerView';
+import { CherryView, CustardView, ItemsView, SpoonsView } from './entities/RoundViews';
 import { Particles } from './fx/Particles';
 import { Popups } from './fx/Popups';
 import { fr } from './i18n/fr';
@@ -35,7 +39,10 @@ import { InputTracker } from './input';
 import { Connection } from './net/connection';
 import { SnapshotBuffer } from './net/interpolation';
 import { TerrainView } from './terrain/TerrainView';
-import { showMenu } from './ui/menu';
+import { showBrowser } from './ui/browser';
+import { ResultsScreen, RoundHud } from './ui/hud';
+import { LobbyPanel } from './ui/lobbyPanel';
+import { showMenu, type MenuChoice } from './ui/menu';
 
 const PORTRAIT_RADIUS = 34;
 const EATING_POPUP_RANGE = 120;
@@ -47,24 +54,22 @@ const setStatus = (text: string): void => {
   statusEl.textContent = text;
 };
 
+/** Everything tied to one loaded map. Rebuilt when a match starts. */
 interface World {
   materials: MaterialRegistry;
   terrain: TerrainBitmap;
   view: TerrainView;
+  background: Sprite;
   lastSeq: number;
 }
 
-async function loadWorld(mapId: string, materials: MaterialRegistry, root: Container): Promise<World> {
+async function loadWorld(mapId: string, materials: MaterialRegistry): Promise<World> {
   const files = await window.assets.map(mapId);
   const def = parseMapDefinition(files.definition, mapId);
   const terrain = buildTerrain(def, files.terrain, materials);
-
   const bitmap = await createImageBitmap(new Blob([files.background as BlobPart], { type: 'image/png' }));
-  root.addChild(new Sprite(new Texture({ source: new ImageSource({ resource: bitmap }) })));
-
-  const view = new TerrainView(terrain, materials);
-  root.addChild(view.container);
-  return { materials, terrain, view, lastSeq: 0 };
+  const background = new Sprite(new Texture({ source: new ImageSource({ resource: bitmap }) }));
+  return { materials, terrain, view: new TerrainView(terrain, materials), background, lastSeq: 0 };
 }
 
 /** Screen-space warm vignette drawn over the game. */
@@ -94,14 +99,30 @@ function makePortraits(app: Application): Map<string, HTMLCanvasElement> {
   return out;
 }
 
+/** Title menu then game browser, until the player picks a game to host or join. */
+async function chooseGame(app: Application): Promise<{ choice: MenuChoice; address: string; port: number }> {
+  const portraits = makePortraits(app);
+  const stats = new Map((await window.assets.characters()).map((raw) => parseCharacterStats(raw)).map((st) => [st.id, st]));
+  for (;;) {
+    const choice = await showMenu(CHARACTER_IDS, DEFAULT_CHARACTER_ID, portraits, stats);
+    const target = await showBrowser();
+    if (target.mode === 'back') continue;
+    if (target.mode === 'join') return { choice, address: target.address, port: target.port };
+    setStatus(fr.connecting);
+    const { port } = await window.lan.host(fr.browser.gameName(choice.name));
+    return { choice, address: '127.0.0.1', port };
+  }
+}
+
 async function start(): Promise<void> {
   const app = new Application();
   const host = document.getElementById('game')!;
   await app.init({ resizeTo: window, background: 0xfff1d6, antialias: true });
   host.appendChild(app.canvas);
 
-  const choice = await showMenu(CHARACTER_IDS, DEFAULT_CHARACTER_ID, makePortraits(app));
+  const { choice, address, port } = await chooseGame(app);
   helpEl.textContent = fr.help[choice.characterId] ?? '';
+  setStatus(fr.connecting);
 
   const camera = new Container();
   const worldRoot = new Container();
@@ -112,18 +133,40 @@ async function start(): Promise<void> {
   const popups = new Popups();
   const playersLayer = new Container();
   const chunksLayer = new Container();
+  const itemsView = new ItemsView();
+  const cherryView = new CherryView();
+  const custardView = new CustardView();
+  const spoonsView = new SpoonsView();
+  // Map-independent layers always sit above the map ones (background, terrain).
+  // The custard covers players who sink into it; the spoon flicks out of it.
+  worldRoot.addChild(
+    chunksLayer,
+    itemsView.container,
+    playersLayer,
+    cherryView.graphics,
+    custardView.graphics,
+    spoonsView.container,
+    particles.graphics,
+    popups.container,
+  );
+  const hud = new RoundHud();
+  const results = new ResultsScreen((mapId) => conn.send({ t: 'pickMap', mapId }));
+  let round = 0;
+  let rounds = 0;
 
-  setStatus(fr.connecting);
-  const { port } = await window.lan.host();
   const materials = parseMaterials(await window.assets.materials());
 
   let world: World | null = null;
+  /** Bumped on every map (re)load, so a slow load never installs a stale world. */
+  let generation = 0;
   let localId = -1;
   let pendingEvents: SequencedEvent[] = [];
-  const infos = new Map<number, PlayerInfo>();
+  /** Server hash waiting for this client to reach the same event seq. */
+  let pendingHash: { seq: number; hash: number } | null = null;
+  let infos = new Map<number, PlayerInfo>();
   const views = new Map<number, PlayerView>();
   const chunkViews = new Map<number, ChunkView>();
-  const snapshots = new SnapshotBuffer();
+  let snapshots = new SnapshotBuffer();
   const input = new InputTracker(app.canvas);
   let states = new Map<number, PlayerState>();
   let shake = 0;
@@ -160,6 +203,18 @@ async function start(): Promise<void> {
     return m ? parseHexColor(m.color) : 0xffffff;
   };
 
+  /** Compares our bitmap with the server's once we have applied the same events (readme §9, M3). */
+  const checkHash = (): void => {
+    if (!world || !pendingHash || world.lastSeq !== pendingHash.seq) return;
+    const mine = world.terrain.hash();
+    if (mine !== pendingHash.hash) {
+      console.error(`[net] DESYNC at seq ${pendingHash.seq}: server ${pendingHash.hash}, client ${mine}`);
+      setStatus(fr.desync);
+      conn.send({ t: 'desync', seq: pendingHash.seq, hash: mine });
+    }
+    pendingHash = null;
+  };
+
   /**
    * Applies one terrain event in sequence. `live` is false while replaying history:
    * no effects, and no chunk sprites (chunks still falling come from the welcome message).
@@ -173,6 +228,7 @@ async function start(): Promise<void> {
     world.lastSeq = seq;
     const { removedByMaterial } = applyTerrainEvent(world.terrain, ev, world.materials);
     world.view.onEvent(ev);
+    checkHash();
 
     if (ev.kind === 'op') {
       if (!live) return;
@@ -206,24 +262,116 @@ async function start(): Promise<void> {
     popups.spawn(ev.x + ev.w / 2, ev.y, fr.onomatopoeia.thud, 30);
   };
 
+  /** Drops the current map and everything on it, then loads `mapId` and replays `history`. */
+  const resetWorld = (mapId: string, history: SequencedEvent[], chunks: ChunkInfo[]): void => {
+    const gen = ++generation;
+    if (world) {
+      world.background.destroy({ texture: true, textureSource: true });
+      itemsView.clear();
+      world.view.container.destroy({ children: true, texture: true, textureSource: true });
+    }
+    world = null;
+    pendingEvents = [];
+    pendingHash = null;
+    for (const id of [...chunkViews.keys()]) removeChunk(id);
+    for (const view of views.values()) view.destroy();
+    views.clear();
+    snapshots = new SnapshotBuffer();
+    setStatus(fr.loadingMap);
+    void loadWorld(mapId, materials)
+      .then((w) => {
+        if (gen !== generation) return; // superseded by a newer start
+        world = w;
+        worldRoot.addChildAt(w.background, 0);
+        worldRoot.addChildAt(w.view.container, 1);
+        for (const { seq, ev } of history) applyServerEvent(seq, ev, false);
+        for (const c of chunks) addChunk(c.id, rleDecode(c.mask, c.w * c.h), c.w, c.h, c.state);
+        const live = pendingEvents;
+        pendingEvents = [];
+        for (const { seq, ev } of live) applyServerEvent(seq, ev, true);
+        setStatus('');
+      })
+      .catch((err: unknown) => setStatus(fr.loadError(err instanceof Error ? err.message : String(err))));
+  };
+
+  /** One-shot cues from the server: splashes, spoons, explosions, pickups. */
+  const onFx = (ev: FxEvent): void => {
+    switch (ev.kind) {
+      case 'splash':
+        particles.burst(ev.x, ev.y, 16, CUSTARD_COLOR, 420);
+        popups.spawn(ev.x, ev.y - 30, fr.fxWords.splash, ev.id ? 36 : 26);
+        break;
+      case 'spoon':
+        spoonsView.spawn(ev.x, ev.y);
+        break;
+      case 'explosion':
+        particles.burst(ev.x, ev.y, 40, 0xffb02e, 650);
+        particles.burst(ev.x, ev.y, 20, 0xff6f91, 400);
+        particles.puff(ev.x, ev.y, 14, 0xfff3a0);
+        popups.spawn(ev.x, ev.y - ev.r, fr.fxWords.explosion, 48);
+        shake = Math.min(SHAKE_MAX, shake + EXPLOSION_SHAKE);
+        freezeUntil = performance.now() + FREEZE_FRAME_MS;
+        break;
+      case 'pickup':
+        popups.spawn(ev.x, ev.y - 20, [fr.items[ev.item] ?? ev.item], 28);
+        particles.burst(ev.x, ev.y, 10, 0xffe14d, 250);
+        break;
+      case 'cherryDrop':
+        popups.spawn(ev.x, ev.y - 40, fr.fxWords.drop, 32);
+        break;
+      case 'whisk':
+        shake = Math.min(SHAKE_MAX, shake + WHISK_SHAKE);
+        for (const s of states.values()) {
+          if (s.id !== ev.id) particles.burst(s.x, s.y, 8, 0x4dc4ff, 300);
+          else popups.spawn(s.x, s.y - s.size - 20, fr.fxWords.whisk, 40);
+        }
+        break;
+    }
+  };
+
+  const lobbyPanel = new LobbyPanel(
+    () => localId,
+    (ready) => conn.send({ t: 'ready', ready }),
+    (rotation) => conn.send({ t: 'rotation', rotation }),
+  );
+  let mapNames = new Map<string, string>();
+
   const onMessage = (msg: ServerMessage): void => {
     switch (msg.t) {
       case 'welcome':
         localId = msg.playerId;
-        msg.players.forEach((p) => infos.set(p.id, p));
-        setStatus(fr.loadingMap);
-        void loadWorld(msg.mapId, materials, worldRoot)
-          .then((w) => {
-            world = w;
-            worldRoot.addChild(chunksLayer, playersLayer, particles.graphics, popups.container);
-            for (const { seq, ev } of msg.events) applyServerEvent(seq, ev, false);
-            for (const c of msg.chunks) addChunk(c.id, rleDecode(c.mask, c.w * c.h), c.w, c.h, c.state);
-            const live = pendingEvents;
-            pendingEvents = [];
-            for (const { seq, ev } of live) applyServerEvent(seq, ev, true);
-            setStatus('');
-          })
-          .catch((err: unknown) => setStatus(fr.loadError(err instanceof Error ? err.message : String(err))));
+        round = msg.round;
+        rounds = msg.rounds;
+        infos = new Map(msg.players.map((p) => [p.id, p]));
+        resetWorld(msg.mapId, msg.events, msg.chunks);
+        break;
+      case 'start':
+        round = msg.round;
+        rounds = msg.rounds;
+        infos = new Map(msg.players.map((p) => [p.id, p]));
+        results.hide();
+        resetWorld(msg.mapId, [], []);
+        if (round === 0) break; // back to the warm-up: no fanfare
+        setStatus(fr.hud.round(round, rounds));
+        setTimeout(() => {
+          if (statusEl.textContent === fr.hud.round(round, rounds)) setStatus('');
+        }, 1500);
+        break;
+      case 'roundEnd':
+        results.showRound(msg, localId);
+        break;
+      case 'matchEnd':
+        results.showMatch(msg, localId);
+        break;
+      case 'fx':
+        onFx(msg.ev);
+        break;
+      case 'lobby':
+        lobbyPanel.update(msg);
+        mapNames = new Map(msg.maps.map((m) => [m.id, m.name]));
+        break;
+      case 'mapPicked':
+        results.showPicked(mapNames.get(msg.mapId) ?? msg.mapId);
         break;
       case 'reject':
         setStatus(
@@ -245,6 +393,10 @@ async function start(): Promise<void> {
       case 'terrain':
         applyServerEvent(msg.seq, msg.ev, true);
         break;
+      case 'hash':
+        pendingHash = { seq: msg.seq, hash: msg.hash };
+        checkHash();
+        break;
       case 'chunkRemoved':
         removeChunk(msg.id);
         break;
@@ -255,16 +407,19 @@ async function start(): Promise<void> {
         freezeUntil = performance.now() + FREEZE_FRAME_MS * 2;
         break;
       case 'snapshot':
-        snapshots.push(performance.now(), msg.players, msg.chunks);
+        snapshots.push(performance.now(), msg.players, msg.chunks, msg.items, msg.round);
         break;
     }
   };
 
   const conn = new Connection(
-    `ws://127.0.0.1:${port}`,
+    `ws://${address}:${port}`,
     onMessage,
     () => conn.send(hello(choice.name, choice.characterId)),
-    () => setStatus(fr.disconnected),
+    () => {
+      setStatus(fr.disconnected);
+      lobbyPanel.update({ phase: 'playing', players: [], countdown: null, hostId: 0, rotation: { mode: 'all', selection: [] }, maps: [] }); // hide it
+    },
   );
 
   const screenToWorld = (sx: number, sy: number): [number, number] => [
@@ -308,6 +463,11 @@ async function start(): Promise<void> {
       const s = sample.chunks.get(id);
       if (s) view.update(s);
     }
+    itemsView.update(sample.items, dt);
+    cherryView.update(sample.round?.cherry ?? null, dt);
+    if (sample.round) custardView.update(sample.round.custardY, world.terrain.width, world.terrain.height, dt, sample.round.finalRush);
+    spoonsView.update(dt);
+    hud.update(round, rounds, sample.round, states, infos, localId);
     const [aimX, aimY] = screenToWorld(input.mouseX, input.mouseY);
     for (const [id, state] of states) {
       const info = infos.get(id);
@@ -320,6 +480,10 @@ async function start(): Promise<void> {
       }
       const ev = view.update(state, id === localId ? aimX : state.x + state.facing * 100, id === localId ? aimY : state.y, dt);
       if (ev.landed && ev.landingSpeed > LANDING_DUST_MIN_VY) particles.puff(state.x, state.y + state.size, 8);
+      // Smarties: a sugary trail.
+      if (state.anim & Anim.Boosted && Math.random() < 0.5) {
+        particles.burst(state.x, state.y + state.size * 0.5, 1, [0xff3b6b, 0xffe14d, 0x4dc4ff, 0x9be15d][Math.floor(Math.random() * 4)], 60);
+      }
       if (ev.stunnedNow) {
         popups.spawn(state.x, state.y - state.size, fr.onomatopoeia.hit, 40);
         particles.burst(state.x, state.y, 10, 0xffe14d, 300);

+ 33 - 7
src/renderer/net/interpolation.ts

@@ -1,14 +1,18 @@
-import type { ChunkState, PlayerState } from '../../shared/protocol';
+import type { ChunkState, ItemState, PlayerState, RoundState } from '../../shared/protocol';
 
 interface Timed {
   time: number;
   players: Map<number, PlayerState>;
   chunks: Map<number, ChunkState>;
+  items: Map<number, ItemState>;
+  round: RoundState | null;
 }
 
 export interface Sample {
   players: Map<number, PlayerState>;
   chunks: Map<number, ChunkState>;
+  items: Map<number, ItemState>;
+  round: RoundState | null;
 }
 
 const MAX_BUFFER = 32;
@@ -21,18 +25,26 @@ function lerpAngle(a: number, b: number, t: number): number {
   return a + d * t;
 }
 
+const lerp = (a: number, b: number, t: number): number => a + (b - a) * t;
+
 /** Buffers snapshots and renders entities slightly in the past, lerping between the two around the render time. */
 export class SnapshotBuffer {
   private buffer: Timed[] = [];
 
-  push(time: number, players: PlayerState[], chunks: ChunkState[]): void {
-    this.buffer.push({ time, players: new Map(players.map((p) => [p.id, p])), chunks: new Map(chunks.map((c) => [c.id, c])) });
+  push(time: number, players: PlayerState[], chunks: ChunkState[], items: ItemState[] = [], round: RoundState | null = null): void {
+    this.buffer.push({
+      time,
+      players: new Map(players.map((p) => [p.id, p])),
+      chunks: new Map(chunks.map((c) => [c.id, c])),
+      items: new Map(items.map((i) => [i.id, i])),
+      round,
+    });
     if (this.buffer.length > MAX_BUFFER) this.buffer.shift();
   }
 
   sample(renderTime: number): Sample {
     const b = this.buffer;
-    if (b.length === 0) return { players: new Map(), chunks: new Map() };
+    if (b.length === 0) return { players: new Map(), chunks: new Map(), items: new Map(), round: null };
     if (renderTime <= b[0].time) return b[0];
     for (let i = b.length - 1; i > 0; i--) {
       const a = b[i - 1];
@@ -43,14 +55,28 @@ export class SnapshotBuffer {
       const players = new Map<number, PlayerState>();
       for (const [id, pc] of c.players) {
         const pa = a.players.get(id);
-        players.set(id, pa ? { ...pc, x: pa.x + (pc.x - pa.x) * t, y: pa.y + (pc.y - pa.y) * t } : pc);
+        players.set(id, pa ? { ...pc, x: lerp(pa.x, pc.x, t), y: lerp(pa.y, pc.y, t) } : pc);
       }
       const chunks = new Map<number, ChunkState>();
       for (const [id, cc] of c.chunks) {
         const ca = a.chunks.get(id);
-        chunks.set(id, ca ? { id, x: ca.x + (cc.x - ca.x) * t, y: ca.y + (cc.y - ca.y) * t, angle: lerpAngle(ca.angle, cc.angle, t) } : cc);
+        chunks.set(id, ca ? { id, x: lerp(ca.x, cc.x, t), y: lerp(ca.y, cc.y, t), angle: lerpAngle(ca.angle, cc.angle, t) } : cc);
+      }
+      const items = new Map<number, ItemState>();
+      for (const [id, ic] of c.items) {
+        const ia = a.items.get(id);
+        items.set(id, ia ? { ...ic, x: lerp(ia.x, ic.x, t), y: lerp(ia.y, ic.y, t), angle: lerpAngle(ia.angle, ic.angle, t) } : ic);
+      }
+      let round = c.round;
+      if (round && a.round) {
+        const ch = round.cherry && a.round.cherry && round.cherry.holder === a.round.cherry.holder ? round.cherry : null;
+        round = {
+          ...round,
+          custardY: lerp(a.round.custardY, round.custardY, t),
+          cherry: ch && a.round.cherry ? { ...ch, x: lerp(a.round.cherry.x, ch.x, t), y: lerp(a.round.cherry.y, ch.y, t) } : round.cherry,
+        };
       }
-      return { players, chunks };
+      return { players, chunks, items, round };
     }
     return b[b.length - 1];
   }

+ 528 - 0
src/renderer/style.css

@@ -85,6 +85,9 @@ body {
 
 .menu-card {
   width: min(760px, calc(100vw - 32px));
+  max-height: calc(100vh - 32px);
+  overflow-y: auto;
+  box-sizing: border-box;
   background: var(--paper);
   border: 4px solid var(--ink);
   border-radius: 28px 22px 30px 20px;
@@ -212,3 +215,528 @@ body {
   transform: translate(3px, 3px);
   box-shadow: 2px 2px 0 var(--ink);
 }
+
+/* ---------- Buttons ---------- */
+
+button.primary,
+button.secondary {
+  font: inherit;
+  font-weight: bold;
+  border: 3px solid var(--ink);
+  border-radius: 16px 11px 17px 10px;
+  padding: 6px 18px;
+  cursor: pointer;
+  box-shadow: 3px 3px 0 var(--ink);
+}
+
+button.primary {
+  color: #fff;
+  background: var(--pink);
+  text-shadow: 1px 1px 0 var(--ink);
+}
+
+button.secondary {
+  color: var(--ink);
+  background: #fff;
+}
+
+button.primary:hover:not(:disabled),
+button.secondary:hover:not(:disabled) {
+  transform: rotate(-1.5deg) scale(1.04);
+}
+
+button:disabled {
+  opacity: 0.45;
+  cursor: not-allowed;
+}
+
+button.small {
+  font-size: 14px;
+  padding: 4px 12px;
+}
+
+/* ---------- Game browser ---------- */
+
+.menu-card h1.small {
+  font-size: clamp(26px, 4.5vw, 40px);
+  margin-bottom: 14px;
+}
+
+.games {
+  list-style: none;
+  margin: 0 auto;
+  padding: 0;
+  max-height: 46vh;
+  overflow-y: auto;
+  text-align: left;
+}
+
+.games li {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  gap: 12px;
+  background: #fff;
+  border: 3px solid var(--ink);
+  border-radius: 14px 10px 15px 9px;
+  padding: 8px 12px;
+  margin-bottom: 10px;
+}
+
+.games li div {
+  display: flex;
+  flex-direction: column;
+  min-width: 0;
+}
+
+.games li strong {
+  font-size: 18px;
+}
+
+.games li span {
+  font-size: 13px;
+  opacity: 0.8;
+}
+
+.games li.empty {
+  justify-content: center;
+  font-style: italic;
+  border-style: dashed;
+}
+
+.manual {
+  display: flex;
+  gap: 10px;
+  justify-content: center;
+  align-items: center;
+  flex-wrap: wrap;
+  margin: 12px 0 4px;
+}
+
+.manual input {
+  font: inherit;
+  border: 3px solid var(--ink);
+  border-radius: 10px 8px 11px 7px;
+  padding: 4px 10px;
+  width: 170px;
+  margin-left: 8px;
+  color: var(--ink);
+}
+
+input.invalid {
+  border-color: #d93a5b !important;
+  background: #ffe3ea;
+}
+
+.actions {
+  display: flex;
+  justify-content: space-between;
+  margin-top: 18px;
+  gap: 12px;
+}
+
+/* ---------- Warm-up panel ---------- */
+
+#lobby-panel {
+  position: fixed;
+  top: 40px;
+  right: 16px;
+  width: 230px;
+  background: var(--paper);
+  border: 3px solid var(--ink);
+  border-radius: 18px 12px 20px 11px;
+  box-shadow: 5px 5px 0 rgba(59, 36, 20, 0.4);
+  padding: 10px 14px 14px;
+  z-index: 5;
+  text-align: center;
+}
+
+#lobby-panel[hidden] {
+  display: none;
+}
+
+#lobby-panel h3 {
+  margin: 0 0 2px;
+  color: var(--pink);
+  -webkit-text-stroke: 1px var(--ink);
+  font-size: 22px;
+}
+
+#lobby-panel .hint {
+  margin: 0 0 8px;
+  font-size: 12px;
+}
+
+#lobby-panel ul {
+  list-style: none;
+  margin: 0 0 6px;
+  padding: 0;
+  text-align: left;
+}
+
+#lobby-panel li {
+  padding: 2px 0;
+  opacity: 0.7;
+}
+
+#lobby-panel li.ready {
+  opacity: 1;
+  font-weight: bold;
+  color: #3f8a1f;
+}
+
+#lobby-panel li.me::after {
+  content: ' ★';
+  color: var(--pink);
+}
+
+#lobby-panel .status {
+  margin: 4px 0 10px;
+  font-weight: bold;
+}
+
+/* ---------- Round HUD ---------- */
+
+#round-hud {
+  position: fixed;
+  top: 8px;
+  left: 50%;
+  transform: translateX(-50%) rotate(-1deg);
+  background: var(--paper);
+  border: 3px solid var(--ink);
+  border-radius: 16px 11px 18px 10px;
+  box-shadow: 4px 4px 0 rgba(59, 36, 20, 0.4);
+  padding: 2px 18px 4px;
+  text-align: center;
+  pointer-events: none;
+  z-index: 4;
+}
+
+#round-hud[hidden] {
+  display: none;
+}
+
+#round-hud .label {
+  font-size: 13px;
+}
+
+#round-hud .timer {
+  font-size: 30px;
+  font-weight: bold;
+  line-height: 1;
+}
+
+#round-hud.rush .timer {
+  color: #d93a5b;
+  animation: wobble 0.5s infinite alternate;
+}
+
+#round-hud .rush-label {
+  font-size: 12px;
+  font-weight: bold;
+  color: #d93a5b;
+}
+
+@keyframes wobble {
+  from {
+    transform: scale(1) rotate(-2deg);
+  }
+  to {
+    transform: scale(1.12) rotate(2deg);
+  }
+}
+
+#scoreboard {
+  position: fixed;
+  top: 10px;
+  left: 12px;
+  list-style: none;
+  margin: 0;
+  padding: 6px 10px;
+  background: rgba(255, 246, 228, 0.88);
+  border: 3px solid var(--ink);
+  border-radius: 14px 10px 15px 9px;
+  min-width: 150px;
+  pointer-events: none;
+  z-index: 4;
+}
+
+#scoreboard[hidden] {
+  display: none;
+}
+
+#scoreboard li {
+  display: flex;
+  justify-content: space-between;
+  gap: 12px;
+  font-size: 15px;
+}
+
+#scoreboard li.me {
+  font-weight: bold;
+}
+
+#scoreboard li.holder::before {
+  content: '🍒 ';
+}
+
+#scoreboard li.dead {
+  opacity: 0.45;
+}
+
+#hint {
+  position: fixed;
+  bottom: 60px;
+  left: 50%;
+  transform: translateX(-50%);
+  font-weight: bold;
+  font-size: 18px;
+  text-shadow:
+    2px 2px 0 #fff,
+    -2px -2px 0 #fff;
+  pointer-events: none;
+}
+
+/* ---------- Results ---------- */
+
+#results {
+  position: fixed;
+  inset: 0;
+  display: grid;
+  place-items: center;
+  background: rgba(59, 36, 20, 0.35);
+  z-index: 8;
+}
+
+#results[hidden] {
+  display: none;
+}
+
+#results table {
+  margin: 0 auto 10px;
+  border-collapse: collapse;
+  font-size: 18px;
+  min-width: 340px;
+}
+
+#results th,
+#results td {
+  padding: 4px 12px;
+  border-bottom: 2px dashed rgba(59, 36, 20, 0.25);
+}
+
+#results td.num {
+  text-align: right;
+  font-weight: bold;
+}
+
+#results tr.me td {
+  color: var(--pink-dark);
+}
+
+#results tr:first-child td:first-child::before {
+  content: '👑 ';
+}
+
+#results .winner {
+  font-size: 24px;
+  font-weight: bold;
+  color: var(--pink);
+  -webkit-text-stroke: 1px var(--ink);
+  margin: 0 0 10px;
+}
+
+#results .trophies {
+  display: grid;
+  grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
+  gap: 10px;
+  margin: 8px 0 12px;
+}
+
+#results .trophy {
+  background: #fff;
+  border: 3px solid var(--ink);
+  border-radius: 14px 10px 15px 9px;
+  padding: 6px 8px;
+  transform: rotate(-1deg);
+}
+
+#results .trophy:nth-child(even) {
+  transform: rotate(1.2deg);
+}
+
+#results .trophy strong {
+  display: block;
+  color: var(--pink-dark);
+}
+
+#results .trophy span {
+  font-size: 13px;
+}
+
+#results .footer {
+  font-size: 14px;
+  opacity: 0.8;
+}
+
+/* ---------- Character sheet ---------- */
+
+.characters .character {
+  width: 150px;
+  padding: 8px 8px 10px;
+}
+
+.sheet {
+  display: flex;
+  gap: 18px;
+  justify-content: center;
+  align-items: center;
+  flex-wrap: wrap;
+  margin: 14px auto 0;
+  padding: 10px 16px;
+  max-width: 640px;
+  min-height: 110px;
+  background: #fff;
+  border: 3px dashed var(--ink);
+  border-radius: 16px 12px 18px 11px;
+  text-align: left;
+}
+
+.sheet .abilities {
+  flex: 1 1 300px;
+}
+
+.sheet p {
+  margin: 3px 0;
+  font-size: 15px;
+}
+
+.sheet .desc {
+  font-style: italic;
+  margin-bottom: 6px;
+}
+
+.sheet .flaw {
+  color: #b02f4c;
+}
+
+.sheet .stats {
+  flex: 0 0 auto;
+}
+
+.stat {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  gap: 10px;
+  font-size: 14px;
+  margin: 4px 0;
+}
+
+.pips {
+  display: inline-flex;
+  gap: 4px;
+}
+
+.pips i {
+  width: 14px;
+  height: 14px;
+  border-radius: 50%;
+  border: 2px solid var(--ink);
+  background: #fff;
+}
+
+.pips i.on {
+  background: var(--pink);
+}
+
+/* Compact title menu: four characters and their sheet must fit in 720 px. */
+.menu-card {
+  padding: 14px 24px 16px;
+}
+
+.menu-card h1 {
+  font-size: clamp(30px, 5vw, 46px);
+}
+
+.subtitle {
+  margin: 2px 0 10px;
+}
+
+.menu-card h2 {
+  margin: 10px 0 8px;
+}
+
+.portrait {
+  height: 92px;
+}
+
+#menu-play {
+  margin-top: 12px;
+}
+
+/* ---------- Map rotation and catch-up pick ---------- */
+
+#lobby-panel .rotation {
+  text-align: left;
+  border-top: 2px dashed rgba(59, 36, 20, 0.3);
+  margin: 6px 0;
+  padding-top: 6px;
+  font-size: 13px;
+}
+
+#lobby-panel .rotation-title {
+  margin: 0 0 4px;
+  font-weight: bold;
+}
+
+#lobby-panel .rotation-summary,
+#lobby-panel .rotation-hint {
+  margin: 2px 0;
+}
+
+#lobby-panel .rotation-hint {
+  opacity: 0.7;
+  font-size: 12px;
+}
+
+#lobby-panel select {
+  font: inherit;
+  width: 100%;
+  border: 2px solid var(--ink);
+  border-radius: 8px;
+  padding: 2px 4px;
+  margin-bottom: 4px;
+}
+
+#lobby-panel label {
+  display: block;
+  cursor: pointer;
+}
+
+#round-hud .wind {
+  font-size: 14px;
+  font-weight: bold;
+  color: #2b7bbf;
+}
+
+#results .map-pick {
+  margin: 4px 0 10px;
+}
+
+#results .pick-title {
+  font-weight: bold;
+  margin: 4px 0 8px;
+}
+
+#results .pick-buttons {
+  display: flex;
+  gap: 8px;
+  justify-content: center;
+  flex-wrap: wrap;
+}
+
+#results .picked {
+  color: var(--pink-dark);
+  font-weight: bold;
+}

+ 105 - 0
src/renderer/ui/browser.ts

@@ -0,0 +1,105 @@
+import { MAX_PLAYERS, NET_PORT, PROTOCOL_VERSION } from '../../shared/constants';
+import type { LanGame } from '../../preload/api';
+import { fr } from '../i18n/fr';
+
+export type BrowserChoice = { mode: 'host' } | { mode: 'join'; address: string; port: number } | { mode: 'back' };
+
+const ADDRESS_KEY = 'gouter.address';
+
+/** Parses "host" or "host:port". */
+function parseAddress(text: string): { address: string; port: number } | null {
+  const m = /^\s*([\w.-]+)(?::(\d{1,5}))?\s*$/.exec(text);
+  if (!m) return null;
+  return { address: m[1], port: m[2] ? Number(m[2]) : NET_PORT };
+}
+
+/** Lists the games announced on the LAN, plus "create" and "join by address". */
+export function showBrowser(): Promise<BrowserChoice> {
+  const root = document.createElement('div');
+  root.id = 'menu';
+  root.innerHTML = `
+    <div class="menu-card browser">
+      <h1 class="small">${fr.browser.title}</h1>
+      <ul class="games"></ul>
+      <div class="manual">
+        <label>${fr.browser.manualLabel}
+          <input id="browser-address" placeholder="${fr.browser.manualPlaceholder}" autocomplete="off" spellcheck="false" />
+        </label>
+        <button id="browser-manual" class="secondary">${fr.browser.join}</button>
+      </div>
+      <div class="actions">
+        <button id="browser-back" class="secondary">${fr.browser.back}</button>
+        <button id="browser-host" class="primary">${fr.browser.host}</button>
+      </div>
+    </div>`;
+  document.body.appendChild(root);
+
+  const list = root.querySelector<HTMLUListElement>('.games')!;
+  const addressInput = root.querySelector<HTMLInputElement>('#browser-address')!;
+  try {
+    addressInput.value = localStorage.getItem(ADDRESS_KEY) ?? '';
+  } catch {
+    // Storage unavailable: start empty.
+  }
+
+  let resolve!: (choice: BrowserChoice) => void;
+  const done = new Promise<BrowserChoice>((r) => (resolve = r));
+  const finish = (choice: BrowserChoice): void => {
+    stop();
+    root.remove();
+    resolve(choice);
+  };
+
+  const render = (games: LanGame[]): void => {
+    list.replaceChildren();
+    if (games.length === 0) {
+      const li = document.createElement('li');
+      li.className = 'empty';
+      li.textContent = fr.browser.searching;
+      list.appendChild(li);
+      return;
+    }
+    for (const g of games) {
+      const li = document.createElement('li');
+      const info = document.createElement('div');
+      const name = document.createElement('strong');
+      name.textContent = g.name;
+      const details = document.createElement('span');
+      details.textContent = `${fr.browser.players(g.players, g.maxPlayers ?? MAX_PLAYERS)} · ${fr.browser.phase[g.phase] ?? g.phase} · ${g.address}`;
+      info.append(name, details);
+      const button = document.createElement('button');
+      button.className = 'primary small';
+      const compatible = g.version === PROTOCOL_VERSION;
+      const full = g.players >= g.maxPlayers;
+      button.textContent = !compatible ? fr.browser.incompatible : full ? fr.browser.full : fr.browser.join;
+      button.disabled = !compatible || full;
+      button.addEventListener('click', () => finish({ mode: 'join', address: g.address, port: g.port }));
+      li.append(info, button);
+      list.appendChild(li);
+    }
+  };
+  render([]);
+  const stop = window.lan.discover(render);
+
+  root.querySelector('#browser-host')!.addEventListener('click', () => finish({ mode: 'host' }));
+  root.querySelector('#browser-back')!.addEventListener('click', () => finish({ mode: 'back' }));
+  const joinManual = (): void => {
+    const parsed = parseAddress(addressInput.value);
+    if (!parsed) {
+      addressInput.classList.add('invalid');
+      return;
+    }
+    try {
+      localStorage.setItem(ADDRESS_KEY, addressInput.value.trim());
+    } catch {
+      // Not remembered, that's all.
+    }
+    finish({ mode: 'join', ...parsed });
+  };
+  root.querySelector('#browser-manual')!.addEventListener('click', joinManual);
+  addressInput.addEventListener('keydown', (e) => {
+    addressInput.classList.remove('invalid');
+    if (e.key === 'Enter') joinManual();
+  });
+  return done;
+}

+ 179 - 0
src/renderer/ui/hud.ts

@@ -0,0 +1,179 @@
+import { Anim } from '../../shared/characters';
+import type { MatchEndMessage, PlayerInfo, PlayerState, RoundEndMessage, RoundState } from '../../shared/protocol';
+import { fr } from '../i18n/fr';
+
+const el = <K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text = ''): HTMLElementTagNameMap[K] => {
+  const e = document.createElement(tag);
+  if (className) e.className = className;
+  if (text) e.textContent = text;
+  return e;
+};
+
+/** Round banner (round, timer, final rush), scoreboard and contextual hint. */
+export class RoundHud {
+  private readonly banner = el('div');
+  private readonly label = el('div', 'label');
+  private readonly timer = el('div', 'timer');
+  private readonly rush = el('div', 'rush-label', fr.hud.rush);
+  private readonly wind = el('div', 'wind');
+  private readonly board = el('ul');
+  private readonly hint = el('div');
+  private lastKey = '';
+
+  constructor() {
+    this.banner.id = 'round-hud';
+    this.board.id = 'scoreboard';
+    this.hint.id = 'hint';
+    this.banner.append(this.label, this.timer, this.rush, this.wind);
+    document.body.append(this.banner, this.board, this.hint);
+    this.banner.hidden = true;
+    this.board.hidden = true;
+  }
+
+  update(round: number, rounds: number, state: RoundState | null, players: Map<number, PlayerState>, infos: Map<number, PlayerInfo>, localId: number): void {
+    const playing = round > 0 && state?.timeLeft != null;
+    this.banner.hidden = !playing;
+    this.board.hidden = !playing;
+    const me = players.get(localId);
+    const alive = me !== undefined && (me.anim & Anim.Dead) === 0;
+    this.hint.textContent = alive && me.item === 'candle' ? fr.hud.candleHint : '';
+    if (!playing || !state) return;
+
+    const t = Math.ceil(state.timeLeft ?? 0);
+    this.label.textContent = fr.hud.round(round, rounds);
+    this.timer.textContent = `${Math.floor(t / 60)}:${String(t % 60).padStart(2, '0')}`;
+    this.banner.classList.toggle('rush', state.finalRush);
+    this.rush.hidden = !state.finalRush;
+    // Wind: up to three arrows in its direction.
+    const arrows = Math.min(3, Math.round(Math.abs(state.wind) / 150));
+    this.wind.hidden = arrows === 0;
+    this.wind.textContent = arrows === 0 ? '' : `💨 ${(state.wind > 0 ? '→' : '←').repeat(arrows)}`;
+
+    // Rebuild the scoreboard only when something visible changed.
+    const rows = [...players.values()]
+      .map((p) => ({ p, name: infos.get(p.id)?.name ?? '?' }))
+      .sort((a, b) => b.p.score - a.p.score || a.p.id - b.p.id);
+    const holder = state.cherry?.holder ?? 0;
+    const key = rows.map(({ p, name }) => `${p.id}:${name}:${p.score}:${p.anim & Anim.Dead}`).join('|') + `#${holder}`;
+    if (key === this.lastKey) return;
+    this.lastKey = key;
+    this.board.replaceChildren(
+      ...rows.map(({ p, name }) => {
+        const li = el('li');
+        li.append(el('span', '', name), el('span', '', String(p.score)));
+        li.classList.toggle('me', p.id === localId);
+        li.classList.toggle('holder', p.id === holder);
+        li.classList.toggle('dead', (p.anim & Anim.Dead) !== 0);
+        return li;
+      }),
+    );
+  }
+}
+
+/** Round results and final results (with trophies) overlay. */
+export class ResultsScreen {
+  private readonly root = el('div');
+  private timer: ReturnType<typeof setInterval> | null = null;
+  private pickBox: HTMLDivElement | null = null;
+
+  constructor(private readonly onPick: (mapId: string) => void) {
+    this.root.id = 'results';
+    this.root.hidden = true;
+    document.body.appendChild(this.root);
+  }
+
+  hide(): void {
+    this.root.hidden = true;
+    this.pickBox = null;
+    if (this.timer) clearInterval(this.timer);
+    this.timer = null;
+  }
+
+  showRound(msg: RoundEndMessage, localId: number): void {
+    this.show(fr.results.roundTitle(msg.round, msg.rounds), msg.results, localId, null, msg.nextIn, fr.results.next);
+    // Catch-up (readme §4): the last-placed player picks the next map.
+    if (msg.picker === null || msg.choices.length === 0) return;
+    const box = el('div', 'map-pick');
+    const pickerName = msg.results.find((r) => r.id === msg.picker)?.name ?? '?';
+    if (msg.picker === localId) {
+      box.appendChild(el('p', 'pick-title', fr.pick.you));
+      const buttons = el('div', 'pick-buttons');
+      for (const m of msg.choices) {
+        const b = el('button', 'secondary', m.name);
+        b.addEventListener('click', () => {
+          this.onPick(m.id);
+          for (const other of buttons.querySelectorAll('button')) other.disabled = true;
+          b.classList.replace('secondary', 'primary');
+        });
+        buttons.appendChild(b);
+      }
+      box.appendChild(buttons);
+    } else {
+      box.appendChild(el('p', 'pick-title', fr.pick.other(pickerName)));
+    }
+    this.pickBox = box;
+    this.root.querySelector('.footer')?.before(box);
+  }
+
+  /** Shows which map the picker chose. */
+  showPicked(mapName: string): void {
+    if (!this.pickBox) return;
+    this.pickBox.appendChild(el('p', 'picked', fr.pick.picked(mapName)));
+  }
+
+  showMatch(msg: MatchEndMessage, localId: number): void {
+    this.show(fr.results.matchTitle, msg.results, localId, msg, msg.lobbyIn, fr.results.lobby);
+  }
+
+  private show(
+    title: string,
+    results: RoundEndMessage['results'],
+    localId: number,
+    match: MatchEndMessage | null,
+    seconds: number,
+    footer: (s: number) => string,
+  ): void {
+    const card = el('div', 'menu-card');
+    card.appendChild(el('h1', 'small', title));
+    if (match && results[0]) card.appendChild(el('p', 'winner', fr.results.winner(results[0].name)));
+
+    const table = el('table');
+    const head = el('tr');
+    for (const h of [fr.results.player, fr.results.round, fr.results.total]) head.appendChild(el('th', '', h));
+    table.appendChild(head);
+    for (const r of results) {
+      const tr = el('tr', r.id === localId ? 'me' : '');
+      tr.append(el('td', '', r.name), el('td', 'num', String(r.roundScore)), el('td', 'num', String(r.total)));
+      table.appendChild(tr);
+    }
+    card.appendChild(table);
+
+    if (match) {
+      card.appendChild(el('h2', '', fr.results.trophies));
+      const grid = el('div', 'trophies');
+      const names = new Map(results.map((r) => [r.id, r.name]));
+      for (const t of match.trophies) {
+        const text = fr.trophies[t.id];
+        if (!text) continue;
+        const box = el('div', 'trophy');
+        box.append(el('strong', '', `🏆 ${text.name}`), el('div', '', names.get(t.playerId) ?? '?'), el('span', '', text.desc(t.value)));
+        grid.appendChild(box);
+      }
+      if (grid.childElementCount === 0) grid.appendChild(el('p', '', fr.results.noTrophy));
+      card.appendChild(grid);
+    }
+
+    const foot = el('p', 'footer');
+    card.appendChild(foot);
+    this.root.replaceChildren(card);
+    this.root.hidden = false;
+
+    let left = Math.ceil(seconds);
+    foot.textContent = footer(left);
+    if (this.timer) clearInterval(this.timer);
+    this.timer = setInterval(() => {
+      left = Math.max(0, left - 1);
+      foot.textContent = footer(left);
+    }, 1000);
+  }
+}

+ 105 - 0
src/renderer/ui/lobbyPanel.ts

@@ -0,0 +1,105 @@
+import type { LobbyPlayer, MapSummary, Phase, Rotation } from '../../shared/protocol';
+import { fr } from '../i18n/fr';
+
+export type LobbyMessage = { phase: Phase; players: LobbyPlayer[]; countdown: number | null; hostId: number; rotation: Rotation; maps: MapSummary[] };
+
+const MODES: Rotation['mode'][] = ['all', 'random', 'selection'];
+
+/**
+ * Warm-up panel: who is here, who is ready, the start countdown, and the map rotation
+ * (set by the host, shown to everyone). Hidden during a match.
+ */
+export class LobbyPanel {
+  private readonly root: HTMLDivElement;
+  private readonly list: HTMLUListElement;
+  private readonly status: HTMLParagraphElement;
+  private readonly button: HTMLButtonElement;
+  private readonly rotationBox: HTMLDivElement;
+  private ready = false;
+  /** Last rotation UI state rendered, to avoid rebuilding (and losing focus) on every lobby update. */
+  private rotationKey = '';
+
+  constructor(
+    private readonly localId: () => number,
+    onReady: (ready: boolean) => void,
+    private readonly onRotation: (rotation: Rotation) => void,
+  ) {
+    this.root = document.createElement('div');
+    this.root.id = 'lobby-panel';
+    this.root.innerHTML = `<h3>${fr.lobby.title}</h3><p class="hint">${fr.lobby.hint}</p><ul></ul><div class="rotation"></div><p class="status"></p><button class="primary"></button>`;
+    this.list = this.root.querySelector('ul')!;
+    this.status = this.root.querySelector('.status')!;
+    this.button = this.root.querySelector('button.primary')!;
+    this.rotationBox = this.root.querySelector('.rotation')!;
+    this.button.addEventListener('click', () => {
+      onReady(!this.ready);
+      this.button.blur(); // keep Space for jumping, not for re-clicking
+    });
+    this.root.hidden = true;
+    document.body.appendChild(this.root);
+  }
+
+  update(msg: LobbyMessage): void {
+    const { phase, players, countdown } = msg;
+    this.root.hidden = phase !== 'lobby';
+    if (phase !== 'lobby') return;
+    this.ready = players.find((p) => p.id === this.localId())?.ready ?? false;
+    this.button.textContent = this.ready ? fr.lobby.notReady : fr.lobby.ready;
+    this.button.classList.toggle('secondary', this.ready);
+    this.list.replaceChildren(
+      ...players.map((p) => {
+        const li = document.createElement('li');
+        li.className = p.ready ? 'ready' : '';
+        li.textContent = `${p.ready ? '✔' : '…'} ${p.name}${p.id === msg.hostId ? ' 👑' : ''}`;
+        if (p.id === this.localId()) li.classList.add('me');
+        return li;
+      }),
+    );
+    const waiting = players.filter((p) => !p.ready).length;
+    this.status.textContent = countdown !== null ? fr.lobby.countdown(countdown) : fr.lobby.waiting(waiting);
+    this.renderRotation(msg);
+  }
+
+  private renderRotation(msg: LobbyMessage): void {
+    const isHost = msg.hostId === this.localId();
+    const key = JSON.stringify([isHost, msg.rotation, msg.maps]);
+    if (key === this.rotationKey) return;
+    this.rotationKey = key;
+    const box = this.rotationBox;
+    box.replaceChildren();
+    const title = document.createElement('p');
+    title.className = 'rotation-title';
+    title.textContent = fr.rotation.title;
+    box.appendChild(title);
+
+    const name = (id: string): string => msg.maps.find((m) => m.id === id)?.name ?? id;
+    if (!isHost) {
+      const p = document.createElement('p');
+      p.className = 'rotation-summary';
+      const picked = msg.rotation.mode === 'selection' && msg.rotation.selection.length > 0;
+      p.textContent = picked ? `${fr.rotation.modes.selection} : ${msg.rotation.selection.map(name).join(', ')}` : fr.rotation.modes[msg.rotation.mode];
+      box.append(p, Object.assign(document.createElement('p'), { className: 'rotation-hint', textContent: fr.rotation.hostOnly }));
+      return;
+    }
+
+    const select = document.createElement('select');
+    for (const mode of MODES) select.appendChild(new Option(fr.rotation.modes[mode], mode, false, mode === msg.rotation.mode));
+    select.addEventListener('change', () => this.onRotation({ mode: select.value as Rotation['mode'], selection: msg.rotation.selection }));
+    box.appendChild(select);
+
+    if (msg.rotation.mode === 'selection') {
+      for (const map of msg.maps) {
+        const label = document.createElement('label');
+        const check = document.createElement('input');
+        check.type = 'checkbox';
+        check.checked = msg.rotation.selection.includes(map.id);
+        check.addEventListener('change', () => {
+          const selection = msg.maps.map((m) => m.id).filter((id) => (id === map.id ? check.checked : msg.rotation.selection.includes(id)));
+          this.onRotation({ mode: 'selection', selection });
+        });
+        label.append(check, ` ${map.name}`);
+        box.appendChild(label);
+      }
+    }
+  }
+}

+ 72 - 6
src/renderer/ui/menu.ts

@@ -1,3 +1,4 @@
+import type { CharacterStats } from '../../shared/characters';
 import { fr } from '../i18n/fr';
 
 export interface MenuChoice {
@@ -24,8 +25,36 @@ function save(key: string, value: string): void {
   }
 }
 
-/** Title screen: nickname + character choice. `previews` maps character ids to a rendered portrait. */
-export function showMenu(characterIds: string[], defaultId: string, previews: Map<string, HTMLCanvasElement>): Promise<MenuChoice> {
+const PIPS = 5;
+
+/** A row of PIPS dots, `value` relative to the best character for that stat. */
+function statBar(label: string, value: number, best: number): HTMLDivElement {
+  const row = document.createElement('div');
+  row.className = 'stat';
+  const name = document.createElement('span');
+  name.textContent = label;
+  const pips = document.createElement('span');
+  pips.className = 'pips';
+  const filled = Math.max(1, Math.round((value / best) * PIPS));
+  for (let i = 0; i < PIPS; i++) {
+    const pip = document.createElement('i');
+    if (i < filled) pip.className = 'on';
+    pips.appendChild(pip);
+  }
+  row.append(name, pips);
+  return row;
+}
+
+/**
+ * Title screen: nickname + character selection (readme §9, M5). `previews` maps character ids
+ * to a rendered portrait, `stats` gives the stat bars of the selected character's sheet.
+ */
+export function showMenu(
+  characterIds: string[],
+  defaultId: string,
+  previews: Map<string, HTMLCanvasElement>,
+  stats: Map<string, CharacterStats>,
+): Promise<MenuChoice> {
   const root = document.createElement('div');
   root.id = 'menu';
   root.innerHTML = `
@@ -37,6 +66,7 @@ export function showMenu(characterIds: string[], defaultId: string, previews: Ma
       </label>
       <h2>${fr.chooseCharacter}</h2>
       <div class="characters"></div>
+      <div class="sheet"></div>
       <button id="menu-play">${fr.play}</button>
     </div>`;
   document.body.appendChild(root);
@@ -49,7 +79,7 @@ export function showMenu(characterIds: string[], defaultId: string, previews: Ma
   const list = root.querySelector<HTMLDivElement>('.characters')!;
   const cards = new Map<string, HTMLButtonElement>();
   for (const id of characterIds) {
-    const text = fr.characters[id] ?? { name: id, desc: '' };
+    const text = fr.characters[id] ?? { name: id, desc: '', attack: '', special: '', flaw: '' };
     const card = document.createElement('button');
     card.className = 'character';
     card.type = 'button';
@@ -60,18 +90,54 @@ export function showMenu(characterIds: string[], defaultId: string, previews: Ma
     }
     const name = document.createElement('strong');
     name.textContent = text.name;
-    const desc = document.createElement('span');
-    desc.textContent = text.desc;
-    card.append(name, desc);
+    card.append(name);
     card.addEventListener('click', () => select(id));
     card.addEventListener('dblclick', () => play());
     list.appendChild(card);
     cards.set(id, card);
   }
 
+  const sheet = root.querySelector<HTMLDivElement>('.sheet')!;
+  const all = [...stats.values()];
+  const best = (key: 'speed' | 'jump' | 'mass'): number => Math.max(...all.map((st) => st[key]), 1);
+  function renderSheet(id: string): void {
+    const text = fr.characters[id];
+    const st = stats.get(id);
+    sheet.replaceChildren();
+    if (!text) return;
+    const left = document.createElement('div');
+    left.className = 'abilities';
+    const desc = document.createElement('p');
+    desc.className = 'desc';
+    desc.textContent = text.desc;
+    left.appendChild(desc);
+    for (const [icon, line, cls] of [
+      ['⚔️', text.attack, ''],
+      ['✨', text.special, ''],
+      ['⚠️', text.flaw, 'flaw'],
+    ]) {
+      const p = document.createElement('p');
+      p.className = cls;
+      p.textContent = `${icon} ${line}`;
+      left.appendChild(p);
+    }
+    sheet.appendChild(left);
+    if (st) {
+      const right = document.createElement('div');
+      right.className = 'stats';
+      right.append(
+        statBar(fr.stats.speed, st.speed, best('speed')),
+        statBar(fr.stats.jump, st.jump, best('jump')),
+        statBar(fr.stats.mass, st.mass, best('mass')),
+      );
+      sheet.appendChild(right);
+    }
+  }
+
   function select(id: string): void {
     selected = id;
     for (const [cid, card] of cards) card.classList.toggle('selected', cid === id);
+    renderSheet(id);
   }
   select(selected);
 

+ 10 - 1
src/server/assets.ts

@@ -1,4 +1,4 @@
-import { existsSync, readFileSync } from 'node:fs';
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
 import { join, resolve } from 'node:path';
 import { PNG } from 'pngjs';
 import { parseCharacterStats, type CharacterStats } from '../shared/characters';
@@ -49,6 +49,15 @@ export function readMapImage(assetsDir: string, mapId: string, file: 'background
   return readFileSync(join(assetsDir, 'maps', mapId, file));
 }
 
+/** Ids of every folder in assets/maps that has a map.json. */
+export function listMapIds(assetsDir: string): string[] {
+  const dir = join(assetsDir, 'maps');
+  return readdirSync(dir, { withFileTypes: true })
+    .filter((d) => d.isDirectory() && existsSync(join(dir, d.name, 'map.json')))
+    .map((d) => d.name)
+    .sort();
+}
+
 export interface LoadedMap {
   definition: MapDefinition;
   terrain: TerrainBitmap;

+ 56 - 0
src/server/discovery.ts

@@ -0,0 +1,56 @@
+import { createSocket, type Socket } from 'node:dgram';
+import { networkInterfaces } from 'node:os';
+import { DISCOVERY_INTERVAL_MS, DISCOVERY_PORT } from '../shared/constants';
+import type { Announcement } from '../shared/protocol';
+
+/**
+ * Broadcast addresses to announce on: the subnet broadcast of every IPv4 interface
+ * (Windows sends 255.255.255.255 out of a single interface only), the limited broadcast,
+ * and loopback so a game is always visible on the machine hosting it.
+ */
+export function broadcastAddresses(): string[] {
+  const out = new Set<string>(['255.255.255.255', '127.0.0.1']);
+  for (const list of Object.values(networkInterfaces())) {
+    for (const ni of list ?? []) {
+      if (ni.family !== 'IPv4' || ni.internal) continue;
+      const ip = ni.address.split('.').map(Number);
+      const mask = ni.netmask.split('.').map(Number);
+      out.add(ip.map((b, i) => (b | (~mask[i] & 0xff)) & 0xff).join('.'));
+    }
+  }
+  return [...out];
+}
+
+/** Announces a game on the LAN every DISCOVERY_INTERVAL_MS (readme §3). */
+export class Announcer {
+  private readonly socket: Socket;
+  private timer: NodeJS.Timeout | null = null;
+
+  constructor(private readonly announcement: () => Announcement) {
+    this.socket = createSocket({ type: 'udp4', reuseAddr: true });
+    this.socket.on('error', (err) => console.error('[discovery] socket error:', err.message));
+  }
+
+  start(): void {
+    this.socket.bind(0, () => {
+      this.socket.setBroadcast(true);
+      this.send();
+      this.timer = setInterval(() => this.send(), DISCOVERY_INTERVAL_MS);
+    });
+  }
+
+  stop(): void {
+    if (this.timer) clearInterval(this.timer);
+    this.socket.close();
+  }
+
+  private send(): void {
+    const data = Buffer.from(JSON.stringify(this.announcement()));
+    for (const address of broadcastAddresses()) {
+      this.socket.send(data, DISCOVERY_PORT, address, (err) => {
+        // Some interfaces refuse broadcasts (VPNs, disconnected adapters): not fatal.
+        if (err && address !== '255.255.255.255') console.warn(`[discovery] cannot announce on ${address}: ${err.message}`);
+      });
+    }
+  }
+}

+ 584 - 50
src/server/game.ts

@@ -1,7 +1,26 @@
 import { Circle, World, type Body, type Contact, type ContactImpulse, type Fixture } from 'planck';
-import { Anim, createCharacter, type Character, type CharacterContext, type CharacterStats } from '../shared/characters';
+import {
+  Anim,
+  createCharacter,
+  type Blast,
+  type Character,
+  type CharacterContext,
+  type CharacterStats,
+  type ProjectileSpec,
+} from '../shared/characters';
 import {
   AIR_CONTROL,
+  CANDLE_ARM_S,
+  CANDLE_BLAST_POWER,
+  CANDLE_BLAST_RADIUS,
+  CANDLE_FUSE_S,
+  CANDLE_KNOCKBACK,
+  CANDLE_STUN_S,
+  CANDLE_THROW_SPEED,
+  CHERRY_DROP_SPEED,
+  CHERRY_POINTS_PER_S,
+  CHERRY_RADIUS,
+  CHERRY_REGRAB_DELAY,
   CHUNK_GLUE_PX,
   CHUNK_MERGE_RETRY,
   CHUNK_REST_ANGULAR,
@@ -10,30 +29,59 @@ import {
   COYOTE_TIME,
   CRUSH_IMPULSE,
   CRUSH_MIN_SPEED,
+  CUSTARD_SINK_PX,
+  FINAL_RUSH_S,
   GRAVITY_PX,
   GROUND_NORMAL_Y,
+  ITEM_LIFETIME_S,
+  ITEM_RADIUS,
   JUMP_BUFFER_TIME,
   JUMP_CUT,
+  MATERIAL_WOOL,
   MIN_CHUNK_PIXELS,
   OUT_OF_MAP_MARGIN,
   PIXELS_PER_METER,
+  PROJECTILE_ARM_S,
   RESIZE_THRESHOLD_PX,
+  RESPAWN_DELAY_S,
+  SMARTIES_DURATION_S,
+  SMARTIES_SPEED_MULT,
+  SPOON_LAUNCH_SPEED,
   TICK_DT,
+  WHISK_CRACK_POWER,
+  WHISK_CRACK_RADIUS,
+  WHISK_CRACKS,
+  WHISK_JOLT,
+  WHISK_STUN_S,
+  WIND_GROUND_FACTOR,
+  WOOL_BURN_RADIUS_FACTOR,
 } from '../shared/constants';
 import { Button, EMPTY_INPUT, isDown, type InputState } from '../shared/input';
 import type { MapDefinition } from '../shared/maps/loader';
 import type { MaterialRegistry } from '../shared/materials';
-import type { ChunkInfo, ChunkState, PlayerInfo, PlayerState } from '../shared/protocol';
+import type { ChunkInfo, ChunkState, EntityKind, FxEvent, ItemKind, ItemState, PlayerInfo, PlayerState, RoundState } from '../shared/protocol';
 import { Rng } from '../shared/rng';
 import type { TerrainBitmap } from '../shared/terrain/bitmap';
 import { DetachFinder, type DetachedComponent } from '../shared/terrain/detach';
 import { applyTerrainEvent, rasterizeChunk, type SequencedEvent, type TerrainEvent } from '../shared/terrain/events';
 import type { TerrainOp } from '../shared/terrain/ops';
 import { rleEncode } from '../shared/terrain/rle';
+import { MODIFIERS, type Modifier, type ModifierContext } from './modifiers';
 import { FallingChunk, type FixtureTag } from './physics/fallingChunk';
 import { TerrainColliders } from './physics/terrainColliders';
+import { MatchStats } from './stats';
 
 const PPM = PIXELS_PER_METER;
+const ITEM_KINDS: readonly ItemKind[] = ['candle', 'smarties', 'whisk'];
+const JELLY = 4;
+/** Height above a player's head where a held cherry sits (px). */
+const CHERRY_HOLD_OFFSET = 16;
+/** Columns scanned for a free spoon launch (px between candidates). */
+const SPOON_COLUMN_STEP = 32;
+/** Cap on the spoon's sideways throw (px/s). */
+const SPOON_MAX_VX = 500;
+/** Free space required on each side of the body along the launch column (px). */
+const SPOON_CLEARANCE = 8;
 
 interface ServerPlayer {
   info: PlayerInfo;
@@ -51,13 +99,59 @@ interface ServerPlayer {
   attackCooldown: number;
   specialCooldown: number;
   stun: number;
+  /** Seconds before the spoon sends the player back; 0 = alive. */
+  dead: number;
+  /** Smarties boost time left. */
+  boost: number;
+  /** Spoon flight time left: horizontal momentum is kept unless the player steers. */
+  flight: number;
+  item: ItemKind | null;
+  /** Seconds holding the cherry this round. */
+  score: number;
 }
 
 interface PendingOp {
   op: TerrainOp;
+  /** Player who caused it (0 = the game itself), for stats. */
+  owner: number;
   onApplied?: (removed: number) => void;
 }
 
+/** A lit candle, or a character's projectile. */
+interface Thrown {
+  owner: number;
+  age: number;
+  /** Candle and firecracker: seconds before it blows up on its own. */
+  fuse: number;
+  arm: number;
+  /** Null for a thrown candle. */
+  spec: ProjectileSpec | null;
+  /** Yarn: where the wool thread was last laid. */
+  trailX: number;
+  trailY: number;
+}
+
+interface Item {
+  id: number;
+  kind: EntityKind;
+  body: Body;
+  age: number;
+  /** Set once thrown: then it is a projectile, no longer something to pick up. */
+  thrown: Thrown | null;
+}
+
+const CANDLE_BLAST: Blast = { r: CANDLE_BLAST_RADIUS, power: CANDLE_BLAST_POWER, knockback: CANDLE_KNOCKBACK, stun: CANDLE_STUN_S };
+/** Spacing of the wool discs along a yarn thread (px). */
+const YARN_STEP = 4;
+
+interface Cherry {
+  body: Body;
+  holder: number;
+  /** Player who cannot grab it back yet, and for how long. */
+  blocked: number;
+  blockedFor: number;
+}
+
 export interface Crush {
   id: number;
   x: number;
@@ -67,9 +161,15 @@ export interface Crush {
 /** What happened during one tick, for the transport to broadcast. */
 export interface StepResult {
   terrain: SequencedEvent[];
-  /** Chunks that left without merging (fell off the map). */
+  /** Chunks that left without merging (fell off the map or into the custard). */
   removedChunks: number[];
   crushed: Crush[];
+  fx: FxEvent[];
+}
+
+export interface RoundRules {
+  /** Round length (s). */
+  duration: number;
 }
 
 export interface GameOptions {
@@ -78,20 +178,26 @@ export interface GameOptions {
   materials: MaterialRegistry;
   seed: number;
   loadCharacter: (id: string) => CharacterStats;
+  /** Null during the warm-up: no timer, no cherry, no items, the custard stays put. */
+  rules?: RoundRules | null;
+  /** Match-wide stats sink (trophies). */
+  stats?: MatchStats;
 }
 
-/** Authoritative simulation. Plain Node, no networking: see net.ts for the transport. */
+/** Authoritative simulation of one round. Plain Node, no networking: see net.ts for the transport. */
 export class Game {
   readonly map: MapDefinition;
   readonly terrain: TerrainBitmap;
   readonly seed: number;
   readonly rng: Rng;
+  readonly stats: MatchStats;
   tick = 0;
 
   private readonly world: World;
   private readonly colliders: TerrainColliders;
   private readonly materials: MaterialRegistry;
   private readonly loadCharacter: (id: string) => CharacterStats;
+  private readonly rules: RoundRules | null;
   private readonly players = new Map<number, ServerPlayer>();
   private readonly eventLog: SequencedEvent[] = [];
   private pendingOps: PendingOp[] = [];
@@ -103,6 +209,19 @@ export class Game {
   private nextPlayerId = 1;
   private nextSpawn = 0;
 
+  private custardY: number;
+  private timeLeft: number;
+  private cherry: Cherry | null = null;
+  private readonly items = new Map<number, Item>();
+  private nextItemId = 1;
+  private itemTimer = 0;
+  /** FX produced outside step() bookkeeping (hits, pickups), flushed into the step result. */
+  private fx: FxEvent[] = [];
+  private readonly modifiers: Modifier[] = [];
+  private readonly modifierCtx: ModifierContext;
+  /** Side wind this tick (px/s²). */
+  private wind = 0;
+
   constructor(opts: GameOptions) {
     this.map = opts.map;
     this.terrain = opts.terrain;
@@ -110,17 +229,46 @@ export class Game {
     this.seed = opts.seed;
     this.rng = new Rng(opts.seed);
     this.loadCharacter = opts.loadCharacter;
+    this.rules = opts.rules ?? null;
+    this.stats = opts.stats ?? new MatchStats();
     this.world = new World({ gravity: { x: 0, y: GRAVITY_PX / PPM } });
     this.colliders = new TerrainColliders(this.world, this.terrain);
     this.colliders.rebuildDirty();
     this.finder = new DetachFinder(this.terrain);
     this.world.on('post-solve', (contact, impulse) => this.onPostSolve(contact, impulse));
+
+    this.custardY = this.map.custard.startY;
+    this.timeLeft = this.rules?.duration ?? Infinity;
+    if (this.rules) {
+      this.spawnCherry();
+      this.itemTimer = this.nextItemDelay();
+      // Map modifiers only run during rounds (ids are validated when the server builds its map catalog).
+      for (const id of this.map.modifiers) {
+        const make = MODIFIERS[id];
+        if (make) this.modifiers.push(make());
+      }
+    }
+    this.modifierCtx = {
+      rng: this.rng,
+      terrain: this.terrain,
+      queueOp: (op) => this.queueOp(op),
+      setWind: (accel) => (this.wind = accel),
+    };
   }
 
   get events(): readonly SequencedEvent[] {
     return this.eventLog;
   }
 
+  /** True once the round timer has run out. */
+  get roundOver(): boolean {
+    return this.rules !== null && this.timeLeft <= 0;
+  }
+
+  get custardLevel(): number {
+    return this.custardY;
+  }
+
   chunkInfos(): ChunkInfo[] {
     return [...this.chunks.values()].map((c) => c.info());
   }
@@ -133,9 +281,15 @@ export class Game {
     return [...this.players.values()].map((p) => p.info);
   }
 
-  addPlayer(name: string, characterId: string): PlayerInfo {
+  /** Whole points scored this round, by player id. */
+  scores(): Map<number, number> {
+    return new Map([...this.players.values()].map((p) => [p.info.id, Math.floor(p.score)]));
+  }
+
+  /** Adds a player. The transport passes its own `id` so players keep it across rounds. */
+  addPlayer(name: string, characterId: string, id = this.nextPlayerId++): PlayerInfo {
     const stats = this.loadCharacter(characterId);
-    const id = this.nextPlayerId++;
+    this.nextPlayerId = Math.max(this.nextPlayerId, id + 1);
     const body = this.world.createBody({ type: 'dynamic', fixedRotation: true, bullet: true });
     const info: PlayerInfo = { id, name, characterId, radius: stats.size };
     const player: ServerPlayer = {
@@ -153,15 +307,21 @@ export class Game {
       attackCooldown: 0,
       specialCooldown: 0,
       stun: 0,
+      dead: 0,
+      boost: 0,
+      flight: 0,
+      item: null,
+      score: 0,
     };
     this.players.set(id, player);
-    this.respawn(player);
+    this.placeAtSpawn(player);
     return info;
   }
 
   removePlayer(id: number): void {
     const p = this.players.get(id);
     if (!p) return;
+    if (this.cherry?.holder === id) this.dropCherry(p);
     this.world.destroyBody(p.body);
     this.players.delete(id);
   }
@@ -181,25 +341,33 @@ export class Game {
   }
 
   /** Queues an op, applied later in this step (in queue order). */
-  queueOp(op: TerrainOp, onApplied?: (removed: number) => void): void {
-    this.pendingOps.push({ op, onApplied });
+  queueOp(op: TerrainOp, onApplied?: (removed: number) => void, owner = 0): void {
+    this.pendingOps.push({ op, owner, onApplied });
+  }
+
+  /** Spawns an item now (tests and debug). */
+  spawnItem(kind: EntityKind, x: number, y: number): number {
+    const id = this.nextItemId++;
+    const body = this.world.createBody({ type: 'dynamic', position: { x: x / PPM, y: y / PPM }, bullet: true, userData: { item: id } });
+    body.createFixture(new Circle(ITEM_RADIUS / PPM), { density: 0.6, friction: 0.6, restitution: 0.25, userData: { item: id } satisfies FixtureTag });
+    this.items.set(id, { id, kind, body, age: 0, thrown: null });
+    return id;
   }
 
   /** Advances one fixed tick. Terrain events in the result must be broadcast as-is, in order. */
   step(): StepResult {
-    const result: StepResult = { terrain: [], removedChunks: [], crushed: [] };
+    const result: StepResult = { terrain: [], removedChunks: [], crushed: [], fx: [] };
     for (const p of this.players.values()) this.updatePlayer(p);
 
     const pending = this.pendingOps;
     this.pendingOps = [];
-    for (const { op, onApplied } of pending) {
+    for (const { op, owner, onApplied } of pending) {
       const { changed, removedByMaterial } = this.emit({ kind: 'op', op }, result);
-      if (onApplied) {
-        let removed = 0;
-        for (const n of removedByMaterial.values()) removed += n;
-        onApplied(removed);
-      }
-      if (changed) for (const component of this.finder.find(changed)) this.detach(component, result);
+      let removed = 0;
+      for (const n of removedByMaterial.values()) removed += n;
+      this.stats.add(owner, 'eaten', removed);
+      onApplied?.(removed);
+      if (changed) for (const component of this.finder.find(changed)) this.detach(component, owner, result);
     }
     this.syncTerrain(result);
 
@@ -207,23 +375,75 @@ export class Game {
     this.world.step(TICK_DT, 8, 3);
     for (const id of this.crushedThisStep) {
       const p = this.players.get(id);
-      if (!p) continue;
+      if (!p || p.dead > 0) continue;
       const pos = p.body.getPosition();
       result.crushed.push({ id, x: pos.x * PPM, y: pos.y * PPM });
-      this.respawn(p);
+      this.kill(p, 'crushed');
     }
     for (const p of this.players.values()) this.postStep(p);
+    this.updateRound();
+    this.updateCherry();
+    this.updateItems();
     this.updateChunks(result);
     this.syncTerrain(result);
+    result.fx = this.fx;
+    this.fx = [];
     this.tick++;
     return result;
   }
 
+  snapshot(): PlayerState[] {
+    return [...this.players.values()].map((p) => {
+      const pos = p.body.getPosition();
+      const vel = p.body.getLinearVelocity();
+      return {
+        id: p.info.id,
+        x: pos.x * PPM,
+        y: pos.y * PPM,
+        vx: vel.x * PPM,
+        vy: vel.y * PPM,
+        facing: p.facing,
+        grounded: p.grounded,
+        size: p.character.size,
+        anim:
+          p.character.anim() | (p.stun > 0 ? Anim.Stunned : 0) | (p.dead > 0 ? Anim.Dead : 0) | (p.boost > 0 ? Anim.Boosted : 0),
+        score: Math.floor(p.score),
+        item: p.item,
+      };
+    });
+  }
+
+  itemStates(): ItemState[] {
+    return [...this.items.values()].map((it) => {
+      const pos = it.body.getPosition();
+      return { id: it.id, kind: it.kind, x: pos.x * PPM, y: pos.y * PPM, angle: it.body.getAngle(), lit: it.thrown !== null };
+    });
+  }
+
+  roundState(): RoundState {
+    let cherry: RoundState['cherry'] = null;
+    if (this.cherry) {
+      const pos = this.cherry.body.getPosition();
+      cherry = { x: pos.x * PPM, y: pos.y * PPM, holder: this.cherry.holder };
+    }
+    return {
+      custardY: this.custardY,
+      timeLeft: this.rules ? Math.max(0, this.timeLeft) : null,
+      finalRush: this.rules !== null && this.timeLeft <= FINAL_RUSH_S,
+      wind: this.wind,
+      cherry,
+    };
+  }
+
+  // ---------------------------------------------------------------- terrain
+
   /** Rebuilds colliders after terrain changes and wakes every body that may have lost its support. */
   private syncTerrain(result: StepResult): void {
     if (this.colliders.rebuildDirty() === 0 && result.terrain.length === 0) return;
     for (const p of this.players.values()) p.body.setAwake(true);
     for (const c of this.chunks.values()) c.body.setAwake(true);
+    for (const it of this.items.values()) it.body.setAwake(true);
+    this.cherry?.body.setAwake(true);
   }
 
   /** Applies a terrain event and logs it if it changed anything. */
@@ -240,20 +460,24 @@ export class Game {
   }
 
   /** Removes an unanchored component from the bitmap; big ones become falling chunks, small ones crumble. */
-  private detach(c: DetachedComponent, result: StepResult): void {
+  private detach(c: DetachedComponent, owner: number, result: StepResult): void {
     const { x0, y0, x1, y1 } = c.bounds;
     const w = x1 - x0;
     const h = y1 - y0;
     const debris = c.pixelCount < MIN_CHUNK_PIXELS;
     const id = this.nextChunkId++;
     this.emit({ kind: 'detach', id, x: x0, y: y0, w, h, mask: rleEncode(c.mask), debris }, result);
-    if (!debris) this.chunks.set(id, new FallingChunk(this.world, id, c.mask, w, h, x0, y0, this.materials));
+    if (debris) return;
+    this.chunks.set(id, new FallingChunk(this.world, id, c.mask, w, h, x0, y0, this.materials));
+    this.stats.add(owner, 'detached');
   }
 
   private updateChunks(result: StepResult): void {
     for (const chunk of [...this.chunks.values()]) {
-      const pos = chunk.body.getPosition();
-      if (pos.y * PPM > this.terrain.height + OUT_OF_MAP_MARGIN) {
+      const center = chunk.body.getWorldCenter();
+      if (center.y * PPM > Math.min(this.custardY + CUSTARD_SINK_PX * 4, this.terrain.height + OUT_OF_MAP_MARGIN)) {
+        // Swallowed by the custard (readme §5).
+        if (center.y * PPM <= this.terrain.height + OUT_OF_MAP_MARGIN) this.fx.push({ kind: 'splash', id: 0, x: center.x * PPM, y: this.custardY });
         this.removeChunk(chunk);
         result.removedChunks.push(chunk.id);
         continue;
@@ -322,23 +546,7 @@ export class Game {
     if (total > CRUSH_IMPULSE) this.crushedThisStep.add(playerId);
   }
 
-  snapshot(): PlayerState[] {
-    return [...this.players.values()].map((p) => {
-      const pos = p.body.getPosition();
-      const vel = p.body.getLinearVelocity();
-      return {
-        id: p.info.id,
-        x: pos.x * PPM,
-        y: pos.y * PPM,
-        vx: vel.x * PPM,
-        vy: vel.y * PPM,
-        facing: p.facing,
-        grounded: p.grounded,
-        size: p.character.size,
-        anim: p.character.anim() | (p.stun > 0 ? Anim.Stunned : 0),
-      };
-    });
-  }
+  // ---------------------------------------------------------------- players
 
   private createBodyFixture(body: Body, radius: number, mass: number, id: number): Fixture {
     const tag: FixtureTag = { player: id };
@@ -353,8 +561,15 @@ export class Game {
   }
 
   private updatePlayer(p: ServerPlayer): void {
+    if (p.dead > 0) {
+      p.dead -= TICK_DT;
+      if (p.dead <= 0) this.spoonLaunch(p);
+      return;
+    }
     const { stats } = p.character;
     p.stun = Math.max(0, p.stun - TICK_DT);
+    p.boost = Math.max(0, p.boost - TICK_DT);
+    p.flight = Math.max(0, p.flight - TICK_DT);
     // Stunned players keep their momentum but ignore input.
     const input = p.stun > 0 ? { ...p.input, buttons: 0 } : p.input;
     const pressed = input.buttons & ~p.prevButtons;
@@ -365,12 +580,13 @@ export class Game {
     let vx = vel.x * PPM;
     let vy = vel.y * PPM;
     const mobility = p.character.mobility();
+    const speedMult = p.boost > 0 ? SMARTIES_SPEED_MULT : 1;
 
     if (p.stun === 0) {
       const dir = (isDown(input, Button.Right) ? 1 : 0) - (isDown(input, Button.Left) ? 1 : 0);
-      const accel = stats.acceleration * (p.grounded ? 1 : AIR_CONTROL) * TICK_DT;
-      const target = dir * stats.speed * mobility;
-      vx = vx < target ? Math.min(target, vx + accel) : Math.max(target, vx - accel);
+      const accel = stats.acceleration * speedMult * (p.grounded ? 1 : AIR_CONTROL) * TICK_DT;
+      const target = dir * stats.speed * mobility * speedMult;
+      if (dir !== 0 || p.flight === 0) vx = vx < target ? Math.min(target, vx + accel) : Math.max(target, vx - accel);
       p.facing = dir !== 0 ? dir : input.aimX >= p.body.getPosition().x * PPM ? 1 : -1;
     }
 
@@ -382,8 +598,12 @@ export class Game {
     } else if (released & Button.Jump && vy < 0) {
       vy *= JUMP_CUT;
     }
+    // Wind: full push in the air, partial on the ground.
+    vx += this.wind * (p.grounded ? WIND_GROUND_FACTOR : 1) * TICK_DT;
     p.body.setLinearVelocity({ x: vx / PPM, y: vy / PPM });
 
+    if (pressed & Button.Use && p.item === 'candle') this.throwCandle(p, input);
+
     p.attackCooldown = Math.max(0, p.attackCooldown - TICK_DT);
     p.specialCooldown = Math.max(0, p.specialCooldown - TICK_DT);
     const ctx = this.contextFor(p, input);
@@ -399,6 +619,7 @@ export class Game {
   }
 
   private postStep(p: ServerPlayer): void {
+    if (p.dead > 0) return;
     p.grounded = false;
     for (let edge = p.body.getContactList(); edge; edge = edge.next) {
       const contact = edge.contact;
@@ -413,32 +634,96 @@ export class Game {
       }
     }
     p.sinceGrounded = p.grounded ? 0 : p.sinceGrounded + TICK_DT;
-    if (p.body.getPosition().y * PPM > this.terrain.height + OUT_OF_MAP_MARGIN) this.respawn(p);
+    // Landing ends the spoon flight; brushing an edge on the way up does not.
+    if (p.grounded && p.body.getLinearVelocity().y >= 0) p.flight = 0;
+    const y = p.body.getPosition().y * PPM;
+    if (y > this.custardY + CUSTARD_SINK_PX || y > this.terrain.height + OUT_OF_MAP_MARGIN) {
+      this.fx.push({ kind: 'splash', id: p.info.id, x: p.body.getPosition().x * PPM, y: this.custardY });
+      this.kill(p, 'custard');
+    }
+  }
+
+  /** Out of the round for RESPAWN_DELAY_S: falls in the custard or crushed (readme §4). */
+  private kill(p: ServerPlayer, cause: 'custard' | 'crushed'): void {
+    if (this.cherry?.holder === p.info.id) this.dropCherry(p);
+    this.stats.add(p.info.id, cause);
+    p.dead = RESPAWN_DELAY_S;
+    p.stun = 0;
+    p.item = null;
+    p.body.setLinearVelocity({ x: 0, y: 0 });
+    p.body.setActive(false);
   }
 
-  private respawn(p: ServerPlayer): void {
+  private placeAtSpawn(p: ServerPlayer): void {
     const [x, y] = this.map.spawns[this.nextSpawn++ % this.map.spawns.length];
     p.body.setPosition({ x: x / PPM, y: y / PPM });
     p.body.setLinearVelocity({ x: 0, y: 0 });
     p.stun = 0;
   }
 
-  private hit(attacker: ServerPlayer, x: number, y: number, r: number, knockback: number, stun: number): number {
+  /**
+   * The spoon catapult: from the custard surface, in a column of open air (so the player
+   * does not launch into the cake), as close as possible to a random spawn point.
+   */
+  private spoonLaunch(p: ServerPlayer): void {
+    p.dead = 0;
+    p.body.setActive(true);
+    const [sx, sy] = this.map.spawns[this.rng.int(0, this.map.spawns.length - 1)];
+    const surface = Math.min(this.custardY, this.terrain.height) - p.bodyRadius - 4;
+    const top = Math.max(0, Math.min(sy, surface - 200));
+    let bestX = -1;
+    for (let x = SPOON_COLUMN_STEP; x < this.terrain.width - SPOON_COLUMN_STEP; x += SPOON_COLUMN_STEP) {
+      if (bestX >= 0 && Math.abs(x - sx) >= Math.abs(bestX - sx)) continue;
+      if (this.columnIsFree(x, p.bodyRadius, top, surface)) bestX = x;
+    }
+    if (bestX < 0) {
+      this.placeAtSpawn(p);
+      return;
+    }
+    p.body.setPosition({ x: bestX / PPM, y: surface / PPM });
+    // Aim the arc at the spawn closest to the launch column (the random one may be across the map,
+    // out of reach): flight time ≈ 2·v/g.
+    let tx = sx;
+    for (const [x] of this.map.spawns) if (Math.abs(x - bestX) < Math.abs(tx - bestX)) tx = x;
+    const flight = (2 * SPOON_LAUNCH_SPEED) / GRAVITY_PX;
+    const vx = Math.max(-SPOON_MAX_VX, Math.min(SPOON_MAX_VX, (tx - bestX) / flight));
+    p.body.setLinearVelocity({ x: vx / PPM, y: -SPOON_LAUNCH_SPEED / PPM });
+    p.body.setAwake(true);
+    p.flight = flight;
+    this.fx.push({ kind: 'spoon', id: p.info.id, x: bestX, y: this.custardY });
+  }
+
+  private columnIsFree(x: number, radius: number, top: number, bottom: number): boolean {
+    for (let y = Math.floor(top); y <= bottom; y += 2) {
+      // Keep a margin around the body so the launch does not scrape a ledge.
+      for (const dx of [-radius - SPOON_CLEARANCE, -radius / 2, 0, radius / 2, radius + SPOON_CLEARANCE]) {
+        if (this.terrain.isSolid(Math.round(x + dx), y)) return false;
+      }
+    }
+    return true;
+  }
+
+  /** Knocks back and stuns players touching the disc. `attacker` is spared (null = everyone is hit, e.g. explosions). */
+  private hitArea(attacker: ServerPlayer | null, x: number, y: number, r: number, knockback: number, stun: number): number {
     let count = 0;
     for (const target of this.players.values()) {
-      if (target === attacker) continue;
+      if (target === attacker || target.dead > 0) continue;
       const pos = target.body.getPosition();
       const dx = pos.x * PPM - x;
       const dy = pos.y * PPM - y;
       const dist = Math.hypot(dx, dy);
       if (dist > r + target.bodyRadius) continue;
       // Push away from the hit point, always with some lift so the target pops up.
-      const nx = dist > 0 ? dx / dist : attacker.facing;
+      const nx = dist > 0 ? dx / dist : (attacker?.facing ?? 1);
       const ny = Math.min(dist > 0 ? dy / dist : 0, -0.4);
       const len = Math.hypot(nx, ny);
       target.body.setLinearVelocity({ x: ((nx / len) * knockback) / PPM, y: ((ny / len) * knockback) / PPM });
       target.stun = Math.max(target.stun, stun);
       target.character.onHit(this.contextFor(target, target.input));
+      // A hit holder lets the cherry go (readme §4).
+      if (this.cherry?.holder === target.info.id) this.dropCherry(target);
+      this.stats.add(target.info.id, 'hitTaken');
+      if (attacker) this.stats.add(attacker.info.id, 'hits');
       count++;
     }
     return count;
@@ -455,10 +740,259 @@ export class Game {
       grounded: p.grounded,
       facing: p.facing,
       input,
-      emitOp: (op, onApplied) => this.queueOp(op, onApplied),
+      emitOp: (op, onApplied) => this.queueOp(op, onApplied, p.info.id),
       setVelocity: (vx, vy) => p.body.setLinearVelocity({ x: vx / PPM, y: vy / PPM }),
       setSize: (radius) => this.resize(p, radius),
-      hit: (x, y, r, knockback, stun) => this.hit(p, x, y, r, knockback, stun),
+      hit: (x, y, r, knockback, stun) => this.hitArea(p, x, y, r, knockback, stun),
+      launch: (spec, x, y, vx, vy) => this.throwEntity(spec.kind, spec, p.info.id, x, y, vx, vy),
+      explode: (x, y, blast, spareSelf) => this.explodeAt(x, y, blast, p.info.id, spareSelf ? p : null),
     };
   }
+
+  private alivePlayers(): ServerPlayer[] {
+    return [...this.players.values()].filter((p) => p.dead === 0);
+  }
+
+  // ---------------------------------------------------------------- round
+
+  private updateRound(): void {
+    if (!this.rules) return;
+    for (const m of this.modifiers) m.tick(this.modifierCtx, TICK_DT);
+    if (this.wind !== 0) {
+      // Loose things drift too.
+      const push = (body: Body): void => {
+        const v = body.getLinearVelocity();
+        body.setLinearVelocity({ x: v.x + (this.wind * TICK_DT) / PPM, y: v.y });
+      };
+      for (const it of this.items.values()) push(it.body);
+      if (this.cherry && this.cherry.holder === 0) push(this.cherry.body);
+    }
+    this.timeLeft -= TICK_DT;
+    const c = this.map.custard;
+    const speed = this.timeLeft <= FINAL_RUSH_S ? c.finalRushSpeed : c.speed;
+    this.custardY = Math.max(0, this.custardY - speed * TICK_DT);
+  }
+
+  private spawnCherry(): void {
+    const [x, y] = this.map.cherrySpawn;
+    const body = this.world.createBody({ type: 'dynamic', position: { x: x / PPM, y: y / PPM }, bullet: true });
+    body.createFixture(new Circle(CHERRY_RADIUS / PPM), { density: 0.6, friction: 0.5, restitution: 0.35, userData: { cherry: true } satisfies FixtureTag });
+    this.cherry = { body, holder: 0, blocked: 0, blockedFor: 0 };
+  }
+
+  private updateCherry(): void {
+    const cherry = this.cherry;
+    if (!cherry) return;
+    cherry.blockedFor = Math.max(0, cherry.blockedFor - TICK_DT);
+    const holder = cherry.holder ? this.players.get(cherry.holder) : undefined;
+    if (holder) {
+      // Held: it rides above the holder's head and scores 1 point per second.
+      const pos = holder.body.getPosition();
+      cherry.body.setPosition({ x: pos.x, y: pos.y - (holder.character.size + CHERRY_HOLD_OFFSET) / PPM });
+      holder.score += CHERRY_POINTS_PER_S * TICK_DT;
+      this.stats.add(holder.info.id, 'cherry', TICK_DT);
+      return;
+    }
+    cherry.holder = 0;
+    const pos = cherry.body.getPosition();
+    if (pos.y * PPM > this.custardY + CUSTARD_SINK_PX || pos.y * PPM > this.terrain.height + OUT_OF_MAP_MARGIN) {
+      this.fx.push({ kind: 'splash', id: 0, x: pos.x * PPM, y: this.custardY });
+      const [x, y] = this.map.cherrySpawn;
+      cherry.body.setPosition({ x: x / PPM, y: y / PPM });
+      cherry.body.setLinearVelocity({ x: 0, y: 0 });
+      return;
+    }
+    for (const p of this.alivePlayers()) {
+      if (p.stun > 0 || (cherry.blocked === p.info.id && cherry.blockedFor > 0)) continue;
+      const pp = p.body.getPosition();
+      if (Math.hypot(pp.x - pos.x, pp.y - pos.y) * PPM > p.bodyRadius + CHERRY_RADIUS + 4) continue;
+      cherry.holder = p.info.id;
+      cherry.body.setActive(false);
+      this.fx.push({ kind: 'pickup', id: p.info.id, item: 'cherry', x: pos.x * PPM, y: pos.y * PPM });
+      return;
+    }
+  }
+
+  /** The holder lets the cherry go: it pops out and rolls (readme §4). */
+  private dropCherry(p: ServerPlayer): void {
+    const cherry = this.cherry;
+    if (!cherry || cherry.holder !== p.info.id) return;
+    const pos = p.body.getPosition();
+    cherry.holder = 0;
+    cherry.blocked = p.info.id;
+    cherry.blockedFor = CHERRY_REGRAB_DELAY;
+    cherry.body.setActive(true);
+    cherry.body.setPosition({ x: pos.x, y: pos.y - (p.character.size + CHERRY_HOLD_OFFSET) / PPM });
+    const angle = -Math.PI / 2 + this.rng.range(-0.8, 0.8);
+    cherry.body.setLinearVelocity({ x: (Math.cos(angle) * CHERRY_DROP_SPEED) / PPM, y: (Math.sin(angle) * CHERRY_DROP_SPEED) / PPM });
+    cherry.body.setAwake(true);
+    this.fx.push({ kind: 'cherryDrop', id: p.info.id, x: pos.x * PPM, y: pos.y * PPM });
+  }
+
+  // ---------------------------------------------------------------- items
+
+  private nextItemDelay(): number {
+    const [a, b] = this.map.items.interval;
+    return this.rng.range(a, b);
+  }
+
+  private updateItems(): void {
+    if (this.rules) {
+      this.itemTimer -= TICK_DT;
+      if (this.itemTimer <= 0) {
+        this.itemTimer = this.nextItemDelay();
+        const weights: Partial<Record<ItemKind, number>> = {};
+        for (const k of ITEM_KINDS) if ((this.map.items.weights[k] ?? 0) > 0) weights[k] = this.map.items.weights[k];
+        if (Object.keys(weights).length > 0) {
+          const kind = this.rng.weighted(weights as Record<ItemKind, number>);
+          this.spawnItem(kind, this.rng.int(80, this.terrain.width - 80), -ITEM_RADIUS * 2);
+        }
+      }
+    }
+
+    for (const item of [...this.items.values()]) {
+      const pos = item.body.getPosition();
+      const x = pos.x * PPM;
+      const y = pos.y * PPM;
+      if (y > this.custardY + CUSTARD_SINK_PX || y > this.terrain.height + OUT_OF_MAP_MARGIN) {
+        this.fx.push({ kind: 'splash', id: 0, x, y: this.custardY });
+        this.removeItem(item);
+        continue;
+      }
+      if (item.thrown) {
+        this.updateThrown(item, item.thrown, x, y);
+        continue;
+      }
+      item.age += TICK_DT;
+      if (item.age > ITEM_LIFETIME_S) {
+        this.removeItem(item);
+        continue;
+      }
+      for (const p of this.alivePlayers()) {
+        const pp = p.body.getPosition();
+        if (Math.hypot(pp.x * PPM - x, pp.y * PPM - y) > p.bodyRadius + ITEM_RADIUS + 4) continue;
+        if (item.kind === 'candle' && p.item !== null) continue; // one candle at a time
+        this.pickUp(p, item, x, y);
+        break;
+      }
+    }
+  }
+
+  private pickUp(p: ServerPlayer, item: Item, x: number, y: number): void {
+    if (item.kind === 'firecracker' || item.kind === 'yarn') return; // projectiles are not pickups
+    this.removeItem(item);
+    this.fx.push({ kind: 'pickup', id: p.info.id, item: item.kind, x, y });
+    if (item.kind === 'candle') p.item = 'candle';
+    else if (item.kind === 'smarties') p.boost = SMARTIES_DURATION_S;
+    else if (item.kind === 'whisk') this.whisk(p);
+  }
+
+  private removeItem(item: Item): void {
+    this.world.destroyBody(item.body);
+    this.items.delete(item.id);
+  }
+
+  private touchesAnything(body: Body): boolean {
+    for (let edge = body.getContactList(); edge; edge = edge.next) if (edge.contact.isTouching()) return true;
+    return false;
+  }
+
+  private throwCandle(p: ServerPlayer, input: InputState): void {
+    p.item = null;
+    const pos = p.body.getPosition();
+    const px = pos.x * PPM;
+    const py = pos.y * PPM;
+    let dx = input.aimX - px;
+    let dy = input.aimY - py;
+    const len = Math.hypot(dx, dy) || 1;
+    dx /= len;
+    dy /= len;
+    const start = p.bodyRadius + ITEM_RADIUS + 2;
+    const v = p.body.getLinearVelocity();
+    this.throwEntity('candle', null, p.info.id, px + dx * start, py + dy * start, v.x * PPM + dx * CANDLE_THROW_SPEED, v.y * PPM + dy * CANDLE_THROW_SPEED);
+    this.stats.add(p.info.id, 'candles');
+  }
+
+  /** Spawns a projectile entity already in flight. */
+  private throwEntity(kind: EntityKind, spec: ProjectileSpec | null, owner: number, x: number, y: number, vx: number, vy: number): void {
+    const id = this.spawnItem(kind, x, y);
+    const item = this.items.get(id)!;
+    const fuse = spec?.kind === 'firecracker' ? spec.fuse : spec?.kind === 'yarn' ? Infinity : CANDLE_FUSE_S;
+    item.thrown = { owner, age: 0, fuse, arm: spec ? PROJECTILE_ARM_S : CANDLE_ARM_S, spec, trailX: x, trailY: y };
+    item.body.setLinearVelocity({ x: vx / PPM, y: vy / PPM });
+    item.body.setAngularVelocity(vx >= 0 ? 12 : -12);
+  }
+
+  private updateThrown(item: Item, t: Thrown, x: number, y: number): void {
+    t.age += TICK_DT;
+    t.fuse -= TICK_DT;
+    const hit = t.age >= t.arm && this.touchesAnything(item.body);
+    const spec = t.spec;
+    if (spec?.kind === 'yarn') {
+      this.layThread(item, t, spec, x, y);
+      if (hit || t.age >= spec.life) {
+        // The ball sticks where it lands (or gives up mid-air): a blob of wool.
+        this.removeItem(item);
+        this.queueOp({ kind: 'fill', x: Math.round(x), y: Math.round(y), r: spec.blobRadius, material: spec.material }, undefined, t.owner);
+      }
+      return;
+    }
+    if (t.fuse <= 0 || hit) {
+      this.removeItem(item);
+      this.explodeAt(x, y, spec?.kind === 'firecracker' ? spec.blast : CANDLE_BLAST, t.owner, null);
+    }
+  }
+
+  /** Lays wool discs from the last thread point up to just behind the ball, so the ball never sits in its own wool. */
+  private layThread(item: Item, t: Thrown, spec: Extract<ProjectileSpec, { kind: 'yarn' }>, x: number, y: number): void {
+    const v = item.body.getLinearVelocity();
+    const speed = Math.hypot(v.x, v.y);
+    if (speed === 0) return;
+    const back = ITEM_RADIUS + spec.trailRadius + 3;
+    const tx = x - (v.x / speed) * back;
+    const ty = y - (v.y / speed) * back;
+    let dist = Math.hypot(tx - t.trailX, ty - t.trailY);
+    while (dist >= YARN_STEP) {
+      t.trailX += ((tx - t.trailX) / dist) * YARN_STEP;
+      t.trailY += ((ty - t.trailY) / dist) * YARN_STEP;
+      this.queueOp({ kind: 'fill', x: Math.round(t.trailX), y: Math.round(t.trailY), r: spec.trailRadius, material: spec.material }, undefined, t.owner);
+      dist -= YARN_STEP;
+    }
+  }
+
+  /**
+   * Every explosion: carves the cake (chocolate resists), burns the wool around it
+   * (Mamie's constructions burn, readme §4) and blows players away, `spare` excepted.
+   */
+  private explodeAt(x: number, y: number, blast: Blast, owner: number, spare: ServerPlayer | null): void {
+    const cx = Math.round(x);
+    const cy = Math.round(y);
+    this.queueOp({ kind: 'carve', x: cx, y: cy, r: Math.round(blast.r), power: Math.round(blast.power) }, undefined, owner);
+    this.queueOp({ kind: 'convert', x: cx, y: cy, r: Math.round(blast.r * WOOL_BURN_RADIUS_FACTOR), from: MATERIAL_WOOL, to: 0 }, undefined, owner);
+    const hits = this.hitArea(spare, x, y, blast.r + 10, blast.knockback, blast.stun);
+    this.stats.add(owner, 'hits', hits);
+    this.fx.push({ kind: 'explosion', x, y, r: blast.r });
+  }
+
+  /** Electric whisk: jolts everyone else and shakes jelly loose, so weakened blocks come off (readme §4). */
+  private whisk(p: ServerPlayer): void {
+    this.fx.push({ kind: 'whisk', id: p.info.id });
+    for (const other of this.alivePlayers()) {
+      if (other === p) continue;
+      const v = other.body.getLinearVelocity();
+      other.body.setLinearVelocity({ x: v.x + this.rng.range(-0.5, 0.5) * (WHISK_JOLT / PPM), y: v.y - WHISK_JOLT / PPM });
+      other.stun = Math.max(other.stun, WHISK_STUN_S);
+      if (this.cherry?.holder === other.info.id) this.dropCherry(other);
+    }
+    const { width, height, data } = this.terrain;
+    for (let n = 0; n < WHISK_CRACKS; n++) {
+      for (let tries = 0; tries < 40; tries++) {
+        const x = this.rng.int(0, width - 1);
+        const y = this.rng.int(0, height - 1);
+        if (data[y * width + x] !== JELLY) continue;
+        this.queueOp({ kind: 'carve', x, y, r: WHISK_CRACK_RADIUS, power: WHISK_CRACK_POWER }, undefined, p.info.id);
+        break;
+      }
+    }
+  }
 }

+ 66 - 14
src/server/index.ts

@@ -1,8 +1,15 @@
 // Server entry point. Runs headless (`npm run server`) or inside an Electron utilityProcess.
-import { DEFAULT_MAP_ID, NET_PORT } from '../shared/constants';
-import { loadCharacterStats, loadMap, loadMaterials, resolveAssetsDir } from './assets';
-import { Game } from './game';
+// Arguments: --map=<id> --port=<n> --seed=<n> --name=<game name>
+// Pacing (testing): --round=<seconds> --rounds=<n> --pause=<seconds between rounds and after the match>
+import { randomUUID } from 'node:crypto';
+import { DEFAULT_MAP_ID, MAX_PLAYERS, NET_PORT, PROTOCOL_VERSION } from '../shared/constants';
+import type { MapSummary } from '../shared/protocol';
+import { listMapIds, loadCharacterStats, loadMap, loadMaterials, resolveAssetsDir } from './assets';
+import { Announcer } from './discovery';
+import { Game, type RoundRules } from './game';
+import { isModifierId } from './modifiers';
 import { GameServer } from './net';
+import type { MatchStats } from './stats';
 
 interface ParentPort {
   postMessage(message: unknown): void;
@@ -20,26 +27,71 @@ function main(): void {
   const assetsDir = resolveAssetsDir();
   const mapId = arg('map') ?? DEFAULT_MAP_ID;
   const port = Number(arg('port') ?? NET_PORT);
+  const name = (arg('name') ?? 'Goûter').slice(0, 40);
   // The only place the seed is drawn; everything downstream uses the seeded RNG.
   const seed = Number(arg('seed') ?? Date.now() % 0x7fffffff);
 
   const materials = loadMaterials(assetsDir);
-  const { definition, terrain } = loadMap(assetsDir, mapId, materials);
-  const game = new Game({
-    map: definition,
-    terrain,
-    materials,
-    seed,
-    loadCharacter: (id) => loadCharacterStats(assetsDir, id),
-  });
+  // Validate every map once at startup (readme §6): a broken map is rejected with an explicit
+  // message and never offered, rather than failing mid-game.
+  const maps: MapSummary[] = [];
+  for (const id of listMapIds(assetsDir)) {
+    try {
+      const { definition } = loadMap(assetsDir, id, materials);
+      const unknown = definition.modifiers.filter((m) => !isModifierId(m));
+      if (unknown.length > 0) throw new Error(`Map "${id}" rejected: unknown modifier(s) ${unknown.join(', ')}`);
+      maps.push({ id, name: definition.name });
+    } catch (err) {
+      console.error(`[server] ${err instanceof Error ? err.message : String(err)}`);
+    }
+  }
+  // --map puts a map first, so it is the warm-up map.
+  maps.sort((a, b) => Number(b.id === mapId) - Number(a.id === mapId));
+  if (maps.length === 0) throw new Error('No valid map in assets/maps');
+  const createGame = (gameSeed: number, rules: RoundRules | null, stats: MatchStats, gameMap: string): Game => {
+    const { definition, terrain } = loadMap(assetsDir, gameMap, materials);
+    return new Game({ map: definition, terrain, materials, seed: gameSeed, rules, stats, loadCharacter: (id) => loadCharacterStats(assetsDir, id) });
+  };
 
-  const server = new GameServer(game, port, '0.0.0.0', () => {
-    console.log(`[server] map "${mapId}" (seed ${seed}) listening on :${port}`);
-    parentPort?.postMessage({ type: 'ready', port });
+  const serverId = randomUUID();
+  let announcer: Announcer | null = null;
+  const num = (name: string): number | undefined => (arg(name) === undefined ? undefined : Number(arg(name)));
+  const pause = num('pause');
+  const server = new GameServer({
+    createGame,
+    maps,
+    seed,
+    port,
+    roundDuration: num('round'),
+    rounds: num('rounds'),
+    roundEndPause: pause,
+    matchEndPause: pause,
+    onListening: () => {
+      console.log(`[server] "${name}" with ${maps.length} map(s) [${maps.map((m) => m.id).join(', ')}] (seed ${seed}) listening on :${port}`);
+      announcer = new Announcer(() => ({
+        magic: 'goutermageddon',
+        serverId,
+        name,
+        mapId: server.mapId,
+        players: server.playerCount,
+        maxPlayers: MAX_PLAYERS,
+        phase: server.currentPhase,
+        version: PROTOCOL_VERSION,
+        port,
+      }));
+      announcer.start();
+      parentPort?.postMessage({ type: 'ready', port });
+    },
+    onError: (err) => {
+      console.error(`[server] cannot listen on :${port}:`, err.message);
+      parentPort?.postMessage({ type: 'error', message: err.message });
+      process.exit(1);
+    },
   });
   server.start();
 
   const shutdown = (): void => {
+    announcer?.stop();
     server.close();
     process.exit(0);
   };

+ 29 - 0
src/server/modifiers/index.ts

@@ -0,0 +1,29 @@
+import type { Rng } from '../../shared/rng';
+import type { TerrainBitmap } from '../../shared/terrain/bitmap';
+import type { TerrainOp } from '../../shared/terrain/ops';
+import { randomCracks } from './randomCracks';
+import { wind } from './wind';
+
+/** What a map modifier may do to a round. Implemented by the server Game. */
+export interface ModifierContext {
+  readonly rng: Rng;
+  readonly terrain: TerrainBitmap;
+  queueOp(op: TerrainOp): void;
+  /** Sideways push for this tick (px/s²): full strength in the air, reduced on the ground. */
+  setWind(accel: number): void;
+}
+
+/** A special rule of a map (readme §6), active during rounds, not the warm-up. */
+export interface Modifier {
+  tick(ctx: ModifierContext, dt: number): void;
+}
+
+/** Map modifier ids, as written in map.json "modifiers". */
+export const MODIFIERS: Record<string, () => Modifier> = {
+  wind,
+  'random-cracks': randomCracks,
+};
+
+export function isModifierId(id: string): boolean {
+  return Object.hasOwn(MODIFIERS, id);
+}

+ 34 - 0
src/server/modifiers/randomCracks.ts

@@ -0,0 +1,34 @@
+import { CRACK_INTERVAL_S, CRACK_LENGTH, CRACK_POWER, CRACK_RADIUS, CRACK_STEP } from '../../shared/constants';
+import type { Modifier } from './index';
+
+/** Materials that crack on their own (brittle: biscuit). */
+const BRITTLE = 5;
+const TRIES = 80;
+
+/** Random cracks (La Tarte aux Fruits): now and then a zigzag crack opens in brittle material. */
+export function randomCracks(): Modifier {
+  let timer = -1;
+  return {
+    tick(ctx, dt) {
+      if (timer < 0) timer = ctx.rng.range(CRACK_INTERVAL_S[0], CRACK_INTERVAL_S[1]);
+      timer -= dt;
+      if (timer > 0) return;
+      timer = ctx.rng.range(CRACK_INTERVAL_S[0], CRACK_INTERVAL_S[1]);
+      const { width, height, data } = ctx.terrain;
+      for (let t = 0; t < TRIES; t++) {
+        let x = ctx.rng.int(0, width - 1);
+        let y = ctx.rng.int(0, height - 1);
+        if (data[y * width + x] !== BRITTLE) continue;
+        // A mostly vertical zigzag: it cuts through the brittle sheets.
+        let angle = Math.PI / 2 + ctx.rng.range(-0.6, 0.6);
+        for (let i = 0; i < CRACK_LENGTH; i++) {
+          ctx.queueOp({ kind: 'carve', x: Math.round(x), y: Math.round(y), r: CRACK_RADIUS, power: CRACK_POWER });
+          angle += ctx.rng.range(-0.7, 0.7);
+          x += Math.cos(angle) * CRACK_STEP;
+          y += Math.sin(angle) * CRACK_STEP;
+        }
+        return;
+      }
+    },
+  };
+}

+ 21 - 0
src/server/modifiers/wind.ts

@@ -0,0 +1,21 @@
+import { WIND_MAX, WIND_PERIOD_S } from '../../shared/constants';
+import type { Modifier } from './index';
+
+/** Side wind (La Pile de Crêpes): a gust picks a new strength and direction every few seconds. */
+export function wind(): Modifier {
+  let current = 0;
+  let target = 0;
+  let timer = 0;
+  return {
+    tick(ctx, dt) {
+      timer -= dt;
+      if (timer <= 0) {
+        timer = WIND_PERIOD_S;
+        target = ctx.rng.range(-WIND_MAX, WIND_MAX);
+      }
+      // Ease toward the new gust so it never snaps.
+      current += (target - current) * Math.min(1, dt * 1.5);
+      ctx.setWind(current);
+    },
+  };
+}

+ 310 - 54
src/server/net.ts

@@ -1,35 +1,121 @@
 import { Packr } from 'msgpackr';
 import { WebSocketServer, type WebSocket } from 'ws';
 import { isCharacterId } from '../shared/characters';
-import { MAX_CATCHUP_TICKS, PROTOCOL_VERSION, TICK_DT, TICKS_PER_SNAPSHOT } from '../shared/constants';
-import { isClientMessage, type ServerMessage } from '../shared/protocol';
-import type { Game } from './game';
+import {
+  HASH_CHECK_INTERVAL_S,
+  MATCH_END_PAUSE_S,
+  MAX_CATCHUP_TICKS,
+  MAX_PLAYERS,
+  PROTOCOL_VERSION,
+  ROUND_DURATION_S,
+  ROUND_END_PAUSE_S,
+  ROUNDS_PER_MATCH,
+  START_COUNTDOWN_S,
+  TICK_DT,
+  TICK_RATE,
+  TICKS_PER_SNAPSHOT,
+} from '../shared/constants';
+import {
+  isClientMessage,
+  type LobbyPlayer,
+  type MapSummary,
+  type Phase,
+  type RoundResult,
+  type Rotation,
+  type ServerMessage,
+} from '../shared/protocol';
+import { Rng } from '../shared/rng';
+import type { Game, RoundRules } from './game';
+import { DEFAULT_ROTATION, defaultMap, lastPlaced, rotationPool, sanitizeRotation } from './rotation';
+import { MatchStats } from './stats';
 
-const MAX_PLAYERS = 8;
 const packr = new Packr({ useRecords: false });
+const HASH_CHECK_TICKS = HASH_CHECK_INTERVAL_S * TICK_RATE;
 
 interface Client {
   socket: WebSocket;
-  playerId: number | null;
+  player: LobbyPlayer | null;
 }
 
-/** WebSocket transport + fixed-step loop around a Game. */
+export interface GameServerOptions {
+  /** Builds a fresh game on `mapId`: warm-up when `rules` is null, a round otherwise. */
+  createGame: (seed: number, rules: RoundRules | null, stats: MatchStats, mapId: string) => Game;
+  /** Valid maps (see index.ts: rejected maps never get here). Must not be empty. */
+  maps: MapSummary[];
+  seed: number;
+  port: number;
+  host?: string;
+  onListening?: () => void;
+  /** Socket errors (e.g. port already in use). Without a handler they are thrown. */
+  onError?: (err: Error) => void;
+  // Match pacing, overridable for tests (seconds / count).
+  roundDuration?: number;
+  rounds?: number;
+  roundEndPause?: number;
+  matchEndPause?: number;
+}
+
+/**
+ * WebSocket transport + fixed-step loop around a Game, and the match flow (readme §4):
+ * lobby (warm-up, everyone ready) → rounds, each on a fresh map, with results in between
+ * → final results and trophies → back to the lobby, where one click restarts.
+ */
 export class GameServer {
   private readonly wss: WebSocketServer;
   private readonly clients = new Set<Client>();
+  private readonly rng: Rng;
+  private game: Game;
+  private phase: Phase = 'lobby';
+  /** Ticks left before the match starts, or null. */
+  private countdown: number | null = null;
+  /** Ticks left on the round results / final results screen. */
+  private pause = 0;
+  private round = 0;
+  private stats = new MatchStats();
+  /** Match totals by player id. */
+  private totals = new Map<number, number>();
+  private rotation: Rotation = DEFAULT_ROTATION;
+  /** Who picks the next map during the current round results, and what they picked. */
+  private picker: number | null = null;
+  private pickedMap: string | null = null;
+  private nextPlayerId = 1;
   private timer: NodeJS.Timeout | null = null;
 
-  constructor(
-    private readonly game: Game,
-    port: number,
-    host = '0.0.0.0',
-    onListening?: () => void,
-  ) {
-    this.wss = new WebSocketServer({ port, host });
-    this.wss.on('listening', () => onListening?.());
+  constructor(private readonly opts: GameServerOptions) {
+    if (opts.maps.length === 0) throw new Error('No playable map');
+    this.rng = new Rng(opts.seed);
+    this.game = this.newGame(null, this.warmupMap());
+    this.wss = new WebSocketServer({ port: opts.port, host: opts.host ?? '0.0.0.0' });
+    this.wss.on('listening', () => opts.onListening?.());
+    this.wss.on('error', (err) => {
+      if (!opts.onError) throw err;
+      opts.onError(err);
+    });
     this.wss.on('connection', (socket) => this.onConnection(socket));
   }
 
+  get currentPhase(): Phase {
+    return this.phase;
+  }
+
+  get mapId(): string {
+    return this.game.map.id;
+  }
+
+  get playerCount(): number {
+    return this.players().length;
+  }
+
+  /** The port actually bound (useful when created with port 0). */
+  get port(): number {
+    const addr = this.wss.address();
+    return typeof addr === 'object' && addr ? addr.port : this.opts.port;
+  }
+
+  private get rounds(): number {
+    return this.opts.rounds ?? ROUNDS_PER_MATCH;
+  }
+
   start(): void {
     let last = performance.now();
     let acc = 0;
@@ -54,18 +140,63 @@ export class GameServer {
     this.wss.close();
   }
 
-  private tickOnce(): void {
+  /** Runs one tick by hand (tests). */
+  tickOnce(): void {
+    if (this.phase === 'roundEnd' || this.phase === 'matchEnd') {
+      // Results on screen: the world is frozen.
+      if (--this.pause > 0) return;
+      if (this.phase === 'roundEnd') this.startRound();
+      else this.backToLobby();
+      return;
+    }
+
     const result = this.game.step();
     for (const { seq, ev } of result.terrain) this.broadcast({ t: 'terrain', seq, ev });
     for (const id of result.removedChunks) this.broadcast({ t: 'chunkRemoved', id });
     for (const c of result.crushed) this.broadcast({ t: 'crushed', ...c });
+    for (const ev of result.fx) this.broadcast({ t: 'fx', ev });
     if (this.game.tick % TICKS_PER_SNAPSHOT === 0) {
-      this.broadcast({ t: 'snapshot', tick: this.game.tick, players: this.game.snapshot(), chunks: this.game.chunkStates() });
+      this.broadcast({
+        t: 'snapshot',
+        tick: this.game.tick,
+        players: this.game.snapshot(),
+        chunks: this.game.chunkStates(),
+        items: this.game.itemStates(),
+        round: this.game.roundState(),
+      });
+    }
+    if (this.game.tick % HASH_CHECK_TICKS === 0) {
+      this.broadcast({ t: 'hash', seq: this.game.events.length, hash: this.game.terrain.hash() });
     }
+    if (this.countdown !== null) {
+      this.countdown--;
+      if (this.countdown <= 0) this.startMatch();
+      else if (this.countdown % TICK_RATE === 0) this.broadcastLobby(); // one update per second shown
+    }
+    if (this.phase === 'playing' && this.game.roundOver) this.endRound();
+  }
+
+  private players(): LobbyPlayer[] {
+    return [...this.clients].flatMap((c) => (c.player ? [c.player] : []));
+  }
+
+  private newGame(rules: RoundRules | null, mapId: string): Game {
+    return this.opts.createGame(this.rng.nextU32(), rules, this.stats, mapId);
+  }
+
+  /** The warm-up happens on the first map of the rotation. */
+  private warmupMap(): string {
+    return rotationPool(this.rotation, this.opts.maps)[0].id;
+  }
+
+  /** The first player who joined (and is still here) sets the rotation. */
+  private hostId(): number {
+    const ids = this.players().map((p) => p.id);
+    return ids.length > 0 ? Math.min(...ids) : 0;
   }
 
   private onConnection(socket: WebSocket): void {
-    const client: Client = { socket, playerId: null };
+    const client: Client = { socket, player: null };
     this.clients.add(client);
     socket.on('message', (data: Buffer) => {
       let msg: unknown;
@@ -75,47 +206,172 @@ export class GameServer {
         return;
       }
       if (!isClientMessage(msg)) return;
-      if (msg.t === 'hello') {
-        if (msg.version !== PROTOCOL_VERSION) {
-          this.send(client, { t: 'reject', reason: 'version', serverVersion: PROTOCOL_VERSION });
-          socket.close();
-          return;
-        }
-        if (client.playerId !== null) return;
-        if (this.game.playerInfos().length >= MAX_PLAYERS) {
-          this.send(client, { t: 'reject', reason: 'full', serverVersion: PROTOCOL_VERSION });
-          socket.close();
-          return;
-        }
-        if (!isCharacterId(msg.characterId)) {
-          this.send(client, { t: 'reject', reason: 'character', serverVersion: PROTOCOL_VERSION });
-          socket.close();
-          return;
-        }
-        const name = msg.name.slice(0, 24) || 'Joueur';
-        const info = this.game.addPlayer(name, msg.characterId);
-        client.playerId = info.id;
-        this.send(client, {
-          t: 'welcome',
-          version: PROTOCOL_VERSION,
-          playerId: info.id,
-          mapId: this.game.map.id,
-          seed: this.game.seed,
-          events: [...this.game.events],
-          players: this.game.playerInfos(),
-          chunks: this.game.chunkInfos(),
-        });
-        this.broadcast({ t: 'playerJoined', player: info }, client);
-      } else if (client.playerId !== null) {
-        this.game.setInput(client.playerId, { buttons: msg.buttons, aimX: msg.aimX, aimY: msg.aimY });
+      if (msg.t === 'hello') this.onHello(client, msg.version, msg.name, msg.characterId);
+      else if (!client.player) return;
+      else if (msg.t === 'input') this.game.setInput(client.player.id, { buttons: msg.buttons, aimX: msg.aimX, aimY: msg.aimY });
+      else if (msg.t === 'ready') this.onReady(client.player, msg.ready);
+      else if (msg.t === 'rotation') this.onRotation(client.player, msg.rotation);
+      else if (msg.t === 'pickMap') this.onPickMap(client.player, msg.mapId);
+      else if (msg.t === 'desync') {
+        console.error(
+          `[net] DESYNC: player ${client.player.id} (${client.player.name}) has hash ${msg.hash} at seq ${msg.seq}; ` +
+            `server is at seq ${this.game.events.length}`,
+        );
       }
     });
     socket.on('close', () => {
       this.clients.delete(client);
-      if (client.playerId !== null) {
-        this.game.removePlayer(client.playerId);
-        this.broadcast({ t: 'playerLeft', id: client.playerId });
+      if (!client.player) return;
+      this.game.removePlayer(client.player.id);
+      this.broadcast({ t: 'playerLeft', id: client.player.id });
+      if (this.playerCount === 0) {
+        // Everyone left: back to the lobby on a fresh map for whoever comes next.
+        this.phase = 'lobby';
+        this.countdown = null;
+        this.round = 0;
+        this.game = this.newGame(null, this.warmupMap());
       }
+      this.updateCountdown();
+      this.broadcastLobby();
+    });
+  }
+
+  private onHello(client: Client, version: number, rawName: string, characterId: string): void {
+    const reject = (reason: 'version' | 'full' | 'character'): void => {
+      this.send(client, { t: 'reject', reason, serverVersion: PROTOCOL_VERSION });
+      client.socket.close();
+    };
+    if (version !== PROTOCOL_VERSION) return reject('version');
+    if (client.player) return;
+    if (this.playerCount >= MAX_PLAYERS) return reject('full');
+    if (!isCharacterId(characterId)) return reject('character');
+
+    const player: LobbyPlayer = { id: this.nextPlayerId++, name: rawName.slice(0, 24) || 'Joueur', characterId, ready: false };
+    client.player = player;
+    const info = this.game.addPlayer(player.name, characterId, player.id);
+    this.send(client, {
+      t: 'welcome',
+      version: PROTOCOL_VERSION,
+      playerId: player.id,
+      mapId: this.game.map.id,
+      seed: this.game.seed,
+      events: [...this.game.events],
+      players: this.game.playerInfos(),
+      chunks: this.game.chunkInfos(),
+      round: this.round,
+      rounds: this.rounds,
+    });
+    this.broadcast({ t: 'playerJoined', player: info }, client);
+    // A newcomer is not ready: a running countdown stops.
+    this.updateCountdown();
+    this.broadcastLobby();
+  }
+
+  private onReady(player: LobbyPlayer, ready: boolean): void {
+    if (this.phase !== 'lobby' || player.ready === ready) return;
+    player.ready = ready;
+    this.updateCountdown();
+    this.broadcastLobby();
+  }
+
+  private onRotation(player: LobbyPlayer, rotation: Rotation): void {
+    if (this.phase !== 'lobby' || player.id !== this.hostId()) return;
+    this.rotation = sanitizeRotation(rotation, this.opts.maps);
+    // Warm up on a map of the new rotation.
+    if (this.game.map.id !== this.warmupMap()) {
+      this.game = this.newGame(null, this.warmupMap());
+      this.populateAndAnnounce();
+      return;
+    }
+    this.broadcastLobby();
+  }
+
+  private onPickMap(player: LobbyPlayer, mapId: string): void {
+    if (this.phase !== 'roundEnd' || player.id !== this.picker || this.pickedMap !== null) return;
+    if (!rotationPool(this.rotation, this.opts.maps).some((m) => m.id === mapId)) return;
+    this.pickedMap = mapId;
+    this.broadcast({ t: 'mapPicked', mapId, by: player.id });
+  }
+
+  private updateCountdown(): void {
+    const players = this.players();
+    const allReady = this.phase === 'lobby' && players.length > 0 && players.every((p) => p.ready);
+    if (allReady && this.countdown === null) this.countdown = START_COUNTDOWN_S * TICK_RATE;
+    else if (!allReady) this.countdown = null;
+  }
+
+  private startMatch(): void {
+    this.countdown = null;
+    this.round = 0;
+    this.stats = new MatchStats();
+    this.totals = new Map();
+    for (const p of this.players()) p.ready = false;
+    this.startRound();
+  }
+
+  /** Loads a fresh map and puts every connected player in it. */
+  private startRound(): void {
+    this.round++;
+    this.phase = 'playing';
+    const mapId = this.pickedMap ?? defaultMap(this.rotation, this.opts.maps, this.round, this.rng);
+    this.picker = null;
+    this.pickedMap = null;
+    this.game = this.newGame({ duration: this.opts.roundDuration ?? ROUND_DURATION_S }, mapId);
+    this.populateAndAnnounce();
+  }
+
+  private endRound(): void {
+    const scores = this.game.scores();
+    for (const p of this.players()) this.totals.set(p.id, (this.totals.get(p.id) ?? 0) + (scores.get(p.id) ?? 0));
+    const results = this.results(scores);
+    if (this.round >= this.rounds) {
+      const lobbyIn = this.opts.matchEndPause ?? MATCH_END_PAUSE_S;
+      this.phase = 'matchEnd';
+      this.pause = Math.max(1, Math.round(lobbyIn * TICK_RATE));
+      this.broadcast({ t: 'matchEnd', results, trophies: this.stats.trophies(this.players().map((p) => p.id)), lobbyIn });
+    } else {
+      const nextIn = this.opts.roundEndPause ?? ROUND_END_PAUSE_S;
+      this.phase = 'roundEnd';
+      this.pause = Math.max(1, Math.round(nextIn * TICK_RATE));
+      // Catch-up rule (readme §4): the last-placed player picks the next map.
+      this.picker = lastPlaced(results);
+      this.pickedMap = null;
+      const choices = rotationPool(this.rotation, this.opts.maps);
+      this.broadcast({ t: 'roundEnd', round: this.round, rounds: this.rounds, results, nextIn, picker: this.picker, choices });
+    }
+    this.broadcastLobby();
+  }
+
+  /** Results sorted by match total, then this round's score. */
+  private results(scores: Map<number, number>): RoundResult[] {
+    return this.players()
+      .map((p) => ({ id: p.id, name: p.name, characterId: p.characterId, roundScore: scores.get(p.id) ?? 0, total: this.totals.get(p.id) ?? 0 }))
+      .sort((a, b) => b.total - a.total || b.roundScore - a.roundScore || a.id - b.id);
+  }
+
+  private backToLobby(): void {
+    this.phase = 'lobby';
+    this.round = 0;
+    this.game = this.newGame(null, this.warmupMap());
+    this.populateAndAnnounce();
+  }
+
+  private populateAndAnnounce(): void {
+    for (const p of this.players()) this.game.addPlayer(p.name, p.characterId, p.id);
+    this.broadcast({ t: 'start', mapId: this.game.map.id, seed: this.game.seed, players: this.game.playerInfos(), round: this.round, rounds: this.rounds });
+    this.broadcastLobby();
+  }
+
+  private broadcastLobby(): void {
+    const countdown = this.countdown === null ? null : Math.ceil(this.countdown / TICK_RATE);
+    this.broadcast({
+      t: 'lobby',
+      phase: this.phase,
+      players: this.players(),
+      countdown,
+      hostId: this.hostId(),
+      rotation: this.rotation,
+      maps: this.opts.maps,
     });
   }
 
@@ -126,7 +382,7 @@ export class GameServer {
   private broadcast(msg: ServerMessage, except?: Client): void {
     const data = packr.pack(msg);
     for (const c of this.clients) {
-      if (c !== except && c.playerId !== null && c.socket.readyState === c.socket.OPEN) c.socket.send(data);
+      if (c !== except && c.player && c.socket.readyState === c.socket.OPEN) c.socket.send(data);
     }
   }
 }

+ 2 - 0
src/server/physics/fallingChunk.ts

@@ -9,6 +9,8 @@ const PPM = PIXELS_PER_METER;
 export interface FixtureTag {
   chunk?: number;
   player?: number;
+  item?: number;
+  cherry?: boolean;
 }
 
 interface BoxRect {

+ 33 - 0
src/server/rotation.ts

@@ -0,0 +1,33 @@
+import type { Rng } from '../shared/rng';
+import type { MapSummary, RoundResult, Rotation } from '../shared/protocol';
+
+export const DEFAULT_ROTATION: Rotation = { mode: 'all', selection: [] };
+
+/** Maps a match may use: the host's selection (ignoring unknown ids), or every map. Never empty. */
+export function rotationPool(rotation: Rotation, catalog: MapSummary[]): MapSummary[] {
+  if (rotation.mode === 'selection') {
+    const picked = catalog.filter((m) => rotation.selection.includes(m.id));
+    if (picked.length > 0) return picked;
+  }
+  return catalog;
+}
+
+/** The map for round `round` (1-based) when nobody picks: in order, or at random for 'random'. */
+export function defaultMap(rotation: Rotation, catalog: MapSummary[], round: number, rng: Rng): string {
+  const pool = rotationPool(rotation, catalog);
+  if (rotation.mode === 'random') return pool[rng.int(0, pool.length - 1)].id;
+  return pool[(Math.max(1, round) - 1) % pool.length].id;
+}
+
+/** The player who picks the next map: lowest total, then lowest round score, then latest to join. */
+export function lastPlaced(results: RoundResult[]): number | null {
+  if (results.length === 0) return null;
+  const sorted = [...results].sort((a, b) => a.total - b.total || a.roundScore - b.roundScore || b.id - a.id);
+  return sorted[0].id;
+}
+
+/** Keeps only known map ids and a known mode. */
+export function sanitizeRotation(rotation: Rotation, catalog: MapSummary[]): Rotation {
+  const ids = new Set(catalog.map((m) => m.id));
+  return { mode: rotation.mode, selection: [...new Set(rotation.selection.filter((id) => ids.has(id)))] };
+}

+ 63 - 0
src/server/stats.ts

@@ -0,0 +1,63 @@
+import type { Trophy } from '../shared/protocol';
+
+/** Per-player counters accumulated over a whole match, used for the trophies. */
+export type StatKey =
+  | 'eaten' // pixels removed from the terrain
+  | 'custard' // falls into the custard
+  | 'crushed' // times crushed by a falling chunk
+  | 'detached' // chunks this player made fall
+  | 'cherry' // seconds holding the cherry
+  | 'hits' // hits landed
+  | 'hitTaken' // hits received
+  | 'candles'; // candles thrown
+
+interface TrophyRule {
+  id: string;
+  score: (s: Record<StatKey, number>) => number;
+}
+
+/** Trophy rules (readme §4). Display names live in renderer/i18n. */
+const TROPHIES: TrophyRule[] = [
+  { id: 'glutton', score: (s) => s.eaten },
+  { id: 'kamikaze', score: (s) => s.custard },
+  { id: 'developer', score: (s) => s.detached },
+  { id: 'notMyFault', score: (s) => s.crushed + s.hitTaken },
+  { id: 'pyromaniac', score: (s) => s.candles },
+  { id: 'cherryPicker', score: (s) => Math.floor(s.cherry) },
+];
+
+const empty = (): Record<StatKey, number> => ({ eaten: 0, custard: 0, crushed: 0, detached: 0, cherry: 0, hits: 0, hitTaken: 0, candles: 0 });
+
+export class MatchStats {
+  private readonly data = new Map<number, Record<StatKey, number>>();
+
+  add(playerId: number, key: StatKey, n = 1): void {
+    if (playerId <= 0) return;
+    let s = this.data.get(playerId);
+    if (!s) this.data.set(playerId, (s = empty()));
+    s[key] += n;
+  }
+
+  get(playerId: number, key: StatKey): number {
+    return this.data.get(playerId)?.[key] ?? 0;
+  }
+
+  /** One trophy per rule, to the best player among `playerIds` (ties: lowest id), only if they did it at all. */
+  trophies(playerIds: number[]): Trophy[] {
+    const out: Trophy[] = [];
+    const ids = [...playerIds].sort((a, b) => a - b);
+    for (const rule of TROPHIES) {
+      let best = 0;
+      let bestId = -1;
+      for (const id of ids) {
+        const v = rule.score(this.data.get(id) ?? empty());
+        if (v > best) {
+          best = v;
+          bestId = id;
+        }
+      }
+      if (bestId > 0) out.push({ id: rule.id, playerId: bestId, value: Math.round(best) });
+    }
+    return out;
+  }
+}

+ 23 - 0
src/shared/characters/Character.ts

@@ -25,8 +25,27 @@ export const Anim = {
   Attack: 1 << 0,
   Special: 1 << 1,
   Stunned: 1 << 2,
+  /** In the custard, waiting for the spoon: not drawn. */
+  Dead: 1 << 3,
+  /** Smarties speed boost. */
+  Boosted: 1 << 4,
 } as const;
 
+/** An explosion: carves the cake (power vs hardness), burns wool around it, blows players away. */
+export interface Blast {
+  r: number;
+  power: number;
+  knockback: number;
+  stun: number;
+}
+
+/** Projectiles a character can throw. Behaviour lives in the server; tuning comes from character.json. */
+export type ProjectileSpec =
+  /** Explodes on contact (after arming) or when the fuse runs out. */
+  | { kind: 'firecracker'; fuse: number; blast: Blast }
+  /** Spins a wool thread along its path and sticks a wool blob where it lands. */
+  | { kind: 'yarn'; life: number; trailRadius: number; blobRadius: number; material: number };
+
 /** What a character may read and do. Implemented by the server simulation. */
 export interface CharacterContext {
   readonly x: number;
@@ -44,6 +63,10 @@ export interface CharacterContext {
   setSize(radius: number): void;
   /** Knocks back and stuns every other player whose body touches the disc (x, y, r). Returns how many were hit. */
   hit(x: number, y: number, r: number, knockback: number, stun: number): number;
+  /** Throws a projectile from (x, y) with velocity (vx, vy) in px/s. */
+  launch(spec: ProjectileSpec, x: number, y: number, vx: number, vy: number): void;
+  /** Explodes at (x, y). `spareSelf`: the character is not blown away by its own blast. */
+  explode(x: number, y: number, blast: Blast, spareSelf: boolean): void;
 }
 
 /** Base class for all characters. Pure logic: no physics engine, no rendering. */

+ 56 - 0
src/shared/characters/Mamie.ts

@@ -0,0 +1,56 @@
+import { MATERIAL_WOOL } from '../constants';
+import { Anim, Character, type CharacterContext } from './Character';
+
+/**
+ * Mamie Tricot.
+ * - Attack: knitting needles, a short jab that barely pushes but stuns for a while.
+ * - Special: throws a ball of yarn that spins a wool thread along its path and sticks a
+ *   wool blob where it lands: bridges and nets, if both ends hold on to something.
+ * - Flaw: slow, and wool burns (explosions consume it, see WOOL_BURN_RADIUS_FACTOR).
+ */
+export class Mamie extends Character {
+  private jabTimer = 0;
+  private throwTimer = 0;
+
+  onAttack(ctx: CharacterContext): void {
+    const p = this.stats.params;
+    const [dx, dy] = aimDir(ctx);
+    const reach = this.size + p.needleReach;
+    const nx = ctx.x + dx * reach;
+    const ny = ctx.y + dy * reach;
+    ctx.hit(nx, ny, p.needleRadius, p.needleKnockback, p.needleStun);
+    // The needles scratch the cake a little: everything goes through the ground (readme §1).
+    ctx.emitOp({ kind: 'carve', x: Math.round(nx), y: Math.round(ny), r: Math.round(p.needleCarveRadius), power: Math.round(p.needlePower) });
+    this.jabTimer = p.jabAnim;
+  }
+
+  onSpecial(ctx: CharacterContext): void {
+    const p = this.stats.params;
+    const [dx, dy] = aimDir(ctx);
+    const start = this.size + p.yarnStart;
+    ctx.launch(
+      { kind: 'yarn', life: p.yarnLife, trailRadius: Math.round(p.yarnTrailRadius), blobRadius: Math.round(p.yarnBlobRadius), material: MATERIAL_WOOL },
+      ctx.x + dx * start,
+      ctx.y + dy * start,
+      dx * p.yarnSpeed + ctx.vx * 0.5,
+      dy * p.yarnSpeed + ctx.vy * 0.5,
+    );
+    this.throwTimer = p.throwAnim;
+  }
+
+  override onTick(_ctx: CharacterContext, dt: number): void {
+    this.jabTimer = Math.max(0, this.jabTimer - dt);
+    this.throwTimer = Math.max(0, this.throwTimer - dt);
+  }
+
+  override anim(): number {
+    return (this.jabTimer > 0 ? Anim.Attack : 0) | (this.throwTimer > 0 ? Anim.Special : 0);
+  }
+}
+
+export function aimDir(ctx: CharacterContext): [number, number] {
+  const dx = ctx.input.aimX - ctx.x;
+  const dy = ctx.input.aimY - ctx.y;
+  const len = Math.hypot(dx, dy);
+  return len < 1 ? [ctx.facing, 0] : [dx / len, dy / len];
+}

+ 66 - 0
src/shared/characters/Pyromanchot.ts

@@ -0,0 +1,66 @@
+import { Anim, Character, type Blast, type CharacterContext } from './Character';
+import { aimDir } from './Mamie';
+
+/**
+ * Pyromanchot, the penguin who loves fireworks.
+ * - Attack: throws a firecracker that explodes on contact.
+ * - Special: belly slide, ending in an explosion where he stops (he is spared).
+ * - Flaw: one firecracker in three goes off in his flippers.
+ */
+export class Pyromanchot extends Character {
+  private thrown = 0;
+  private slideTime = 0;
+  private slideDir = 1;
+  private throwTimer = 0;
+
+  onAttack(ctx: CharacterContext): void {
+    const p = this.stats.params;
+    this.thrown++;
+    this.throwTimer = p.throwAnim;
+    const blast = this.crackerBlast();
+    if (this.thrown % Math.max(1, Math.round(p.backfireEvery)) === 0) {
+      // Backfire: it blows up right here, and he is not spared.
+      ctx.explode(ctx.x + ctx.facing * this.size * 0.6, ctx.y, blast, false);
+      return;
+    }
+    const [dx, dy] = aimDir(ctx);
+    const start = this.size + 10;
+    ctx.launch(
+      { kind: 'firecracker', fuse: p.crackerFuse, blast },
+      ctx.x + dx * start,
+      ctx.y + dy * start,
+      dx * p.crackerSpeed + ctx.vx * 0.5,
+      dy * p.crackerSpeed + ctx.vy * 0.5 - p.crackerLift,
+    );
+  }
+
+  onSpecial(ctx: CharacterContext): void {
+    if (this.slideTime > 0) return;
+    this.slideTime = this.stats.params.slideTime;
+    this.slideDir = ctx.facing;
+  }
+
+  override onTick(ctx: CharacterContext, dt: number): void {
+    const p = this.stats.params;
+    this.throwTimer = Math.max(0, this.throwTimer - dt);
+    if (this.slideTime <= 0) return;
+    this.slideTime -= dt;
+    // Belly slide: fast and flat, gravity still applies.
+    ctx.setVelocity(this.slideDir * p.slideSpeed, Math.max(ctx.vy, 0));
+    // Blocked by a wall, or the slide is over: boom.
+    const blocked = this.slideTime < p.slideTime - 0.1 && Math.abs(ctx.vx) < p.slideSpeed * 0.3;
+    if (this.slideTime <= 0 || blocked) {
+      this.slideTime = 0;
+      ctx.explode(ctx.x + this.slideDir * this.size, ctx.y, { r: p.slideBlastRadius, power: p.slideBlastPower, knockback: p.slideKnockback, stun: p.slideStun }, true);
+    }
+  }
+
+  override anim(): number {
+    return (this.throwTimer > 0 ? Anim.Attack : 0) | (this.slideTime > 0 ? Anim.Special : 0);
+  }
+
+  private crackerBlast(): Blast {
+    const p = this.stats.params;
+    return { r: p.crackerRadius, power: p.crackerPower, knockback: p.crackerKnockback, stun: p.crackerStun };
+  }
+}

+ 7 - 2
src/shared/characters/index.ts

@@ -1,10 +1,15 @@
 import { Castor } from './Castor';
 import type { Character, CharacterStats } from './Character';
 import { Generic } from './Generic';
+import { Mamie } from './Mamie';
+import { Pyromanchot } from './Pyromanchot';
 
+// Menu order: the three M5 characters, then the test character.
 const registry: Record<string, new (stats: CharacterStats) => Character> = {
-  generic: Generic,
   castor: Castor,
+  mamie: Mamie,
+  pyromanchot: Pyromanchot,
+  generic: Generic,
 };
 
 /** Ids of playable characters, in menu order. */
@@ -21,4 +26,4 @@ export function createCharacter(stats: CharacterStats): Character {
 }
 
 export { Anim, Character, parseCharacterStats } from './Character';
-export type { CharacterContext, CharacterStats } from './Character';
+export type { Blast, CharacterContext, CharacterStats, ProjectileSpec } from './Character';

+ 68 - 1
src/shared/constants.ts

@@ -2,10 +2,77 @@
 // (characters, maps, materials) whenever they belong to a specific entity.
 
 /** Bumped on every incompatible protocol change. */
-export const PROTOCOL_VERSION = 3;
+export const PROTOCOL_VERSION = 7;
 
 export const NET_PORT = 47100;
 export const DISCOVERY_PORT = 47101;
+export const MAX_PLAYERS = 8;
+/** Servers announce themselves this often; clients forget a server not heard for DISCOVERY_TTL_MS. */
+export const DISCOVERY_INTERVAL_MS = 1000;
+export const DISCOVERY_TTL_MS = 3500;
+/** Seconds between two bitmap hash comparisons (readme §9, M3). */
+export const HASH_CHECK_INTERVAL_S = 5;
+/** Countdown once every player in the lobby is ready (s). */
+export const START_COUNTDOWN_S = 3;
+
+// Match rules (readme §4). Tune by playing.
+export const ROUND_DURATION_S = 180;
+export const ROUNDS_PER_MATCH = 4;
+/** The custard rises at finalRushSpeed during the last seconds of a round. */
+export const FINAL_RUSH_S = 30;
+/** Pause on the round results before the next round (s). */
+export const ROUND_END_PAUSE_S = 7;
+/** Pause on the final results and trophies before going back to the lobby (s). */
+export const MATCH_END_PAUSE_S = 15;
+/** Seconds in the custard before the spoon catapult sends a player back. */
+export const RESPAWN_DELAY_S = 5;
+/** Launch speed of the spoon catapult (px/s). */
+export const SPOON_LAUNCH_SPEED = 950;
+/** A body sinks this far below the custard surface before it counts as fallen in (px). */
+export const CUSTARD_SINK_PX = 6;
+export const CHERRY_RADIUS = 12;
+export const CHERRY_POINTS_PER_S = 1;
+/** After dropping the cherry, its last holder cannot grab it back for this long (s). */
+export const CHERRY_REGRAB_DELAY = 1;
+/** Speed at which a dropped cherry pops out (px/s). */
+export const CHERRY_DROP_SPEED = 380;
+export const ITEM_RADIUS = 12;
+/** Items lying around for this long disappear (s). */
+export const ITEM_LIFETIME_S = 25;
+export const CANDLE_THROW_SPEED = 720;
+/** A thrown candle explodes on contact after arming, or when its fuse runs out (s). */
+export const CANDLE_ARM_S = 0.12;
+export const CANDLE_FUSE_S = 1.6;
+export const CANDLE_BLAST_RADIUS = 52;
+/** Below chocolate's hardness: chocolate resists explosions (readme §4). */
+export const CANDLE_BLAST_POWER = 50;
+export const CANDLE_KNOCKBACK = 760;
+export const CANDLE_STUN_S = 0.7;
+export const SMARTIES_DURATION_S = 5;
+export const SMARTIES_SPEED_MULT = 1.6;
+/** Electric whisk: number of jelly spots it shakes loose, and how hard players are jolted. */
+export const WHISK_CRACKS = 14;
+export const WHISK_CRACK_RADIUS = 11;
+export const WHISK_CRACK_POWER = 35;
+export const WHISK_JOLT = 320;
+export const WHISK_STUN_S = 0.35;
+/** Explosions burn wool (material 7) within this multiple of their radius (readme §4, Mamie Tricot). */
+export const WOOL_BURN_RADIUS_FACTOR = 2.2;
+export const MATERIAL_WOOL = 7;
+// Map modifiers (server/modifiers). Tune by playing.
+/** Strongest side wind (px/s²) and how often a new gust is drawn (s). */
+export const WIND_MAX = 520;
+export const WIND_PERIOD_S = 6;
+/** Wind push on a player standing on the ground, relative to the air. */
+export const WIND_GROUND_FACTOR = 0.35;
+/** Random cracks: delay between two cracks (s), carve size and shape. */
+export const CRACK_INTERVAL_S: [number, number] = [3, 7];
+export const CRACK_LENGTH = 14;
+export const CRACK_STEP = 6;
+export const CRACK_RADIUS = 3;
+export const CRACK_POWER = 35;
+/** Projectiles can only hit things after this delay, so they do not blow up in the thrower's hands (s). */
+export const PROJECTILE_ARM_S = 0.08;
 
 export const TICK_RATE = 60;
 export const TICK_DT = 1 / TICK_RATE;

+ 2 - 0
src/shared/input.ts

@@ -6,6 +6,8 @@ export const Button = {
   Down: 1 << 3,
   Attack: 1 << 4,
   Special: 1 << 5,
+  /** Uses the carried item (throws the candle). */
+  Use: 1 << 6,
 } as const;
 
 export interface InputState {

+ 172 - 2
src/shared/protocol.ts

@@ -25,6 +25,67 @@ export interface PlayerState {
   size: number;
   /** Anim flags (shared/characters/Character.ts). */
   anim: number;
+  /** Points scored this round (whole seconds holding the cherry). */
+  score: number;
+  /** Item carried, waiting to be used. */
+  item: ItemKind | null;
+}
+
+export type ItemKind = 'candle' | 'smarties' | 'whisk';
+/** Things in flight: pickable items, and projectiles thrown by characters. */
+export type EntityKind = ItemKind | 'firecracker' | 'yarn';
+
+/** An item lying around, falling, or thrown (lit candle, firecracker, yarn ball). */
+export interface ItemState {
+  id: number;
+  kind: EntityKind;
+  x: number;
+  y: number;
+  angle: number;
+  lit: boolean;
+}
+
+export interface CherryState {
+  x: number;
+  y: number;
+  /** Player holding it, 0 when it rolls free. */
+  holder: number;
+}
+
+/** Round-wide state carried by every snapshot. Null fields are inactive (warm-up). */
+export interface RoundState {
+  custardY: number;
+  /** Seconds left in the round, null during warm-up. */
+  timeLeft: number | null;
+  /** True during the last FINAL_RUSH_S seconds. */
+  finalRush: boolean;
+  /** Sideways wind (px/s², positive = to the right), 0 without the wind modifier. */
+  wind: number;
+  cherry: CherryState | null;
+}
+
+/** One-shot visual/sound cues. */
+export type FxEvent =
+  | { kind: 'splash'; id: number; x: number; y: number }
+  | { kind: 'spoon'; id: number; x: number; y: number }
+  | { kind: 'explosion'; x: number; y: number; r: number }
+  | { kind: 'pickup'; id: number; item: ItemKind | 'cherry'; x: number; y: number }
+  | { kind: 'cherryDrop'; id: number; x: number; y: number }
+  | { kind: 'whisk'; id: number };
+
+export interface RoundResult {
+  id: number;
+  name: string;
+  characterId: string;
+  roundScore: number;
+  total: number;
+}
+
+/** A funny end-of-match award (names are in renderer/i18n). */
+export interface Trophy {
+  id: string;
+  playerId: number;
+  value: number;
 }
 
 /** A falling chunk's pose: (x, y) is its local origin (mask top-left) in map pixels. */
@@ -45,10 +106,74 @@ export interface ChunkInfo {
   state: ChunkState;
 }
 
+/** A playable map, as listed in the lobby. */
+export interface MapSummary {
+  id: string;
+  name: string;
+}
+
+/**
+ * Which maps a match uses (readme §6): all of them in order, a selection (in order),
+ * or all of them in random order. The last-placed player still picks from this pool.
+ */
+export interface Rotation {
+  mode: 'all' | 'selection' | 'random';
+  selection: string[];
+}
+
+export const PHASES = ['lobby', 'playing', 'roundEnd', 'matchEnd'] as const;
+export type Phase = (typeof PHASES)[number];
+
+export interface LobbyPlayer {
+  id: number;
+  name: string;
+  characterId: string;
+  ready: boolean;
+}
+
+/** UDP broadcast payload (JSON) announcing a game on the LAN. */
+export interface Announcement {
+  magic: typeof ANNOUNCE_MAGIC;
+  /** Random per server process, to merge announcements received on several interfaces. */
+  serverId: string;
+  name: string;
+  mapId: string;
+  players: number;
+  maxPlayers: number;
+  phase: Phase;
+  version: number;
+  port: number;
+}
+
+export const ANNOUNCE_MAGIC = 'goutermageddon';
+
+export function isAnnouncement(msg: unknown): msg is Announcement {
+  if (!msg || typeof msg !== 'object') return false;
+  const m = msg as Record<string, unknown>;
+  return (
+    m.magic === ANNOUNCE_MAGIC &&
+    typeof m.serverId === 'string' &&
+    typeof m.name === 'string' &&
+    typeof m.mapId === 'string' &&
+    typeof m.players === 'number' &&
+    typeof m.maxPlayers === 'number' &&
+    typeof m.version === 'number' &&
+    typeof m.port === 'number' &&
+    PHASES.includes(m.phase as Phase)
+  );
+}
+
 // Client -> server
 export type ClientMessage =
   | { t: 'hello'; version: number; name: string; characterId: string }
-  | ({ t: 'input' } & InputState);
+  | ({ t: 'input' } & InputState)
+  | { t: 'ready'; ready: boolean }
+  /** Host only, in the lobby. */
+  | { t: 'rotation'; rotation: Rotation }
+  /** The last-placed player picks the next map during the round results. */
+  | { t: 'pickMap'; mapId: string }
+  /** The client's bitmap hash differs from the server's at `seq`. */
+  | { t: 'desync'; seq: number; hash: number };
 
 // Server -> client
 export type ServerMessage =
@@ -62,6 +187,9 @@ export type ServerMessage =
       events: SequencedEvent[];
       players: PlayerInfo[];
       chunks: ChunkInfo[];
+      /** 0 during warm-up. */
+      round: number;
+      rounds: number;
     }
   | { t: 'reject'; reason: 'version' | 'full' | 'character'; serverVersion: number }
   | { t: 'playerJoined'; player: PlayerInfo }
@@ -70,7 +198,34 @@ export type ServerMessage =
   /** A chunk left the game without merging (fell off the map). */
   | { t: 'chunkRemoved'; id: number }
   | { t: 'crushed'; id: number; x: number; y: number }
-  | { t: 'snapshot'; tick: number; players: PlayerState[]; chunks: ChunkState[] };
+  | { t: 'snapshot'; tick: number; players: PlayerState[]; chunks: ChunkState[]; items: ItemState[]; round: RoundState }
+  | { t: 'fx'; ev: FxEvent }
+  | {
+      t: 'lobby';
+      phase: Phase;
+      players: LobbyPlayer[];
+      countdown: number | null;
+      /** The first player who joined sets the rotation. */
+      hostId: number;
+      rotation: Rotation;
+      maps: MapSummary[];
+    }
+  | { t: 'mapPicked'; mapId: string; by: number }
+  /** A round (or the warm-up, round 0) starts on a freshly loaded map: clients drop their world and reload. */
+  | { t: 'start'; mapId: string; seed: number; players: PlayerInfo[]; round: number; rounds: number }
+  | {
+      t: 'roundEnd';
+      round: number;
+      rounds: number;
+      results: RoundResult[];
+      nextIn: number;
+      /** Last-placed player, who picks the next map among `choices` (readme §4). */
+      picker: number | null;
+      choices: MapSummary[];
+    }
+  | { t: 'matchEnd'; results: RoundResult[]; trophies: Trophy[]; lobbyIn: number }
+  /** Consistency check: the server's bitmap hash once `seq` terrain events have been applied. */
+  | { t: 'hash'; seq: number; hash: number };
 
 export function hello(name: string, characterId: string): ClientMessage {
   return { t: 'hello', version: PROTOCOL_VERSION, name, characterId };
@@ -81,5 +236,20 @@ export function isClientMessage(msg: unknown): msg is ClientMessage {
   const m = msg as Record<string, unknown>;
   if (m.t === 'hello') return typeof m.version === 'number' && typeof m.name === 'string' && typeof m.characterId === 'string';
   if (m.t === 'input') return typeof m.buttons === 'number' && typeof m.aimX === 'number' && typeof m.aimY === 'number';
+  if (m.t === 'ready') return typeof m.ready === 'boolean';
+  if (m.t === 'pickMap') return typeof m.mapId === 'string';
+  if (m.t === 'rotation') {
+    const r = m.rotation as Partial<Rotation> | undefined;
+    return (
+      !!r &&
+      (r.mode === 'all' || r.mode === 'selection' || r.mode === 'random') &&
+      Array.isArray(r.selection) &&
+      r.selection.every((id) => typeof id === 'string')
+    );
+  }
+  if (m.t === 'desync') return typeof m.seq === 'number' && typeof m.hash === 'number';
   return false;
 }
+
+export type RoundEndMessage = Extract<ServerMessage, { t: 'roundEnd' }>;
+export type MatchEndMessage = Extract<ServerMessage, { t: 'matchEnd' }>;

+ 140 - 0
tests/characters.test.ts

@@ -0,0 +1,140 @@
+import { describe, expect, it } from 'vitest';
+import { loadCharacterStats, loadMap } from '../src/server/assets';
+import { Game } from '../src/server/game';
+import { Anim, CHARACTER_IDS } from '../src/shared/characters';
+import { MATERIAL_WOOL, TICK_RATE } from '../src/shared/constants';
+import { Button } from '../src/shared/input';
+import type { FxEvent } from '../src/shared/protocol';
+import { ASSETS, realMaterials } from './helpers';
+
+const materials = realMaterials();
+
+function newGame(): Game {
+  const { definition, terrain } = loadMap(ASSETS, 'gateau-etages', materials);
+  return new Game({ map: definition, terrain, materials, seed: 5, loadCharacter: (id) => loadCharacterStats(ASSETS, id) });
+}
+
+function run(game: Game, ticks: number): FxEvent[] {
+  const fx: FxEvent[] = [];
+  for (let i = 0; i < ticks; i++) fx.push(...game.step().fx);
+  return fx;
+}
+
+const me = (game: Game, id: number) => game.snapshot().find((p) => p.id === id)!;
+const countWool = (game: Game): number => game.terrain.data.reduce((n, m) => n + (m === MATERIAL_WOOL ? 1 : 0), 0);
+
+/** Presses `buttons` aimed at (x, y) for one tick, then releases. */
+function press(game: Game, id: number, buttons: number, x: number, y: number): FxEvent[] {
+  game.setInput(id, { buttons, aimX: Math.round(x), aimY: Math.round(y) });
+  const fx = run(game, 1);
+  game.setInput(id, { buttons: 0, aimX: Math.round(x), aimY: Math.round(y) });
+  return fx;
+}
+
+describe('roster', () => {
+  it('every character has data that loads', () => {
+    expect(CHARACTER_IDS).toEqual(['castor', 'mamie', 'pyromanchot', 'generic']);
+    for (const id of CHARACTER_IDS) expect(loadCharacterStats(ASSETS, id).id).toBe(id);
+  });
+});
+
+describe('Mamie Tricot', () => {
+  it('her yarn ball spins a wool thread that holds when it reaches a wall', () => {
+    const game = newGame();
+    const { id } = game.addPlayer('Mamie', 'mamie');
+    game.teleport(id, 640, 440); // middle tier, left of the top tier wall (x ≈ 780)
+    run(game, 60);
+    const m = me(game, id);
+    press(game, id, Button.Special, 800, m.y - 40);
+    run(game, 2 * TICK_RATE);
+    const wool = countWool(game);
+    expect(wool).toBeGreaterThan(150);
+    // Let anything unanchored fall and merge or vanish: most of the thread must still be in the bitmap.
+    run(game, 4 * TICK_RATE);
+    expect(countWool(game)).toBeGreaterThan(wool * 0.5);
+  });
+
+  it('her needles barely push but stun for a long time', () => {
+    const game = newGame();
+    const mamie = game.addPlayer('Mamie', 'mamie');
+    const victim = game.addPlayer('Victime', 'generic');
+    run(game, 90);
+    const m = me(game, mamie.id);
+    game.teleport(victim.id, m.x + 40, m.y);
+    press(game, mamie.id, Button.Attack, m.x + 40, m.y);
+    const v = me(game, victim.id);
+    expect(v.anim & Anim.Stunned).toBeTruthy();
+    expect(Math.hypot(v.vx, v.vy)).toBeLessThan(400);
+    run(game, Math.round(0.6 * TICK_RATE));
+    expect(me(game, victim.id).anim & Anim.Stunned).toBeTruthy();
+  });
+
+  it('her wool burns: an explosion nearby consumes it', () => {
+    const game = newGame();
+    const mamie = game.addPlayer('Mamie', 'mamie');
+    const pyro = game.addPlayer('Pyro', 'pyromanchot');
+    game.teleport(mamie.id, 640, 440);
+    run(game, 60);
+    const m = me(game, mamie.id);
+    press(game, mamie.id, Button.Special, 800, m.y - 40);
+    run(game, 2 * TICK_RATE);
+    const before = countWool(game);
+    expect(before).toBeGreaterThan(0);
+    // A firecracker thrown into the wool.
+    game.teleport(pyro.id, 700, 300);
+    run(game, 2);
+    const fx = press(game, pyro.id, Button.Attack, 760, m.y - 30).concat(run(game, TICK_RATE));
+    expect(fx.some((e) => e.kind === 'explosion')).toBe(true);
+    run(game, 2);
+    expect(countWool(game)).toBeLessThan(before);
+  });
+});
+
+describe('Pyromanchot', () => {
+  it('throws firecrackers that explode away from him, and every third one backfires', () => {
+    const game = newGame();
+    const { id } = game.addPlayer('Pyro', 'pyromanchot');
+    run(game, 90);
+    const explosions: { x: number; y: number }[] = [];
+    for (let shot = 0; shot < 3; shot++) {
+      const p = me(game, id);
+      const fx = press(game, id, Button.Attack, p.x + 300, p.y - 100).concat(run(game, TICK_RATE));
+      for (const e of fx) if (e.kind === 'explosion') explosions.push({ x: e.x - p.x, y: e.y - p.y });
+      run(game, Math.round(0.5 * TICK_RATE));
+    }
+    expect(explosions).toHaveLength(3);
+    // The first two flew off; the third went off right next to him.
+    expect(Math.hypot(explosions[0].x, explosions[0].y)).toBeGreaterThan(60);
+    expect(Math.hypot(explosions[1].x, explosions[1].y)).toBeGreaterThan(60);
+    expect(Math.hypot(explosions[2].x, explosions[2].y)).toBeLessThan(40);
+  });
+
+  it('a backfire stuns him', () => {
+    const game = newGame();
+    const { id } = game.addPlayer('Pyro', 'pyromanchot');
+    run(game, 90);
+    for (let shot = 0; shot < 3; shot++) {
+      const p = me(game, id);
+      press(game, id, Button.Attack, p.x + 300, p.y - 100);
+      if (shot < 2) run(game, TICK_RATE);
+    }
+    expect(me(game, id).anim & Anim.Stunned).toBeTruthy();
+  });
+
+  it('belly slide: fast, then an explosion at the end that spares him', () => {
+    const game = newGame();
+    const pyro = game.addPlayer('Pyro', 'pyromanchot');
+    const victim = game.addPlayer('Victime', 'generic');
+    game.teleport(pyro.id, 900, 680); // bottom tier, lots of room to the right
+    game.teleport(victim.id, 1500, 680);
+    run(game, 60);
+    const start = me(game, pyro.id);
+    press(game, pyro.id, Button.Special, start.x + 500, start.y);
+    expect(me(game, pyro.id).anim & Anim.Special).toBeTruthy();
+    const fx = run(game, TICK_RATE);
+    const end = me(game, pyro.id);
+    expect(end.x - start.x).toBeGreaterThan(200);
+    expect(fx.some((e) => e.kind === 'explosion')).toBe(true);
+    expect(end.anim & Anim.Stunned).toBe(0);
+  });
+});

+ 46 - 0
tests/discovery.test.ts

@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+import { DiscoveryListener } from '../src/main/discovery';
+import { Announcer, broadcastAddresses } from '../src/server/discovery';
+import { MAX_PLAYERS, PROTOCOL_VERSION } from '../src/shared/constants';
+import { isAnnouncement, type Announcement } from '../src/shared/protocol';
+
+const announcement: Announcement = {
+  magic: 'goutermageddon',
+  serverId: 'test-server',
+  name: 'Goûter de test',
+  mapId: 'gateau-etages',
+  players: 2,
+  maxPlayers: MAX_PLAYERS,
+  phase: 'lobby',
+  version: PROTOCOL_VERSION,
+  port: 47100,
+};
+
+describe('LAN discovery', () => {
+  it('validates announcements', () => {
+    expect(isAnnouncement(announcement)).toBe(true);
+    expect(isAnnouncement({ ...announcement, magic: 'other-game' })).toBe(false);
+    expect(isAnnouncement({ ...announcement, phase: 'nope' })).toBe(false);
+  });
+
+  it('always announces on loopback and the limited broadcast', () => {
+    expect(broadcastAddresses()).toEqual(expect.arrayContaining(['127.0.0.1', '255.255.255.255']));
+  });
+
+  it('a listener hears an announcer on the same machine, once, with its address', async () => {
+    const listener = new DiscoveryListener();
+    listener.start((err) => {
+      throw err;
+    });
+    const announcer = new Announcer(() => announcement);
+    announcer.start();
+    await new Promise((r) => setTimeout(r, 400));
+    // Other games may be running on this machine or the LAN: only look at ours.
+    const games = listener.list().filter((g) => g.serverId === 'test-server');
+    announcer.stop();
+    listener.stop();
+    expect(games).toHaveLength(1);
+    expect(games[0]).toMatchObject({ serverId: 'test-server', name: 'Goûter de test', players: 2, port: 47100 });
+    expect(games[0].address).toMatch(/^\d+\.\d+\.\d+\.\d+$/);
+  });
+});

+ 107 - 0
tests/maps.test.ts

@@ -0,0 +1,107 @@
+import { describe, expect, it } from 'vitest';
+import { listMapIds, loadCharacterStats, loadMap } from '../src/server/assets';
+import { Game } from '../src/server/game';
+import { isModifierId } from '../src/server/modifiers';
+import { defaultMap, lastPlaced, rotationPool, sanitizeRotation } from '../src/server/rotation';
+import { TICK_RATE } from '../src/shared/constants';
+import { Rng } from '../src/shared/rng';
+import type { MapSummary } from '../src/shared/protocol';
+import { ASSETS, realMaterials } from './helpers';
+
+const materials = realMaterials();
+const catalog: MapSummary[] = [
+  { id: 'a', name: 'A' },
+  { id: 'b', name: 'B' },
+  { id: 'c', name: 'C' },
+];
+
+describe('built-in maps', () => {
+  it('all load, validate, and only use known modifiers', () => {
+    const ids = listMapIds(ASSETS);
+    expect(ids).toEqual(expect.arrayContaining(['gateau-etages', 'mille-feuille', 'piece-montee']));
+    for (const id of ids) {
+      const { definition, terrain } = loadMap(ASSETS, id, materials);
+      expect(terrain.width).toBe(definition.size[0]);
+      for (const m of definition.modifiers) expect(isModifierId(m), `${id}: ${m}`).toBe(true);
+    }
+  });
+
+  it('la pièce montée: removing a chou drops the column above it', () => {
+    const { definition, terrain } = loadMap(ASSETS, 'piece-montee', materials);
+    const game = new Game({ map: definition, terrain, materials, seed: 1, loadCharacter: (id) => loadCharacterStats(ASSETS, id) });
+    // Bottom row, centre chou: centre (1024, 905 - 42).
+    game.queueOp({ kind: 'carve', x: 1024, y: 863, r: 44, power: 99 });
+    const res = game.step();
+    const heights = res.terrain.flatMap((e) => (e.ev.kind === 'detach' && !e.ev.debris ? [e.ev.h] : []));
+    expect(heights.length).toBeGreaterThanOrEqual(1);
+    expect(Math.max(...heights)).toBeGreaterThan(300); // the whole column, not just one chou
+  });
+});
+
+describe('rotation', () => {
+  it('pool: the selection when valid, every map otherwise', () => {
+    expect(rotationPool({ mode: 'all', selection: ['b'] }, catalog)).toEqual(catalog);
+    expect(rotationPool({ mode: 'selection', selection: ['c', 'a'] }, catalog).map((m) => m.id)).toEqual(['a', 'c']);
+    expect(rotationPool({ mode: 'selection', selection: ['zzz'] }, catalog)).toEqual(catalog);
+    expect(sanitizeRotation({ mode: 'selection', selection: ['a', 'zzz', 'a'] }, catalog)).toEqual({ mode: 'selection', selection: ['a'] });
+  });
+
+  it('default map: in order, or seeded random', () => {
+    const rng = new Rng(1);
+    expect([1, 2, 3, 4].map((r) => defaultMap({ mode: 'all', selection: [] }, catalog, r, rng))).toEqual(['a', 'b', 'c', 'a']);
+    const pick = (): string[] => [1, 2, 3, 4, 5].map((r) => defaultMap({ mode: 'random', selection: [] }, catalog, r, new Rng(9 + r)));
+    expect(pick()).toEqual(pick());
+  });
+
+  it('the last-placed player picks', () => {
+    expect(
+      lastPlaced([
+        { id: 1, name: '', characterId: '', roundScore: 5, total: 20 },
+        { id: 2, name: '', characterId: '', roundScore: 1, total: 3 },
+        { id: 3, name: '', characterId: '', roundScore: 9, total: 3 },
+      ]),
+    ).toBe(2);
+    expect(lastPlaced([])).toBeNull();
+  });
+});
+
+describe('modifiers', () => {
+  function round(mapId: string, seed = 3): Game {
+    const { definition, terrain } = loadMap(ASSETS, mapId, materials);
+    return new Game({ map: definition, terrain, materials, seed, rules: { duration: 180 }, loadCharacter: (id) => loadCharacterStats(ASSETS, id) });
+  }
+
+  it('wind blows players sideways (piece-montee)', () => {
+    const game = round('piece-montee');
+    const { id } = game.addPlayer('Plume', 'generic');
+    game.teleport(id, 300, 300);
+    let maxWind = 0;
+    const x0 = game.snapshot()[0].x;
+    let drift = 0;
+    for (let i = 0; i < 12 * TICK_RATE; i++) {
+      game.step();
+      maxWind = Math.max(maxWind, Math.abs(game.roundState().wind));
+      if (i === 30) drift = game.snapshot().find((p) => p.id === id)!.x - x0;
+    }
+    expect(maxWind).toBeGreaterThan(50);
+    expect(Math.abs(drift)).toBeGreaterThan(0);
+  });
+
+  it('random cracks open in the brittle pastry over time (mille-feuille), deterministically', () => {
+    const a = round('mille-feuille', 4);
+    const b = round('mille-feuille', 4);
+    for (let i = 0; i < 10 * TICK_RATE; i++) {
+      a.step();
+      b.step();
+    }
+    expect(a.events.length).toBeGreaterThan(10);
+    expect(a.terrain.hash()).toBe(b.terrain.hash());
+  });
+
+  it('modifiers are off during the warm-up', () => {
+    const { definition, terrain } = loadMap(ASSETS, 'mille-feuille', materials);
+    const warm = new Game({ map: definition, terrain, materials, seed: 4, loadCharacter: (id) => loadCharacterStats(ASSETS, id) });
+    for (let i = 0; i < 10 * TICK_RATE; i++) warm.step();
+    expect(warm.events).toHaveLength(0);
+  });
+});

+ 280 - 0
tests/net.test.ts

@@ -0,0 +1,280 @@
+import { Packr } from 'msgpackr';
+import { afterEach, describe, expect, it } from 'vitest';
+import WebSocket from 'ws';
+import { loadCharacterStats, loadMap } from '../src/server/assets';
+import { Game } from '../src/server/game';
+import { GameServer, type GameServerOptions } from '../src/server/net';
+import { HASH_CHECK_INTERVAL_S, PROTOCOL_VERSION, START_COUNTDOWN_S, TICK_RATE } from '../src/shared/constants';
+import { Button } from '../src/shared/input';
+import type { ClientMessage, ServerMessage } from '../src/shared/protocol';
+import type { TerrainBitmap } from '../src/shared/terrain/bitmap';
+import { applyTerrainEvent } from '../src/shared/terrain/events';
+import { ASSETS, realMaterials } from './helpers';
+
+const packr = new Packr({ useRecords: false });
+const materials = realMaterials();
+const freshTerrain = (): TerrainBitmap => loadMap(ASSETS, 'gateau-etages', materials).terrain;
+const flush = (ms = 30): Promise<void> => new Promise((r) => setTimeout(r, ms));
+
+/** A headless client that keeps its own bitmap in sync, like the renderer does. */
+class TestClient {
+  readonly messages: ServerMessage[] = [];
+  readonly socket: WebSocket;
+  terrain = freshTerrain();
+  mapId = 'gateau-etages';
+  lastSeq = 0;
+  playerId = -1;
+  hashChecks: { seq: number; server: number; mine: number }[] = [];
+
+  constructor(port: number) {
+    this.socket = new WebSocket(`ws://127.0.0.1:${port}`);
+    this.socket.on('message', (data: Buffer) => this.onMessage(packr.unpack(data) as ServerMessage));
+  }
+
+  async hello(name: string, characterId = 'generic', version = PROTOCOL_VERSION): Promise<void> {
+    await new Promise((r) => this.socket.once('open', r));
+    this.send({ t: 'hello', version, name, characterId });
+  }
+
+  send(msg: ClientMessage): void {
+    this.socket.send(packr.pack(msg));
+  }
+
+  last<T extends ServerMessage['t']>(t: T): Extract<ServerMessage, { t: T }> | undefined {
+    return [...this.messages].reverse().find((m) => m.t === t) as Extract<ServerMessage, { t: T }> | undefined;
+  }
+
+  private onMessage(msg: ServerMessage): void {
+    this.messages.push(msg);
+    if (msg.t === 'welcome') {
+      this.playerId = msg.playerId;
+      for (const { seq, ev } of msg.events) this.apply(seq, ev);
+    } else if (msg.t === 'start') {
+      this.mapId = msg.mapId;
+      this.terrain = loadMap(ASSETS, msg.mapId, materials).terrain;
+      this.lastSeq = 0;
+    } else if (msg.t === 'terrain') {
+      this.apply(msg.seq, msg.ev);
+    } else if (msg.t === 'hash') {
+      expect(this.lastSeq).toBe(msg.seq);
+      this.hashChecks.push({ seq: msg.seq, server: msg.hash, mine: this.terrain.hash() });
+    }
+  }
+
+  private apply(seq: number, ev: Parameters<typeof applyTerrainEvent>[1]): void {
+    expect(seq).toBe(this.lastSeq + 1);
+    this.lastSeq = seq;
+    applyTerrainEvent(this.terrain, ev, materials);
+  }
+}
+
+describe('LAN server (M3)', () => {
+  let server: GameServer | null = null;
+  const clients: TestClient[] = [];
+
+  afterEach(() => {
+    for (const c of clients) c.socket.close();
+    clients.length = 0;
+    server?.close();
+    server = null;
+  });
+
+  async function startServer(pacing: Partial<GameServerOptions> = {}): Promise<GameServer> {
+    await new Promise<void>((resolve) => {
+      server = new GameServer({
+        maps: [
+          { id: 'gateau-etages', name: 'Le Gâteau à Étages' },
+          { id: 'mille-feuille', name: 'Le Mille-Feuille' },
+          { id: 'piece-montee', name: 'La Pièce Montée' },
+        ],
+        ...pacing,
+        createGame: (seed, rules, stats, mapId) => {
+          const { definition, terrain } = loadMap(ASSETS, mapId, materials);
+          return new Game({ map: definition, terrain, materials, seed, rules, stats, loadCharacter: (id) => loadCharacterStats(ASSETS, id) });
+        },
+        seed: 42,
+        port: 0,
+        host: '127.0.0.1',
+        onListening: resolve,
+      });
+    });
+    return server!;
+  }
+
+  function tick(n: number): void {
+    for (let i = 0; i < n; i++) server!.tickOnce();
+  }
+
+  it('rejects a client with another protocol version', async () => {
+    const s = await startServer();
+    const c = new TestClient(s.port);
+    clients.push(c);
+    await c.hello('Vieux', 'generic', PROTOCOL_VERSION - 1);
+    await flush();
+    expect(c.last('reject')).toMatchObject({ reason: 'version', serverVersion: PROTOCOL_VERSION });
+  });
+
+  it('lobby → everyone ready → countdown → match on a fresh map, clients stay bit-identical', async () => {
+    const s = await startServer();
+    const a = new TestClient(s.port);
+    const b = new TestClient(s.port);
+    clients.push(a, b);
+    await a.hello('Alice');
+    await b.hello('Bob', 'castor');
+    await flush();
+    expect(a.last('lobby')).toMatchObject({ phase: 'lobby', countdown: null });
+    expect(a.last('lobby')!.players.map((p) => p.name)).toEqual(['Alice', 'Bob']);
+
+    // Warm-up destruction, then only one player ready: no countdown.
+    tick(120);
+    a.send({ t: 'ready', ready: true });
+    await flush();
+    tick(1);
+    await flush();
+    expect(b.last('lobby')).toMatchObject({ countdown: null });
+
+    b.send({ t: 'ready', ready: true });
+    await flush();
+    expect(a.last('lobby')!.countdown).toBe(START_COUNTDOWN_S);
+    tick(START_COUNTDOWN_S * TICK_RATE);
+    await flush();
+    expect(a.last('start')).toBeDefined();
+    expect(b.last('start')!.players.map((p) => p.id).sort()).toEqual([a.playerId, b.playerId].sort());
+    expect(a.last('lobby')).toMatchObject({ phase: 'playing' });
+
+    // Both dig for a while; snapshots, terrain events and hash checks flow to both clients.
+    for (let i = 0; i < HASH_CHECK_INTERVAL_S * TICK_RATE * 2; i++) {
+      if (i % 10 === 0) {
+        const snap = a.last('snapshot');
+        for (const [c, dy] of [
+          [a, 40],
+          [b, 60],
+        ] as const) {
+          const me = snap?.players.find((p) => p.id === c.playerId);
+          if (me) c.send({ t: 'input', buttons: c === a ? Button.Attack : Button.Special, aimX: Math.round(me.x), aimY: Math.round(me.y + dy) });
+        }
+        await flush(5);
+      }
+      tick(1);
+    }
+    await flush(100);
+    expect(a.lastSeq).toBeGreaterThan(5);
+    for (const c of [a, b]) {
+      expect(c.hashChecks.length).toBeGreaterThanOrEqual(2);
+      for (const h of c.hashChecks) expect(h.mine).toBe(h.server);
+    }
+    expect(a.terrain.hash()).toBe(b.terrain.hash());
+  });
+
+  it('a player leaving is announced and an empty server goes back to the lobby', async () => {
+    const s = await startServer();
+    const a = new TestClient(s.port);
+    const b = new TestClient(s.port);
+    clients.push(a, b);
+    await a.hello('Alice');
+    await b.hello('Bob');
+    await flush();
+    b.socket.close();
+    await flush();
+    expect(a.last('playerLeft')).toMatchObject({ id: b.playerId });
+    expect(a.last('lobby')!.players).toHaveLength(1);
+    a.socket.close();
+    await flush();
+    expect(s.currentPhase).toBe('lobby');
+    expect(s.playerCount).toBe(0);
+  });
+
+  it('a whole match: rounds with results in between, final results with trophies, then back to the lobby', async () => {
+    const s = await startServer({ rounds: 2, roundDuration: 1, roundEndPause: 0.25, matchEndPause: 0.25 });
+    const a = new TestClient(s.port);
+    clients.push(a);
+    await a.hello('Alice', 'castor');
+    await flush();
+    a.send({ t: 'ready', ready: true });
+    await flush();
+    tick(START_COUNTDOWN_S * TICK_RATE);
+    await flush();
+    expect(a.last('start')).toMatchObject({ round: 1, rounds: 2 });
+
+    // Alice eats the cake during round 1 so she earns a trophy.
+    for (let i = 0; i < TICK_RATE + 2; i++) {
+      const me = a.last('snapshot')?.players.find((p) => p.id === a.playerId);
+      if (me && i % 10 === 0) {
+        a.send({ t: 'input', buttons: Button.Special, aimX: Math.round(me.x), aimY: Math.round(me.y + 100) });
+        await flush(5);
+      }
+      tick(1);
+    }
+    await flush();
+    expect(a.last('roundEnd')).toMatchObject({ round: 1, rounds: 2 });
+    expect(a.last('lobby')).toMatchObject({ phase: 'roundEnd' });
+
+    tick(Math.round(0.25 * TICK_RATE));
+    await flush();
+    expect(a.last('start')).toMatchObject({ round: 2 });
+    tick(TICK_RATE + 2);
+    await flush();
+    const end = a.last('matchEnd')!;
+    expect(end).toBeDefined();
+    expect(end.results.map((r) => r.id)).toEqual([a.playerId]);
+    expect(end.trophies).toContainEqual(expect.objectContaining({ id: 'glutton', playerId: a.playerId }));
+
+    tick(Math.round(0.25 * TICK_RATE));
+    await flush();
+    expect(a.last('start')).toMatchObject({ round: 0 });
+    expect(a.last('lobby')).toMatchObject({ phase: 'lobby' });
+    expect(a.last('lobby')!.players[0].ready).toBe(false);
+  });
+
+  it('only the host sets the rotation; the warm-up moves to its first map', async () => {
+    const s = await startServer();
+    const host = new TestClient(s.port);
+    const guest = new TestClient(s.port);
+    clients.push(host, guest);
+    await host.hello('Hote');
+    await guest.hello('Invite');
+    await flush();
+    expect(guest.last('lobby')).toMatchObject({ hostId: host.playerId, rotation: { mode: 'all' } });
+    expect(guest.last('lobby')!.maps.map((m) => m.id)).toEqual(['gateau-etages', 'mille-feuille', 'piece-montee']);
+
+    guest.send({ t: 'rotation', rotation: { mode: 'selection', selection: ['piece-montee'] } });
+    await flush();
+    expect(host.last('lobby')!.rotation.mode).toBe('all');
+
+    host.send({ t: 'rotation', rotation: { mode: 'selection', selection: ['piece-montee', 'nope'] } });
+    await flush(400); // the warm-up map is reloaded: give the server time to decode it
+    expect(guest.last('lobby')!.rotation).toEqual({ mode: 'selection', selection: ['piece-montee'] });
+    expect(guest.last('start')).toMatchObject({ mapId: 'piece-montee', round: 0 });
+  });
+
+  it('the last-placed player picks the next map during the round results', async () => {
+    const s = await startServer({ rounds: 2, roundDuration: 1, roundEndPause: 1, matchEndPause: 0.25 });
+    const a = new TestClient(s.port);
+    const b = new TestClient(s.port);
+    clients.push(a, b);
+    await a.hello('Alice');
+    await b.hello('Bob');
+    await flush();
+    a.send({ t: 'ready', ready: true });
+    b.send({ t: 'ready', ready: true });
+    await flush();
+    tick(START_COUNTDOWN_S * TICK_RATE);
+    await flush();
+    expect(a.last('start')).toMatchObject({ round: 1, mapId: 'gateau-etages' });
+    tick(TICK_RATE + 2);
+    await flush();
+    const end = a.last('roundEnd')!;
+    // Nobody scored: the tie goes to the latest to join.
+    expect(end.picker).toBe(b.playerId);
+    expect(end.choices).toHaveLength(3);
+
+    a.send({ t: 'pickMap', mapId: 'piece-montee' }); // not Alice's call
+    b.send({ t: 'pickMap', mapId: 'mille-feuille' });
+    await flush();
+    expect(a.last('mapPicked')).toEqual({ t: 'mapPicked', mapId: 'mille-feuille', by: b.playerId });
+    tick(TICK_RATE);
+    await flush();
+    expect(a.last('start')).toMatchObject({ round: 2, mapId: 'mille-feuille' });
+    expect(b.mapId).toBe('mille-feuille');
+  });
+});

+ 206 - 0
tests/rules.test.ts

@@ -0,0 +1,206 @@
+import { describe, expect, it } from 'vitest';
+import { loadCharacterStats, loadMap } from '../src/server/assets';
+import { Game } from '../src/server/game';
+import { MatchStats } from '../src/server/stats';
+import { Anim } from '../src/shared/characters';
+import { CHERRY_REGRAB_DELAY, FINAL_RUSH_S, RESPAWN_DELAY_S, SMARTIES_DURATION_S, TICK_RATE } from '../src/shared/constants';
+import { Button } from '../src/shared/input';
+import type { FxEvent } from '../src/shared/protocol';
+import { ASSETS, realMaterials } from './helpers';
+
+const materials = realMaterials();
+
+function newRound(duration = 180, seed = 1): Game {
+  const { definition, terrain } = loadMap(ASSETS, 'gateau-etages', materials);
+  return new Game({ map: definition, terrain, materials, seed, rules: { duration }, loadCharacter: (id) => loadCharacterStats(ASSETS, id) });
+}
+
+function run(game: Game, ticks: number): FxEvent[] {
+  const fx: FxEvent[] = [];
+  for (let i = 0; i < ticks; i++) fx.push(...game.step().fx);
+  return fx;
+}
+
+const me = (game: Game, id: number) => game.snapshot().find((p) => p.id === id)!;
+
+describe('custard and the spoon', () => {
+  it('rises during a round, faster in the final rush, and stays put during the warm-up', () => {
+    const round = newRound(40);
+    const start = round.custardLevel;
+    run(round, 5 * TICK_RATE);
+    const slow = start - round.custardLevel;
+    expect(slow).toBeCloseTo(round.map.custard.speed * 5, 0);
+    run(round, (40 - FINAL_RUSH_S) * TICK_RATE); // into the final rush
+    const before = round.custardLevel;
+    run(round, 5 * TICK_RATE);
+    expect(before - round.custardLevel).toBeCloseTo(round.map.custard.finalRushSpeed * 5, 0);
+    expect(round.roundState().finalRush).toBe(true);
+
+    const { definition, terrain } = loadMap(ASSETS, 'gateau-etages', materials);
+    const warmup = new Game({ map: definition, terrain, materials, seed: 1, loadCharacter: (id) => loadCharacterStats(ASSETS, id) });
+    run(warmup, 5 * TICK_RATE);
+    expect(warmup.custardLevel).toBe(definition.custard.startY);
+    expect(warmup.roundState()).toMatchObject({ timeLeft: null, cherry: null });
+  });
+
+  it('a player falling in is out for 5 s, then the spoon launches them back from open air', () => {
+    const game = newRound();
+    const { id } = game.addPlayer('Plouf', 'generic');
+    game.teleport(id, 100, 900); // left of the cake: nothing below but custard
+    const fx = run(game, TICK_RATE);
+    expect(fx).toContainEqual(expect.objectContaining({ kind: 'splash', id }));
+    expect(me(game, id).anim & Anim.Dead).toBeTruthy();
+    expect(game.stats.get(id, 'custard')).toBe(1);
+
+    const later = run(game, RESPAWN_DELAY_S * TICK_RATE);
+    const spoon = later.find((e) => e.kind === 'spoon');
+    expect(spoon).toBeDefined();
+    const p = me(game, id);
+    expect(p.anim & Anim.Dead).toBe(0);
+    expect(p.y).toBeLessThan(game.custardLevel);
+    // ...and lands on the cake instead of falling straight back in.
+    const flight = run(game, 3 * TICK_RATE);
+    expect(flight.filter((e) => e.kind === 'splash' && e.id === id)).toEqual([]);
+    expect(me(game, id).grounded).toBe(true);
+  });
+
+  it('the spoon lands players back on the cake whatever spawn it rolls (several seeds)', () => {
+    for (const seed of [1, 2, 3, 4, 5, 6]) {
+      const game = newRound(180, seed);
+      const { id } = game.addPlayer('Plouf', 'generic');
+      game.teleport(id, 100, 900);
+      run(game, (RESPAWN_DELAY_S + 0.5) * TICK_RATE);
+      const fx = run(game, 3 * TICK_RATE);
+      expect(fx.filter((e) => e.kind === 'splash' && e.id === id), `seed ${seed}`).toEqual([]);
+    }
+  });
+
+  it('the round ends when the timer runs out', () => {
+    const game = newRound(2);
+    run(game, 2 * TICK_RATE - 1);
+    expect(game.roundOver).toBe(false);
+    run(game, 2);
+    expect(game.roundOver).toBe(true);
+  });
+});
+
+describe('the cherry', () => {
+  it('is picked up by touching it and scores 1 point per second', () => {
+    const game = newRound();
+    const { id } = game.addPlayer('Gourmand', 'generic');
+    const [cx, cy] = game.map.cherrySpawn;
+    run(game, 30); // let the cherry settle on the top tier
+    const cherry = game.roundState().cherry!;
+    game.teleport(id, cherry.x, cherry.y - 10);
+    const fx = run(game, 10);
+    expect(fx).toContainEqual(expect.objectContaining({ kind: 'pickup', id, item: 'cherry' }));
+    expect(game.roundState().cherry!.holder).toBe(id);
+    run(game, 3 * TICK_RATE);
+    expect(me(game, id).score).toBeGreaterThanOrEqual(3);
+    expect([cx, cy]).toEqual(game.map.cherrySpawn);
+  });
+
+  it('a hit holder drops it, and cannot grab it back right away', () => {
+    const game = newRound();
+    const holder = game.addPlayer('Porteur', 'generic');
+    const biter = game.addPlayer('Castor', 'castor');
+    run(game, 30);
+    const cherry = game.roundState().cherry!;
+    game.teleport(holder.id, cherry.x, cherry.y - 10);
+    run(game, 10);
+    expect(game.roundState().cherry!.holder).toBe(holder.id);
+
+    const h = me(game, holder.id);
+    game.teleport(biter.id, h.x - 45, h.y);
+    game.setInput(biter.id, { buttons: Button.Attack, aimX: Math.round(h.x), aimY: Math.round(h.y) });
+    const fx = run(game, 2);
+    expect(fx).toContainEqual(expect.objectContaining({ kind: 'cherryDrop', id: holder.id }));
+    expect(game.roundState().cherry!.holder).not.toBe(holder.id);
+    expect(game.stats.get(biter.id, 'hits')).toBeGreaterThanOrEqual(1);
+    // Still blocked for the holder for a moment.
+    game.setInput(biter.id, { buttons: 0, aimX: 0, aimY: 0 });
+    run(game, Math.floor(CHERRY_REGRAB_DELAY * TICK_RATE * 0.5));
+    expect(game.roundState().cherry!.holder).not.toBe(holder.id);
+  });
+});
+
+describe('items', () => {
+  it('a candle is picked up, thrown with Use, and explodes: carves the cake and blows players away', () => {
+    const game = newRound();
+    const { id } = game.addPlayer('Artificier', 'generic');
+    run(game, 90);
+    const p = me(game, id);
+    game.spawnItem('candle', p.x, p.y - 30);
+    const fx = run(game, 20);
+    expect(fx).toContainEqual(expect.objectContaining({ kind: 'pickup', id, item: 'candle' }));
+    expect(me(game, id).item).toBe('candle');
+
+    const eventsBefore = game.events.length;
+    game.setInput(id, { buttons: Button.Use, aimX: Math.round(p.x + 60), aimY: Math.round(p.y + 80) });
+    const after = run(game, 2 * TICK_RATE);
+    expect(me(game, id).item).toBeNull();
+    expect(after).toContainEqual(expect.objectContaining({ kind: 'explosion' }));
+    expect(game.events.length).toBeGreaterThan(eventsBefore);
+    expect(game.stats.get(id, 'candles')).toBe(1);
+  });
+
+  it('smarties boost the speed for a while', () => {
+    const game = newRound();
+    const { id } = game.addPlayer('Speedy', 'generic');
+    run(game, 90);
+    const p = me(game, id);
+    game.spawnItem('smarties', p.x, p.y - 30);
+    run(game, 20);
+    expect(me(game, id).anim & Anim.Boosted).toBeTruthy();
+    run(game, SMARTIES_DURATION_S * TICK_RATE);
+    expect(me(game, id).anim & Anim.Boosted).toBe(0);
+  });
+
+  it('the electric whisk jolts the others and shakes the jelly', () => {
+    const game = newRound();
+    const a = game.addPlayer('Fouet', 'generic');
+    const b = game.addPlayer('Victime', 'generic');
+    run(game, 90);
+    const p = me(game, a.id);
+    const eventsBefore = game.events.length;
+    game.spawnItem('whisk', p.x, p.y - 30);
+    let whisked = false;
+    for (let i = 0; i < 30 && !whisked; i++) whisked = game.step().fx.some((e) => e.kind === 'whisk' && e.id === a.id);
+    expect(whisked).toBe(true);
+    // Same tick: the other player is jolted and stunned.
+    expect(me(game, b.id).anim & Anim.Stunned).toBeTruthy();
+    run(game, 2);
+    expect(game.events.length).toBeGreaterThan(eventsBefore + 5);
+    expect(game.stats.get(a.id, 'eaten')).toBeGreaterThan(0);
+  });
+
+  it('items fall from the sky on their own during a round (seeded)', () => {
+    const a = newRound(180, 7);
+    const b = newRound(180, 7);
+    // The first item drops within map.items.interval[1] seconds; both games drop the same ones.
+    let seen = 0;
+    for (let i = 0; i < a.map.items.interval[1] * TICK_RATE + 2; i++) {
+      a.step();
+      b.step();
+      seen = Math.max(seen, a.itemStates().length);
+    }
+    expect(seen).toBeGreaterThan(0);
+    expect(a.itemStates()).toEqual(b.itemStates());
+  });
+});
+
+describe('trophies', () => {
+  it('go to the best player of each stat, only if they did it', () => {
+    const stats = new MatchStats();
+    stats.add(1, 'eaten', 5000);
+    stats.add(2, 'eaten', 300);
+    stats.add(2, 'custard', 3);
+    stats.add(3, 'crushed', 1);
+    stats.add(3, 'hitTaken', 4);
+    const t = stats.trophies([1, 2, 3]);
+    expect(t).toContainEqual({ id: 'glutton', playerId: 1, value: 5000 });
+    expect(t).toContainEqual({ id: 'kamikaze', playerId: 2, value: 3 });
+    expect(t).toContainEqual({ id: 'notMyFault', playerId: 3, value: 5 });
+    expect(t.find((x) => x.id === 'pyromaniac')).toBeUndefined();
+  });
+});