5 Commits a11d7249aa ... b5a481ba6c

Autore SHA1 Messaggio Data
  Idleman b5a481ba6c feat(game): surprises, a living cherry, cartoon hits 3 settimane fa
  Idleman 68aececba8 feat(game): wall jumps for everyone, a heavy cherry that comes back anywhere 3 settimane fa
  Idleman 52b06970f2 feat(characters): add Tatie Douille (turrets) and Léon le Caméléon (invisible) 3 settimane fa
  Idleman e6a5f93374 fix(dist): hash release blobs without eol filters, run npm without shell args 3 settimane fa
  Idleman 2be396f3f5 feat(dist): self-update from the git repository's release tags 3 settimane fa

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

@@ -0,0 +1,25 @@
+{
+  "id": "leon",
+  "name": "Léon le Caméléon",
+  "speed": 245,
+  "acceleration": 2200,
+  "jump": 610,
+  "mass": 0.9,
+  "size": 18,
+  "cooldowns": {
+    "attack": 0.6,
+    "special": 6
+  },
+  "params": {
+    "tongueReach": 110,
+    "tongueStep": 12,
+    "tongueCarve": 5,
+    "tonguePower": 25,
+    "tongueRadius": 18,
+    "tongueStun": 0.35,
+    "tonguePull": 620,
+    "tongueLift": 120,
+    "tongueAnim": 0.22,
+    "invisibleTime": 5
+  }
+}

+ 2 - 1
assets/characters/prout/character.json

@@ -23,6 +23,7 @@
     "cloudRadius": 46,
     "cloudLife": 3.5,
     "puffAnim": 0.25,
-    "airPuffs": 3
+    "airPuffs": 3,
+    "cherryAirPuffs": 1
   }
 }

+ 38 - 0
assets/characters/tatie/character.json

@@ -0,0 +1,38 @@
+{
+  "id": "tatie",
+  "name": "Tatie Douille",
+  "speed": 210,
+  "acceleration": 1800,
+  "jump": 570,
+  "mass": 1.1,
+  "size": 20,
+  "cooldowns": {
+    "attack": 0.4,
+    "special": 2.5
+  },
+  "params": {
+    "pinReach": 14,
+    "pinRadius": 18,
+    "pinKnockback": 560,
+    "pinStun": 0.35,
+    "pinCarve": 12,
+    "pinPower": 30,
+    "pinAnim": 0.2,
+    "buildReach": 120,
+    "buildAnim": 0.6,
+    "turretBaseRadius": 13,
+    "turretMaterial": 5,
+    "turretHeight": 18,
+    "turretRange": 420,
+    "turretInterval": 1.3,
+    "turretLife": 25,
+    "turretMax": 2,
+    "turretGroundReach": 160,
+    "drageeSpeed": 760,
+    "drageeFuse": 1.2,
+    "drageeRadius": 10,
+    "drageePower": 25,
+    "drageeKnockback": 420,
+    "drageeStun": 0.25
+  }
+}

+ 3 - 0
electron.vite.config.ts

@@ -6,8 +6,11 @@ export default defineConfig({
     plugins: [externalizeDepsPlugin()],
     build: {
       rollupOptions: {
+        external: ['original-fs'],
         // The server is bundled next to main so it can be forked in a utilityProcess.
+        // boot picks the installed game or a downloaded update (src/main/updater.ts), then loads index.
         input: {
+          boot: resolve(__dirname, 'src/main/boot.ts'),
           index: resolve(__dirname, 'src/main/index.ts'),
           server: resolve(__dirname, 'src/server/index.ts'),
         },

+ 3 - 2
package.json

@@ -2,7 +2,7 @@
   "name": "goutermageddon",
   "version": "0.1.0",
   "description": "Jeu de baston 2D en LAN dans un goûter géant entièrement destructible.",
-  "main": "./out/main/index.js",
+  "main": "./out/main/boot.js",
   "private": true,
   "scripts": {
     "dev": "electron-vite dev",
@@ -13,7 +13,8 @@
     "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:maps": "tsx scripts/gen-maps.ts"
+    "gen:maps": "tsx scripts/gen-maps.ts",
+    "release": "tsx scripts/release.ts"
   },
   "dependencies": {
     "msgpackr": "^1.12.1",

+ 36 - 2
readme.md

@@ -47,6 +47,7 @@ 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           # versions Windows autonomes dans dist/ (electron-builder)
+npm run release -- 0.2.0   # publie la version 0.2.0 : tag, build, mise à jour automatique (voir plus bas)
 ```
 
 `npm run dist` produit trois fichiers dans `dist/`. Aucun d'eux n'a besoin de Node.js sur le PC qui joue :
@@ -55,6 +56,18 @@ npm run dist           # versions Windows autonomes dans dist/ (electron-builder
 - `Goutermageddon-<version>-x64.zip` : le jeu décompressé. On extrait le dossier et on lance `Goûtermageddon.exe`. Le démarrage est plus rapide, et l'autorisation du pare-feu reste valable d'une fois sur l'autre.
 - `Goutermageddon-<version>-setup.exe` : un installeur classique, avec un raccourci dans le menu Démarrer.
 
+### Mises à jour automatiques
+
+Le jeu installé se met à jour tout seul à partir du dépôt Git (`UPDATE_REPO_URL`), sans serveur en plus :
+
+- `npm run release -- <x.y.z>` vérifie que `main` est propre, lance les tests et le lint, change la version, construit les exe, puis crée le tag `v<x.y.z>` et un commit sans parent à la référence `refs/builds/v<x.y.z>`. Ce commit contient les fichiers du jeu (`app.asar`, ses modules natifs, `assets/`, environ 16 Mo) et un `manifest.json` (taille et sha256 de chaque fichier). Le script pousse ensuite `main`, le tag et le build (`--no-push` pour ne rien pousser). Un clone ne récupère jamais `refs/builds/*`, donc l'historique du code reste léger.
+- Au lancement, le jeu lit les références du dépôt (`info/refs`, public) et cherche un build plus récent que lui. Il télécharge les fichiers modifiés par l'URL brute du serveur Git, vérifie chaque sha256, et range la version dans `%APPDATA%\Goûtermageddon\game\<version>\`. Un bandeau en bas à gauche affiche la progression, puis un bouton « Relancer ».
+- Le point d'entrée (`main/boot.ts`) lance la version téléchargée la plus récente, sinon celle de l'installeur. Si la version téléchargée plante au démarrage, il revient à celle de l'installeur.
+- Seul le code du jeu est mis à jour, pas le runtime Electron. Si un build utilise une autre version majeure d'Electron, le jeu affiche qu'il faut réinstaller.
+- Ça marche avec l'installeur, le zip et l'exe portable (la version téléchargée est rangée dans le profil Windows du joueur, pas à côté de l'exe).
+- Le nouveau joueur reçoit une seule fois `Goutermageddon-<version>-setup.exe` (ou le portable) ; ensuite tout passe par les releases.
+- `GOUTER_NO_UPDATE=1` désactive la mise à jour, `GOUTER_UPDATE_REPO=<url>` la fait pointer sur un autre dépôt (tests).
+
 Les exe ne sont pas signés. Windows SmartScreen affiche donc « Windows a protégé votre ordinateur » : il faut cliquer sur « Informations complémentaires », puis « Exécuter quand même ». Au premier hébergement, le pare-feu demande l'accès : il faut cocher **Réseaux privés**, sinon les autres PC ne voient pas la partie.
  
 ---
@@ -105,10 +118,24 @@ Toute la logique aléatoire (objets, Magicien Raté, mutateurs) passe par un **R
  
 ### Déroulement d'une manche
  
-- La cerise apparaît au sommet de la carte (position définie par la carte).
+- La cerise apparaît au sommet de la carte (position définie par la carte). Si elle tombe dans la crème, elle revient sur une corniche du gâteau tirée au hasard (pas forcément en haut).
+- La cerise est lourde : celui qui la tient saute moins haut (`CHERRY_HOLDER_JUMP_MULT`), et Captain Prout n'a qu'une poussée.
+- **La cerise est vivante :** elle a des yeux et regarde le joueur le plus proche. Quand elle est libre et posée, elle fait un bond pour s'éloigner de celui qui approche (`CHERRY_FLEE_*`).
+- **Patate chaude :** tenue `CHERRY_HOT_S` secondes par le même joueur, elle chauffe, tremble, fait tic-tac, puis lui explose dans les mains.
+- **Vol :** faire lâcher la cerise par un coup et la rattraper dans les `CHERRY_STEAL_WINDOW_S` secondes rapporte `CHERRY_STEAL_BONUS` points.
+- **Surprises** (`server/surprises/`) : deux fois par manche, à un moment tiré au hasard, un événement est annoncé en grand :
+  - « Le chat de la maison passe ! » : une patte géante balaie le sommet du gâteau et projette ceux qui s'y trouvent ;
+  - « L'enfant a faim ! » : une ombre grandit, puis une main arrache une poignée de gâteau et lance ceux qui sont dessous ;
+  - « Tremblement de table ! » : les joueurs au sol sautent et le gâteau se fissure ;
+  - « Pluie de vermicelles ! » : des vermicelles tombent et grignotent le gâteau partout ;
+  - « Panne de courant ! » : noir complet, seuls les yeux des joueurs brillent.
+
+  Les poids et les durées sont dans `SURPRISE_WEIGHTS` et `SURPRISE_DURATIONS`.
+- **Coups de dessin animé :** un joueur projeté tourne sur lui-même en sifflant. S'il percute un mur ou le sol, il s'y écrase (« SPLAF ! »).
 - Tant qu'un joueur la tient, il marque **1 point par seconde**. S'il est touché, il la lâche et elle roule (objet physique).
 - **La crème anglaise monte** en continu. La vitesse est définie par la carte et accélère dans les 30 dernières secondes.
 - Un joueur qui tombe dans la crème réapparaît 5 secondes plus tard sur une **cuillère-catapulte** qui le renvoie sur le terrain. La cuillère vise une corniche du gâteau qu'elle peut atteindre (trajectoire vérifiée contre le terrain), même s'il ne reste qu'un petit îlot.
+- **Saut contre un mur**, pour tous les personnages : en l'air contre une paroi, sauter fait rebondir dessus. En gardant la direction du mur, on y revient et on grimpe. On y glisse aussi plus lentement (`WALL_*`). Aucun personnage ne reste coincé sous un étage.
 - Un joueur coincé peut **abandonner** (touche K) : il plonge dans la crème et revient par la cuillère.
 - La manche s'arrête plus tôt s'il ne reste presque plus de gâteau au-dessus de la crème (`MIN_CAKE_PIXELS`).
 - Des **objets tombent du ciel** à intervalles aléatoires :
@@ -154,6 +181,8 @@ Ils sont définis dans `src/shared/characters/` : une classe par personnage qui
 | **Captain Prout** | Coup de cape | Jetpack par petites poussées (3 avant de reposer le pied), laisse un nuage toxique (vision floue + toux) | Chaque poussée s'entend |
 | **Le Chat** | Coup de patte qui griffe | Bond griffes en avant : creuse, éjecte qui il percute, puis pousse blocs, objets et joueurs | Se lèche la patte au hasard |
 | **Magicien Raté** | Baguette | Sort aléatoire : terrain en gelée, échange de position, lapin géant, « pfft » | Tirage pondéré : plus il est en tête, plus ses sorts ratent |
+| **Tatie Douille** | Rouleau à pâtisserie | Pose une tourelle sur le gâteau (socle en biscuit) qui tire des dragées sur le joueur le plus proche, jamais sur elle (2 au plus) | Reste plantée le temps de la poser, et la tourelle tombe avec le gâteau dessous |
+| **Léon le Caméléon** | Grande langue : creuse un sillon et ramène ce qu'elle attrape (joueurs, objets, blocs) | Invisible pour les autres pendant 5 s (il se voit en fantôme) | Attaquer ou être touché le révèle, et la cerise qu'il tient reste visible |
  
 API commune : `onAttack()`, `onSpecial()`, `onTick(dt)`, `onHit()`, et les stats (`speed`, `jump`, `mass`, `size`, `cooldowns`).
  
@@ -190,7 +219,7 @@ type TerrainOp =
 - Quand le bloc s'immobilise (vitesse quasi nulle pendant 0,5 s), le serveur le **rastérise** dans le bitmap et diffuse `merge { id, x, y, w, h, patch }`. Le patch est le résultat pixel par pixel, pour qu'aucun client n'ait à recalculer la rotation. Il comble jusqu'à `CHUNK_GLUE_PX` pixels sous le bloc pour le raccrocher au sol. Si le résultat ne serait pas ancré (bloc posé sur un joueur ou sur un autre bloc), la réintégration est retentée plus tard.
 - Les ops, `detach` et `merge` forment **un seul flux d'événements séquencés** (`shared/terrain/events.ts`) : c'est ce flux, rejoué dans l'ordre, qui garantit un bitmap identique au bit près sur tous les clients (vérifié par les tests).
 - Côté physique, un bloc est approché par des boîtes alignées sur une grille (Box2D ne fait pas collisionner deux chaînes entre elles).
-- Un bloc qui tombe et percute un joueur avec assez d'énergie l'écrase (élimination). Les blocs mous (laine, chantilly : densité < `CRUSH_MIN_DENSITY`) n'écrasent pas. Un bloc qui tombe dans la crème disparaît.
+- Un bloc qui tombe et percute un joueur avec assez d'énergie l'écrase. La vitesse prise en compte est celle d'avant le choc. Un gros bloc élimine le joueur, mais un bloc de moins de `CRUSH_KILL_PIXELS` le transforme seulement en crêpe : il reste aplati et immobile pendant `FLAT_S`. Les blocs mous (laine, chantilly : densité < `CRUSH_MIN_DENSITY`) n'écrasent pas. Un bloc qui tombe dans la crème disparaît.
 ### Budget de performance
  
 - Une op avec flood-fill et régénération des colliders doit tenir en **2 ms** côté serveur. Si ce n'est pas le cas, on optimise : flood-fill borné, bitsets, cache des composantes.
@@ -357,6 +386,7 @@ Chaque étape doit être **jouable** avant de passer à la suivante.
     - Les signatures (prout, jet, sortie de terre, sorts, léchouille) passent par un événement `cue` commun, prêt pour l'audio.
   - **DA, première passe finale :** terrain et fonds nets à toutes les résolutions, personnages en volume et plus expressifs, ambiance onirique (§7).
   - **Versions Windows autonomes :** `npm run dist` produit un exe portable, un zip et un installeur (§2). Ils ne sont pas signés et n'ont pas encore d'icône.
+  - **Mises à jour automatiques :** `npm run release` publie une version dans le dépôt Git, et le jeu installé la télécharge au lancement (§2).
   - **Retours de la première vraie partie :**
     - **Équilibrage :** plus d'assommage en boucle (§4). Pyromanchot : pétards qui vont plus loin, explosion ratée aléatoire et moins forte. Captain Prout : 3 poussées avant de reposer le pied. Gégé : saute plus haut et creuse le chocolat. Bébé Pompier : son détrempage piège ceux qui marchent dessus et ralentit ceux qu'il arrose. Le Chat : bond griffu, coup de patte plus fort, léchouilles plus rares.
     - **Cuillère :** elle vise une corniche atteignable (§4).
@@ -368,6 +398,10 @@ Chaque étape doit être **jouable** avant de passer à la suivante.
     - **Cartes :** la Pile de Crêpes est refaite (crêpes épaisses, garnitures molles qu'on peut toutes creuser, une seconde petite pile). Des gaufrettes servent de corniches autour du Roulé, et les choux de la Pièce Montée ont le dessus plat.
     - **Captain Prout :** le flou du nuage passe par le filtre onirique. Il ne rétrécit plus l'écran.
   - **Audio :** tous les sons sont synthétisés en WebAudio (`renderer/audio/`), sans fichier. Chaque matériau joue le son nommé dans `materials.json` (`sfx`). Les sons sont spatialisés autour de la caméra et varient à chaque fois. La musique, « Joyeux anniversaire » à la flûte à bec, accélère au fil de la manche et pendant la montée finale.
+  - **Deux personnages en plus :**
+    - **Tatie Douille :** sa tourelle est posée sur le terrain. Le socle est un disque de biscuit (`fill`), et quand ce socle disparaît, la tourelle disparaît aussi. La tourelle vise le joueur le plus proche qu'elle voit (ligne de vue vérifiée contre le terrain) et tire en compensant la gravité. Les dragées sont des projectiles comme les pétards, trop faibles pour casser le biscuit. Réglages : `turret*` et `dragee*` dans `character.json`.
+    - **Léon le Caméléon :** l'invisibilité est un drapeau d'animation. Le serveur continue d'envoyer sa position et ce sont les clients qui le cachent : c'est suffisant entre amis en LAN.
+  - **Plus drôle :** surprises, cerise vivante (patate chaude, vol), coups de dessin animé et joueur aplati en crêpe (§4, §5).
   - **Écran d'options** (Échap ou ⚙) : volumes, son coupé, secousses de l'écran. Les réglages sont gardés sur le PC (`renderer/settings.ts`).
 - **Reste :** la suite de la DA (sprites dessinés, particules par matériau), l'éditeur de cartes, et l'icône et la signature des exe.
 ---

+ 111 - 0
scripts/release.ts

@@ -0,0 +1,111 @@
+// Publishes a new version (readme §2): npm run release -- <x.y.z> [--no-push] [--skip-checks]
+//
+// 1. checks (clean tree on main, tests and lint), bumps the version;
+// 2. builds the Windows exes (npm run dist);
+// 3. stores the game files (app.asar, its unpacked natives, assets/) with a manifest.json in a
+//    parentless commit at refs/builds/v<x.y.z>, next to the tag v<x.y.z> of the source;
+// 4. pushes main, the tag and the build: installed games pick it up at their next launch.
+import { execFileSync, execSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, relative, resolve } from 'node:path';
+import { BUILD_REF_PREFIX, compareVersions, isVersion, MANIFEST_FILE, type BuildManifest } from '../src/main/updates';
+
+const root = resolve(import.meta.dirname, '..');
+const resources = join(root, 'dist', 'win-unpacked', 'resources');
+/** What a build carries: everything else in resources/ belongs to the installed runtime. */
+const PAYLOAD = ['app.asar', 'app.asar.unpacked', 'assets'];
+
+const args = process.argv.slice(2);
+const version = args.find((a) => !a.startsWith('--')) ?? '';
+const push = !args.includes('--no-push');
+const checks = !args.includes('--skip-checks');
+
+function run(cmd: string, cmdArgs: string[], env?: NodeJS.ProcessEnv): string {
+  return execFileSync(cmd, cmdArgs, { cwd: root, encoding: 'utf8', env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'inherit'] }).trim();
+}
+const git = (...a: string[]): string => run('git', a);
+function npm(...a: string[]): void {
+  console.log(`\n> npm ${a.join(' ')}`);
+  execSync(`npm ${a.join(' ')}`, { cwd: root, stdio: 'inherit' });
+}
+function fail(message: string): never {
+  console.error(`\n✗ ${message}`);
+  process.exit(1);
+}
+
+function listFiles(dir: string): string[] {
+  return readdirSync(dir, { withFileTypes: true }).flatMap((e) =>
+    e.isDirectory() ? listFiles(join(dir, e.name)) : [join(dir, e.name)],
+  );
+}
+
+/** Writes the payload into the git object store and returns the commit of the build. */
+function commitBuild(): string {
+  const electron = (JSON.parse(readFileSync(join(root, 'node_modules', 'electron', 'package.json'), 'utf8')) as { version: string }).version;
+  const files = PAYLOAD.flatMap((p) => {
+    const abs = join(resources, p);
+    return statSync(abs).isDirectory() ? listFiles(abs) : [abs];
+  });
+  const manifest: BuildManifest = {
+    version,
+    electron,
+    files: files.map((abs) => ({
+      path: relative(resources, abs).split('\\').join('/'),
+      size: statSync(abs).size,
+      sha256: createHash('sha256').update(readFileSync(abs)).digest('hex'),
+    })),
+  };
+  // A throwaway index, so the working tree and the real index stay untouched.
+  const tmp = mkdtempSync(join(tmpdir(), 'goutermageddon-release-'));
+  const env = { GIT_INDEX_FILE: join(tmp, 'index') };
+  try {
+    const add = (path: string, blob: string): void => {
+      run('git', ['update-index', '--add', '--cacheinfo', `100644,${blob},${path}`], env);
+    };
+    for (const [i, f] of manifest.files.entries()) add(f.path, run('git', ['hash-object', '-w', '--no-filters', '--', files[i]]));
+    const manifestBlob = execFileSync('git', ['hash-object', '-w', '--no-filters', '--stdin'], { cwd: root, input: JSON.stringify(manifest, null, 1), encoding: 'utf8' }).trim();
+    add(MANIFEST_FILE, manifestBlob);
+    const tree = run('git', ['write-tree'], env);
+    const size = manifest.files.reduce((s, f) => s + f.size, 0);
+    console.log(`\nBuild v${version}: ${manifest.files.length} files, ${(size / 1e6).toFixed(1)} MB (Electron ${electron})`);
+    return git('commit-tree', tree, '-m', `build v${version}`);
+  } finally {
+    rmSync(tmp, { recursive: true, force: true });
+  }
+}
+
+const current = (JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version: string }).version;
+if (!isVersion(version)) fail(`usage: npm run release -- <x.y.z>   (current version: ${current})`);
+if (compareVersions(version, current) <= 0) fail(`${version} must be newer than the current version ${current}`);
+if (git('rev-parse', '--abbrev-ref', 'HEAD') !== 'main') fail('releases are made from main');
+if (git('status', '--porcelain', '--untracked-files=no')) fail('commit or stash your changes first');
+if (git('tag', '--list', `v${version}`)) fail(`tag v${version} already exists`);
+
+if (checks) {
+  npm('test');
+  npm('run', 'lint');
+}
+npm('version', version, '--no-git-tag-version');
+try {
+  npm('run', 'dist');
+} catch {
+  git('checkout', '--', 'package.json', 'package-lock.json');
+  fail('build failed; version bump undone');
+}
+
+const build = commitBuild();
+git('commit', '-q', '-m', `chore: release v${version}`, '--', 'package.json', 'package-lock.json');
+git('tag', '-a', `v${version}`, '-m', `v${version}`);
+git('update-ref', `${BUILD_REF_PREFIX}${version}`, build);
+console.log(`Tag v${version} and ${BUILD_REF_PREFIX}${version} (${build.slice(0, 7)}) created.`);
+
+if (push) {
+  console.log('\n> git push');
+  execFileSync('git', ['push', 'origin', 'main', `v${version}`, `${BUILD_REF_PREFIX}${version}`], { cwd: root, stdio: 'inherit' });
+  console.log(`\n✓ v${version} published: installed games update at their next launch.`);
+} else {
+  console.log(`\nNot pushed. To publish: git push origin main v${version} ${BUILD_REF_PREFIX}${version}`);
+}
+console.log(`First install for a new player: dist/Goutermageddon-${version}-setup.exe (or -portable.exe).`);

+ 40 - 0
src/main/boot.ts

@@ -0,0 +1,40 @@
+// Electron entry point. Runs the newest game: the one shipped with the installer, or a newer
+// one downloaded by updater.ts into userData/game/<version>/ (readme §2).
+import { join } from 'node:path';
+import { app } from 'electron';
+import * as fs from 'original-fs';
+import { compareVersions, CURRENT_FILE, isVersion, MANIFEST_FILE } from './updates';
+
+/** Loads a CommonJS entry by absolute path, left as is by the bundler. */
+// eslint-disable-next-line @typescript-eslint/no-require-imports -- the game entry is chosen at runtime
+const load = (path: string): unknown => require(path);
+
+/** Folder of a downloaded game newer than the built-in one, if there is a complete one. */
+function downloadedGame(): string | null {
+  if (!app.isPackaged || process.env.GOUTER_NO_UPDATE) return null;
+  try {
+    const gamesDir = join(app.getPath('userData'), 'game');
+    const { version } = JSON.parse(fs.readFileSync(join(gamesDir, CURRENT_FILE), 'utf8')) as { version: string };
+    const root = join(gamesDir, version);
+    if (!isVersion(version) || compareVersions(version, app.getVersion()) <= 0) return null;
+    return fs.existsSync(join(root, MANIFEST_FILE)) ? root : null;
+  } catch {
+    return null;
+  }
+}
+
+const root = downloadedGame();
+let started = false;
+if (root) {
+  try {
+    process.env.GOUTER_GAME_ROOT = root;
+    load(join(root, 'app.asar', 'out', 'main', 'index.js'));
+    started = true;
+  } catch (err) {
+    // A broken download must not keep the game from starting: forget it and run the built-in one.
+    console.error('[boot] downloaded game failed, falling back to the built-in one:', err);
+    delete process.env.GOUTER_GAME_ROOT;
+    fs.rmSync(join(root, '..', CURRENT_FILE), { force: true });
+  }
+}
+if (!started) load(join(__dirname, 'index.js'));

+ 36 - 3
src/main/index.ts

@@ -1,13 +1,18 @@
 import { join } from 'node:path';
 import { app, BrowserWindow, ipcMain, utilityProcess, type UtilityProcess, type WebContents } from 'electron';
 import { readFileSync } from 'node:fs';
-import type { HostResult, MapFiles } from '../preload/api';
-import { DISCOVERY_INTERVAL_MS } from '../shared/constants';
+import type { HostResult, MapFiles, UpdateStatus } from '../preload/api';
+import { DISCOVERY_INTERVAL_MS, UPDATE_CHECK_DELAY_MS, UPDATE_REPO_URL } from '../shared/constants';
 import { loadCharacterStats, readMapFiles, readMapImage, resolveAssetsDir } from '../server/assets';
 import { CHARACTER_IDS } from '../shared/characters';
 import { DiscoveryListener } from './discovery';
+import { checkForUpdate } from './updater';
 
-const assetsDir = app.isPackaged ? join(process.resourcesPath, 'assets') : join(app.getAppPath(), 'assets');
+/** Folder holding app.asar and assets/: set by boot.ts for a downloaded version, else the installed one. */
+const gameRoot = process.env.GOUTER_GAME_ROOT ?? process.resourcesPath;
+const assetsDir = app.isPackaged ? join(gameRoot, 'assets') : join(app.getAppPath(), 'assets');
+/** Version of this game code (its own package.json, not the installer's). */
+const gameVersion = (JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf8')) as { version: string }).version;
 process.env.GOUTER_ASSETS = assetsDir;
 
 let server: UtilityProcess | null = null;
@@ -84,8 +89,36 @@ ipcMain.handle('assets:map', (_event, mapId: string): MapFiles => {
   return { definition, terrain, background: readMapImage(dir, mapId, 'background.png') };
 });
 
+// Self-update: only for the packaged app; GOUTER_UPDATE_REPO points it at another server (tests).
+let updateStatus: UpdateStatus = { state: 'idle' };
+function setUpdateStatus(status: UpdateStatus): void {
+  updateStatus = status;
+  for (const win of BrowserWindow.getAllWindows()) win.webContents.send('updates:status', status);
+}
+function startUpdater(): void {
+  if (!app.isPackaged || process.env.GOUTER_NO_UPDATE) return;
+  setTimeout(() => {
+    void checkForUpdate({
+      repoUrl: process.env.GOUTER_UPDATE_REPO ?? UPDATE_REPO_URL,
+      current: gameVersion,
+      gamesDir: join(app.getPath('userData'), 'game'),
+      runningRoot: gameRoot,
+      onStatus: setUpdateStatus,
+    });
+  }, UPDATE_CHECK_DELAY_MS);
+}
+ipcMain.handle('updates:version', () => gameVersion);
+ipcMain.handle('updates:status', () => updateStatus);
+ipcMain.handle('updates:restart', () => {
+  // The portable exe unpacks itself to a temp folder: relaunch the exe the player clicked.
+  const portable = process.env.PORTABLE_EXECUTABLE_FILE;
+  app.relaunch(portable ? { execPath: portable } : undefined);
+  app.exit(0);
+});
+
 void app.whenReady().then(() => {
   createWindow();
+  startUpdater();
   app.on('activate', () => {
     if (BrowserWindow.getAllWindows().length === 0) createWindow();
   });

+ 111 - 0
src/main/updater.ts

@@ -0,0 +1,111 @@
+// Self-update of the packaged game (readme §2). Looks at the builds published in the git
+// repository, downloads the newest one into userData/game/<version>/ and points
+// userData/game/current.json at it. boot.ts runs it on the next launch; the Electron runtime
+// that came with the installer stays as is.
+import { createHash } from 'node:crypto';
+import { join } from 'node:path';
+import { net } from 'electron';
+// original-fs: plain fs, without Electron's asar handling (we write files named app.asar).
+import * as fs from 'original-fs';
+import type { UpdateStatus } from '../preload/api';
+import { CURRENT_FILE, MANIFEST_FILE, newestBuild, parseAdvertisedRefs, parseManifest, rawFileUrl, sameElectronMajor, type ManifestFile } from './updates';
+
+export interface UpdaterOptions {
+  repoUrl: string;
+  /** Version of the game running now. */
+  current: string;
+  /** userData/game: one folder per downloaded version. */
+  gamesDir: string;
+  /** Folder of the running game (app.asar, assets/...): files that did not change are copied from it. */
+  runningRoot: string;
+  onStatus(status: UpdateStatus): void;
+}
+
+async function fetchOk(url: string): Promise<Response> {
+  const res = await net.fetch(url, { headers: { 'Cache-Control': 'no-cache' } });
+  if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
+  return res;
+}
+
+function sha256(data: Uint8Array): string {
+  return createHash('sha256').update(data).digest('hex');
+}
+
+/** The file of the running game when it is byte-identical to the one wanted, else null. */
+function reusable(runningRoot: string, file: ManifestFile): Buffer | null {
+  try {
+    const path = join(runningRoot, ...file.path.split('/'));
+    if (fs.statSync(path).size !== file.size) return null;
+    const data = fs.readFileSync(path);
+    return sha256(data) === file.sha256 ? data : null;
+  } catch {
+    return null;
+  }
+}
+
+/** Checks for a newer build and downloads it. Never throws: failures are reported as a status. */
+export async function checkForUpdate(opts: UpdaterOptions): Promise<void> {
+  try {
+    fs.mkdirSync(opts.gamesDir, { recursive: true });
+    const refs = parseAdvertisedRefs(await (await fetchOk(`${opts.repoUrl}.git/info/refs?service=git-upload-pack`)).text());
+    const build = newestBuild(refs, opts.current);
+    if (!build) return;
+    const target = join(opts.gamesDir, build.version);
+    if (fs.existsSync(join(target, MANIFEST_FILE))) {
+      // Already downloaded by an earlier launch.
+      writeCurrent(opts.gamesDir, build.version);
+      opts.onStatus({ state: 'ready', version: build.version });
+      return;
+    }
+
+    const manifest = parseManifest(await (await fetchOk(rawFileUrl(opts.repoUrl, build.sha, MANIFEST_FILE))).json(), build.version);
+    if (!sameElectronMajor(manifest.electron, process.versions.electron)) {
+      opts.onStatus({ state: 'manual', version: build.version });
+      return;
+    }
+
+    const partial = `${target}.part`;
+    fs.rmSync(partial, { recursive: true, force: true });
+    const total = manifest.files.reduce((sum, f) => sum + f.size, 0) || 1;
+    let done = 0;
+    opts.onStatus({ state: 'downloading', version: build.version, progress: 0 });
+    for (const file of manifest.files) {
+      let data = reusable(opts.runningRoot, file);
+      if (!data) {
+        data = Buffer.from(await (await fetchOk(rawFileUrl(opts.repoUrl, build.sha, file.path))).arrayBuffer());
+        if (data.length !== file.size || sha256(data) !== file.sha256) throw new Error(`${file.path} is corrupted`);
+      }
+      const path = join(partial, ...file.path.split('/'));
+      fs.mkdirSync(join(path, '..'), { recursive: true });
+      fs.writeFileSync(path, data);
+      done += file.size;
+      opts.onStatus({ state: 'downloading', version: build.version, progress: done / total });
+    }
+    // The manifest goes last: its presence marks a complete download.
+    fs.writeFileSync(join(partial, MANIFEST_FILE), JSON.stringify(manifest));
+    fs.rmSync(target, { recursive: true, force: true });
+    fs.renameSync(partial, target);
+    writeCurrent(opts.gamesDir, build.version);
+    removeOldVersions(opts.gamesDir, [build.version, opts.current]);
+    opts.onStatus({ state: 'ready', version: build.version });
+  } catch (err) {
+    console.error('[update]', err);
+    opts.onStatus({ state: 'error', message: err instanceof Error ? err.message : String(err) });
+  }
+}
+
+function writeCurrent(gamesDir: string, version: string): void {
+  fs.writeFileSync(join(gamesDir, CURRENT_FILE), JSON.stringify({ version }));
+}
+
+/** Deletes downloaded versions other than `keep` (the running one may be in use). */
+function removeOldVersions(gamesDir: string, keep: string[]): void {
+  for (const entry of fs.readdirSync(gamesDir, { withFileTypes: true })) {
+    if (!entry.isDirectory() || keep.includes(entry.name)) continue;
+    try {
+      fs.rmSync(join(gamesDir, entry.name), { recursive: true, force: true });
+    } catch {
+      // A folder still locked by another running instance: removed on a later update.
+    }
+  }
+}

+ 95 - 0
src/main/updates.ts

@@ -0,0 +1,95 @@
+// Pure helpers for self-updates (no Electron, no fs): parsing what the git server advertises
+// and the manifest of a published build. Tested in tests/updates.test.ts.
+//
+// A release is a tag `vX.Y.Z` on the source plus a parentless commit at `refs/builds/vX.Y.Z`
+// holding the game files (app.asar, its unpacked natives, assets/) and a manifest.json.
+// Clones never fetch refs/builds/*, so the builds don't weigh on the source history.
+
+export const BUILD_REF_PREFIX = 'refs/builds/v';
+export const MANIFEST_FILE = 'manifest.json';
+/** userData/game/current.json: the downloaded version boot.ts should run. */
+export const CURRENT_FILE = 'current.json';
+
+export interface ManifestFile {
+  /** Relative path with forward slashes, e.g. "assets/maps/roule/map.json". */
+  path: string;
+  size: number;
+  sha256: string;
+}
+
+export interface BuildManifest {
+  version: string;
+  /** Electron version the build was made with: a different one needs a new installer. */
+  electron: string;
+  files: ManifestFile[];
+}
+
+const VERSION_RE = /^(\d+)\.(\d+)\.(\d+)$/;
+
+export function isVersion(v: string): boolean {
+  return VERSION_RE.test(v);
+}
+
+/** Compares two x.y.z versions: negative if a < b, 0 if equal, positive if a > b. */
+export function compareVersions(a: string, b: string): number {
+  const pa = VERSION_RE.exec(a);
+  const pb = VERSION_RE.exec(b);
+  if (!pa || !pb) throw new Error(`not a version: ${pa ? b : a}`);
+  for (let i = 1; i <= 3; i++) {
+    const d = Number(pa[i]) - Number(pb[i]);
+    if (d !== 0) return d;
+  }
+  return 0;
+}
+
+/** Refs advertised by `GET <repo>.git/info/refs?service=git-upload-pack`, as name -> commit sha. */
+export function parseAdvertisedRefs(body: string): Map<string, string> {
+  const refs = new Map<string, string>();
+  // Each pkt-line is "<4 hex length><sha> <ref>[\0capabilities]\n"; the length prefix is glued to the sha.
+  for (const m of body.matchAll(/([0-9a-f]{40}) (refs\/[^\0\n]+)/g)) refs.set(m[2], m[1]);
+  return refs;
+}
+
+/** The newest published build strictly newer than `current`, if any. */
+export function newestBuild(refs: Map<string, string>, current: string): { version: string; sha: string } | null {
+  let best: { version: string; sha: string } | null = null;
+  for (const [ref, sha] of refs) {
+    if (!ref.startsWith(BUILD_REF_PREFIX)) continue;
+    const version = ref.slice(BUILD_REF_PREFIX.length);
+    if (!isVersion(version) || compareVersions(version, current) <= 0) continue;
+    if (!best || compareVersions(version, best.version) > 0) best = { version, sha };
+  }
+  return best;
+}
+
+/** A manifest path must stay inside the game folder. */
+function isSafePath(path: string): boolean {
+  if (!path || path.startsWith('/') || path.includes('\\') || path.includes(':')) return false;
+  return path.split('/').every((part) => part !== '' && part !== '.' && part !== '..');
+}
+
+/** Validates a downloaded manifest; throws with an explicit message when it is unusable. */
+export function parseManifest(raw: unknown, expectedVersion: string): BuildManifest {
+  const m = raw as Partial<BuildManifest> | null;
+  if (!m || typeof m !== 'object') throw new Error('manifest is not an object');
+  if (m.version !== expectedVersion) throw new Error(`manifest is for ${String(m.version)}, expected ${expectedVersion}`);
+  if (typeof m.electron !== 'string') throw new Error('manifest has no electron version');
+  if (!Array.isArray(m.files) || m.files.length === 0) throw new Error('manifest lists no file');
+  for (const f of m.files) {
+    if (!f || typeof f.path !== 'string' || !isSafePath(f.path)) throw new Error(`unsafe path in manifest: ${String(f?.path)}`);
+    if (!Number.isInteger(f.size) || f.size < 0) throw new Error(`bad size for ${f.path}`);
+    if (typeof f.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(f.sha256)) throw new Error(`bad sha256 for ${f.path}`);
+  }
+  if (!m.files.some((f) => f.path === 'app.asar')) throw new Error('manifest has no app.asar');
+  return { version: m.version, electron: m.electron, files: m.files };
+}
+
+/** URL of a file of a published build, served raw by the git web front (Gogs, Gitea, GitLab...). */
+export function rawFileUrl(repoUrl: string, sha: string, path: string): string {
+  return `${repoUrl}/raw/${sha}/${path.split('/').map(encodeURIComponent).join('/')}`;
+}
+
+/** Electron builds with the same major version share the same native ABI and runtime APIs. */
+export function sameElectronMajor(a: string, b: string): boolean {
+  return a.split('.')[0] === b.split('.')[0];
+}

+ 20 - 0
src/preload/api.ts

@@ -41,9 +41,29 @@ export interface AssetsApi {
   map(mapId: string): Promise<MapFiles>;
 }
 
+/** Where the self-update stands (src/main/updater.ts). */
+export type UpdateStatus =
+  | { state: 'idle' }
+  | { state: 'downloading'; version: string; progress: number }
+  /** Downloaded: runs on the next launch. */
+  | { state: 'ready'; version: string }
+  /** Needs a new installer (different Electron runtime). */
+  | { state: 'manual'; version: string }
+  | { state: 'error'; message: string };
+
+export interface UpdatesApi {
+  /** Version of the running game. */
+  version(): Promise<string>;
+  /** `onStatus` receives the current status at once, then every change. Returns an unsubscribe function. */
+  watch(onStatus: (status: UpdateStatus) => void): () => void;
+  /** Restarts the app on the downloaded version. */
+  restart(): void;
+}
+
 declare global {
   interface Window {
     lan: LanApi;
     assets: AssetsApi;
+    updates: UpdatesApi;
   }
 }

+ 13 - 1
src/preload/index.ts

@@ -1,5 +1,5 @@
 import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron';
-import type { AssetsApi, LanApi, LanGame } from './api';
+import type { AssetsApi, LanApi, LanGame, UpdatesApi, UpdateStatus } from './api';
 
 const lan: LanApi = {
   host: (name) => ipcRenderer.invoke('lan:host', name),
@@ -20,5 +20,17 @@ const assets: AssetsApi = {
   map: (mapId) => ipcRenderer.invoke('assets:map', mapId),
 };
 
+const updates: UpdatesApi = {
+  version: () => ipcRenderer.invoke('updates:version'),
+  watch: (onStatus) => {
+    const listener = (_event: IpcRendererEvent, status: UpdateStatus): void => onStatus(status);
+    ipcRenderer.on('updates:status', listener);
+    void ipcRenderer.invoke('updates:status').then(onStatus);
+    return () => ipcRenderer.removeListener('updates:status', listener);
+  },
+  restart: () => void ipcRenderer.invoke('updates:restart'),
+};
+
 contextBridge.exposeInMainWorld('lan', lan);
 contextBridge.exposeInMainWorld('assets', assets);
+contextBridge.exposeInMainWorld('updates', updates);

+ 66 - 0
src/renderer/audio/Audio.ts

@@ -32,7 +32,21 @@ export type SoundName =
   | 'lick'
   | 'spell'
   | 'pounce'
+  | 'build'
+  | 'turret'
+  | 'turretDown'
+  | 'tongue'
+  | 'vanish'
+  | 'appear'
   | 'crush'
+  | 'surprise'
+  | 'rumble'
+  | 'powerDown'
+  | 'giggle'
+  | 'tick'
+  | 'stolen'
+  | 'splat'
+  | 'whizz'
   | 'thud'
   | 'beep'
   | 'go'
@@ -308,6 +322,58 @@ const SOUNDS: Record<SoundName, (s: Synth) => void> = {
     o.frequency.linearRampToValueAtTime(420, s.t0 + 0.28);
     s.noise('highpass', 3000, 3000, 0.05, 0.12, 0.2, 1, 0.01);
   },
+  build: (s) => {
+    // Squeezing the piping bag, then a little "ta-da".
+    s.noise('bandpass', 500, 900, 0, 0.3, 0.4, 3, 0.05);
+    [659, 880].forEach((f, i) => s.tone('triangle', f, f, 0.28 + i * 0.08, 0.12, 0.2));
+  },
+  turret: (s) => {
+    s.tone('sine', 900 * s.vary(), 300, 0, 0.08, 0.35);
+    s.noise('highpass', 2500, 1500, 0, 0.04, 0.25);
+  },
+  turretDown: (s) => {
+    for (let i = 0; i < 3; i++) s.noise('bandpass', 1800 * s.vary(0.3), 900, i * 0.05, 0.06, 0.5, 2);
+    s.tone('square', 500, 120, 0, 0.3, 0.1);
+  },
+  tongue: (s) => {
+    // "Shlurp!": out fast, back in.
+    s.tone('triangle', 300, 1100, 0, 0.1, 0.25, 0.01);
+    s.noise('bandpass', 1500, 600, 0.08, 0.15, 0.4, 4, 0.01);
+  },
+  vanish: (s) => {
+    for (let i = 0; i < 5; i++) s.tone('sine', 1800 - i * 260, 1500 - i * 260, i * 0.05, 0.1, 0.15);
+  },
+  appear: (s) => {
+    for (let i = 0; i < 5; i++) s.tone('sine', 700 + i * 260, 900 + i * 260, i * 0.05, 0.1, 0.15);
+  },
+  surprise: (s) => {
+    // "Tadaaa!": a rising brass-like call.
+    [392, 523, 659, 784].forEach((f, i) => s.tone('sawtooth', f, f, i * 0.09, i === 3 ? 0.5 : 0.12, 0.12));
+  },
+  rumble: (s) => {
+    s.noise('lowpass', 220, 90, 0, 2.2, 0.9, 1, 0.2);
+    s.tone('sine', 55, 40, 0, 2, 0.5, 0.2);
+  },
+  powerDown: (s) => {
+    s.tone('sawtooth', 520, 40, 0, 1.1, 0.25, 0.01);
+    s.noise('highpass', 3000, 1000, 0, 0.15, 0.3);
+  },
+  giggle: (s) => {
+    for (let i = 0; i < 4; i++) s.tone('triangle', 1300 + (i % 2) * 260, 1200, i * 0.07, 0.06, 0.18, 0.005);
+  },
+  tick: (s) => s.tone('square', 1800, 1800, 0, 0.03, 0.12, 0.002),
+  stolen: (s) => {
+    [880, 1175, 1568].forEach((f, i) => s.tone('square', f, f, i * 0.06, 0.1, 0.12));
+    s.noise('highpass', 5000, 6000, 0, 0.3, 0.15, 1, 0.02);
+  },
+  splat: (s) => {
+    s.noise('lowpass', 1400, 200, 0, 0.22, 0.9, 1, 0.003);
+    s.tone('sine', 260, 60, 0, 0.2, 0.6);
+  },
+  whizz: (s) => {
+    const o = s.tone('sine', 1500, 400, 0, 0.5, 0.18, 0.02);
+    s.wobble(o, 12, 60, 0, 0.5);
+  },
   crush: (s) => {
     s.noise('lowpass', 900, 100, 0, 0.5, 1, 1, 0.005);
     s.tone('sine', 180, 40, 0, 0.45, 0.8);

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

@@ -536,6 +536,76 @@ export const paintMagicien: Painter = (g, r, pose) => {
   stars(g, r, pose);
 };
 
+/** Tatie Douille: a pastry chef in a pink dress and apron, a tall toque, a piping bag or a rolling pin in hand. */
+export const paintTatie: Painter = (g, r, pose) => {
+  const dress = 0xff8fab;
+  const step = pose.moving && pose.grounded ? Math.sin(pose.walk) : 0;
+  foot(g, -0.35 * r - step * 0.16 * r, 0.93 * r, r, 0x8a3a5a, pose.ink);
+  body(g, 0, 0, r, r, dress, pose);
+  // Apron with a pocket.
+  g.roundRect(-0.15 * r, 0.05 * r, 0.95 * r, 0.8 * r, 0.2 * r).fill(0xfffaf0).stroke({ width: pose.ink * 0.6, color: INK });
+  g.roundRect(0.15 * r, 0.42 * r, 0.4 * r, 0.25 * r, 0.06 * r).stroke({ width: pose.ink * 0.4, color: 0xd9547a });
+  // Face, curls and the toque.
+  g.ellipse(0.25 * r, -0.25 * r, 0.6 * r, 0.48 * r).fill(0xffdcc4);
+  for (let i = 0; i < 4; i++) g.circle(-0.55 * r + i * 0.13 * r, -0.45 * r + (i % 2) * 0.08 * r, 0.14 * r).fill(0xc8643c).stroke({ width: pose.ink * 0.4, color: INK });
+  const puff = Math.sin(pose.time * 3) * 0.03 * r;
+  g.rect(-0.45 * r, -0.95 * r, 0.9 * r, 0.32 * r).fill(0xffffff).stroke({ width: pose.ink * 0.8, color: INK });
+  for (const [cx, cy, cr] of [[-0.35, -1.12, 0.3], [0.0, -1.3, 0.36], [0.35, -1.12, 0.3]]) g.circle(cx * r, cy * r + puff, cr * r).fill(0xffffff).stroke({ width: pose.ink * 0.8, color: INK });
+  g.rect(-0.43 * r, -0.97 * r, 0.86 * r, 0.14 * r).fill(0xffffff);
+  eyes(g, pose, [[0.12 * r, -0.3 * r], [0.48 * r, -0.28 * r]], 0.13 * r);
+  blush(g, 0.66 * r, -0.08 * r, 0.11 * r);
+  g.moveTo(0.3 * r, 0.0).quadraticCurveTo(0.42 * r, 0.08 * r, 0.54 * r, 0.0).stroke({ width: pose.ink * 0.6, color: INK, cap: 'round' });
+  if (pose.attack) {
+    // Rolling pin swung forward.
+    g.roundRect(0.55 * r, -0.35 * r, 0.3 * r, 1.0 * r, 0.12 * r).fill(0xe0b07a).stroke({ width: pose.ink * 0.8, color: INK });
+    for (const y of [-0.5, 0.75]) g.roundRect(0.63 * r, y * r, 0.14 * r, 0.16 * r, 0.05 * r).fill(0x9c6b3a).stroke({ width: pose.ink * 0.5, color: INK });
+  } else {
+    // Piping bag, squeezed while she builds.
+    const squeeze = pose.special ? 0.12 * r : 0;
+    g.poly([0.55 * r, -0.05 * r + squeeze, 1.05 * r, 0.25 * r, 0.6 * r, 0.5 * r - squeeze]).fill(0xfff6e4).stroke({ width: pose.ink * 0.8, color: INK, join: 'round' });
+    g.poly([1.02 * r, 0.18 * r, 1.25 * r, 0.3 * r, 1.04 * r, 0.34 * r]).fill(0xc0c8d0).stroke({ width: pose.ink * 0.5, color: INK });
+    if (pose.special) g.circle(1.3 * r, 0.36 * r, 0.12 * r).fill(0xffffff).stroke({ width: pose.ink * 0.5, color: INK });
+  }
+  foot(g, 0.35 * r + step * 0.16 * r, 0.93 * r, r, 0x8a3a5a, pose.ink);
+  stars(g, r, pose);
+};
+
+/** Léon le Caméléon: green with a spiky crest, a curled tail, one big turret eye, and a very long tongue. */
+export const paintLeon: Painter = (g, r, pose) => {
+  const green = 0x6fcf4a;
+  const dark = 0x3f9a2a;
+  const step = pose.moving && pose.grounded ? Math.sin(pose.walk) : 0;
+  // Curled tail.
+  const curl = Math.sin(pose.time * 2) * 0.05 * r;
+  g.moveTo(-0.8 * r, 0.35 * r).quadraticCurveTo(-1.45 * r, 0.3 * r, -1.35 * r, -0.15 * r + curl).stroke({ width: pose.ink * 3, color: INK, cap: 'round' });
+  g.moveTo(-0.8 * r, 0.35 * r).quadraticCurveTo(-1.45 * r, 0.3 * r, -1.35 * r, -0.15 * r + curl).stroke({ width: pose.ink * 1.8, color: green, cap: 'round' });
+  g.circle(-1.17 * r, -0.12 * r + curl, 0.16 * r).fill(green).stroke({ width: pose.ink * 0.7, color: INK });
+  foot(g, -0.35 * r - step * 0.2 * r, 0.93 * r, r, dark, pose.ink);
+  // Crest.
+  const crest: number[] = [];
+  for (let i = 0; i <= 6; i++) crest.push((-0.7 + i * 0.22) * r, (i % 2 ? -1.12 : -0.82) * r + (i === 0 || i === 6 ? 0.1 * r : 0));
+  g.poly([...crest, 0.62 * r, -0.6 * r, -0.7 * r, -0.6 * r]).fill(0xffd23f).stroke({ width: pose.ink * 0.7, color: INK, join: 'round' });
+  body(g, 0, 0, r, r, green, pose);
+  // Skin spots and a pale belly.
+  for (const [sx, sy, sr] of [[-0.45, -0.3, 0.12], [-0.6, 0.2, 0.09], [-0.2, 0.5, 0.1], [-0.3, -0.62, 0.07]]) g.circle(sx * r, sy * r, sr * r).fill({ color: dark, alpha: 0.55 });
+  g.ellipse(0.25 * r, 0.42 * r, 0.5 * r, 0.32 * r).fill(0xd8f5b0);
+  // One big turret eye in a cone of skin.
+  g.circle(0.38 * r, -0.28 * r, 0.36 * r).fill(green).stroke({ width: pose.ink * 0.8, color: INK });
+  eyes(g, pose, [[0.42 * r, -0.28 * r]], 0.2 * r);
+  // Wide grin, and the tongue when he attacks.
+  g.moveTo(0.35 * r, 0.12 * r).quadraticCurveTo(0.7 * r, 0.22 * r, 0.95 * r, 0.05 * r).stroke({ width: pose.ink * 0.7, color: INK, cap: 'round' });
+  if (pose.attack) {
+    const len = 6.5 * r;
+    const tx = 0.9 * r + pose.lookX * len;
+    const ty = 0.1 * r + pose.lookY * len;
+    g.moveTo(0.9 * r, 0.1 * r).lineTo(tx, ty).stroke({ width: pose.ink * 2.6, color: INK, cap: 'round' });
+    g.moveTo(0.9 * r, 0.1 * r).lineTo(tx, ty).stroke({ width: pose.ink * 1.5, color: 0xff6f91, cap: 'round' });
+    g.circle(tx, ty, 0.28 * r).fill(0xff6f91).stroke({ width: pose.ink * 0.7, color: INK });
+  }
+  foot(g, 0.35 * r + step * 0.2 * r, 0.93 * r, r, dark, pose.ink);
+  stars(g, r, pose);
+};
+
 export const PAINTERS: Record<string, Painter> = {
   castor: paintCastor,
   mamie: paintMamie,
@@ -545,5 +615,7 @@ export const PAINTERS: Record<string, Painter> = {
   prout: paintProut,
   chat: paintChat,
   magicien: paintMagicien,
+  tatie: paintTatie,
+  leon: paintLeon,
   generic: paintGeneric,
 };

+ 22 - 0
src/renderer/config.ts

@@ -52,6 +52,10 @@ export const PLAYER_SPLAT_COLOR = 0xff6f91;
 export const CUSTARD_COLOR = 0xf7d774;
 export const CUSTARD_DARK = 0xd9a93a;
 export const EXPLOSION_SHAKE = 14;
+/** Explosions smaller than this (turret dragées) get a small effect: no freeze frame, little shake. */
+export const SMALL_BLAST_R = 16;
+/** Sprinkles (blast radius 9) pop without a word; bigger small blasts (dragées) get a "POC !". */
+export const SPRINKLE_POPUP_MIN_R = 9;
 export const WHISK_SHAKE = 10;
 export const FREEZE_FRAME_MS = 50;
 export const PARTICLES_PER_100_PX = 6;
@@ -64,6 +68,24 @@ export const INPUT_SEND_HZ = 60;
 export const SQUASH_RECOVERY = 10;
 /** Max forward lean (radians) of a running character. */
 export const RUN_LEAN = 0.12;
+// Cartoon hits.
+/** A stunned player flying faster than this (px/s) spins, this fast (rad/s). */
+export const SPIN_MIN_SPEED = 450;
+export const SPIN_RATE = 16;
+/** How long a player stays squashed against a wall after a splat (s). */
+export const SPLAT_SHOW_S = 0.45;
+/** A flattened player: height and width multipliers. */
+export const PANCAKE_SQUASH = 0.3;
+export const PANCAKE_STRETCH = 1.7;
+// Surprises.
+export const QUAKE_SHAKE = 7;
+export const BLACKOUT_ALPHA = 0.9;
+export const BLACKOUT_FADE_S = 0.5;
+/** The hot cherry ticks when its heat is above this (0..1). */
+export const CHERRY_TICK_HEAT = 0.5;
+/** Léon invisible: how he sees himself (alpha), and how fast he fades in and out (1/s). */
+export const INVISIBLE_SELF_ALPHA = 0.35;
+export const INVISIBLE_FADE = 8;
 /** Hue shifts (degrees) of the 2nd, 3rd... player on the same character. */
 export const VARIANT_HUES = [150, 240, 60, 300, 100, 200, 330];
 /** Resolution of the hue filter on those players (high enough to stay sharp under the dream filter). */

+ 60 - 5
src/renderer/entities/PlayerView.ts

@@ -3,7 +3,22 @@ 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, RUN_LEAN, SQUASH_RECOVERY, VARIANT_FILTER_RESOLUTION, VARIANT_HUES } from '../config';
+import {
+  INVISIBLE_FADE,
+  INVISIBLE_SELF_ALPHA,
+  OUTLINE_COLOR,
+  OUTLINE_WIDTH,
+  PLAYER_COLORS,
+  PANCAKE_SQUASH,
+  PANCAKE_STRETCH,
+  RUN_LEAN,
+  SPIN_MIN_SPEED,
+  SPIN_RATE,
+  SPLAT_SHOW_S,
+  SQUASH_RECOVERY,
+  VARIANT_FILTER_RESOLUTION,
+  VARIANT_HUES,
+} from '../config';
 
 /** Max size the fat ratio is normalized against (castor maxSize is in its JSON; this only drives the cheeks). */
 const FAT_RANGE = 26;
@@ -32,6 +47,12 @@ export class PlayerView {
   private wasGrounded = true;
   private wasStunned = false;
   private lastVy = 0;
+  /** Cartoon effects: spinning when knocked flying, squashed against a wall, flat as a pancake. */
+  private spin = 0;
+  private splatTime = 0;
+  private splatNx = 0;
+  private splatNy = 0;
+  private flat = false;
 
   constructor(readonly info: PlayerInfo) {
     this.paint = PAINTERS[info.characterId] ?? paintGeneric;
@@ -57,12 +78,23 @@ export class PlayerView {
     this.shadow.clear();
   }
 
-  update(state: PlayerState, aimX: number, aimY: number, dt: number): PlayerEvents {
+  /** `local`: this is the player at this keyboard (who still sees themself when invisible). */
+  /** Slammed into a wall or the floor: squashed flat against it for a moment. (nx, ny) points away from it. */
+  splat(nx: number, ny: number): void {
+    this.splatTime = SPLAT_SHOW_S;
+    this.splatNx = nx;
+    this.splatNy = ny;
+  }
+
+  update(state: PlayerState, aimX: number, aimY: number, dt: number, local = false): PlayerEvents {
     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;
+    // Invisible (Léon): gone for the others, a ghost for himself; fades in and out.
+    const alpha = state.anim & Anim.Invisible ? (local ? INVISIBLE_SELF_ALPHA : 0) : 1;
+    this.container.alpha += (alpha - this.container.alpha) * Math.min(1, INVISIBLE_FADE * dt);
     this.held.clear();
     if (state.item) {
       paintItem(this.held, state.item, false, this.time);
@@ -95,7 +127,13 @@ export class PlayerView {
     const dy = aimY - state.y;
     const len = Math.hypot(dx, dy) || 1;
     // Leans into the run.
-    this.body.rotation = Math.max(-RUN_LEAN, Math.min(RUN_LEAN, (state.vx / 600) * RUN_LEAN));
+    this.splatTime = Math.max(0, this.splatTime - dt);
+    this.flat = (state.anim & Anim.Flat) !== 0;
+    // Knocked flying: the body spins like in a cartoon; otherwise it leans into the run.
+    const speed = Math.hypot(state.vx, state.vy);
+    if (stunned && speed > SPIN_MIN_SPEED && this.splatTime === 0 && !this.flat) this.spin += dt * SPIN_RATE * Math.sign(state.vx || 1);
+    else this.spin = 0;
+    this.body.rotation = this.spin !== 0 ? this.spin : Math.max(-RUN_LEAN, Math.min(RUN_LEAN, (state.vx / 600) * RUN_LEAN));
     this.shadow.clear();
     if (state.grounded) this.shadow.ellipse(0, size * 0.98, size * 0.85, size * 0.18).fill({ color: OUTLINE_COLOR, alpha: 0.18 });
     this.draw(size, state.facing, dx / len, dy / len, {
@@ -131,9 +169,26 @@ export class PlayerView {
     const sy = 1 - this.squash;
     // Wobble while eating.
     const wobble = flags.special ? 1 + Math.sin(this.time * 28) * 0.04 : 1;
-    this.body.scale.set(facing * scale * sx * wobble, scale * sy / wobble);
+    let kx = sx * wobble;
+    let ky = sy / wobble;
+    this.body.x = 0;
+    if (this.flat) {
+      // A pancake: flat on the ground.
+      kx = PANCAKE_STRETCH;
+      ky = PANCAKE_SQUASH;
+    } else if (this.splatTime > 0) {
+      // Squashed against what it hit, stuck to it.
+      const k = this.splatTime / SPLAT_SHOW_S;
+      const wall = Math.abs(this.splatNx) > Math.abs(this.splatNy);
+      const flatten = 1 - 0.6 * k;
+      const widen = 1 + 0.5 * k;
+      kx = wall ? flatten : widen;
+      ky = wall ? widen : flatten;
+      if (wall) this.body.x = -this.splatNx * size * (1 - flatten);
+    }
+    this.body.scale.set(facing * scale * kx, scale * ky);
     // Keep the feet on the ground while squashed.
-    this.body.y = size * (1 - sy);
+    this.body.y = size * (1 - ky);
     this.body.clear();
     this.paint(this.body, base, {
       time: this.time,

+ 80 - 11
src/renderer/entities/RoundViews.ts

@@ -1,6 +1,6 @@
 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';
+import type { CherryState, EntityKind, ItemState, PlayerState, TurretState } from '../../shared/protocol';
+import { CUSTARD_COLOR, CUSTARD_DARK, OUTLINE_COLOR, OUTLINE_WIDTH, PLAYER_COLORS } from '../config';
 
 const INK = OUTLINE_COLOR;
 const W = OUTLINE_WIDTH;
@@ -43,25 +43,65 @@ export class CherryView {
   readonly graphics = new Graphics();
   private time = 0;
 
-  update(cherry: CherryState | null, dt: number): void {
+  /** The cherry is alive: it looks at the nearest player, and as a hot potato it glows and shakes. */
+  update(cherry: CherryState | null, dt: number, players: Map<number, PlayerState>): void {
     this.time += dt;
     const g = this.graphics;
     g.clear();
     if (!cherry) return;
+    const heat = cherry.heat;
     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 });
+    // About to blow: it trembles harder and harder.
+    const tremble = heat > 0.5 ? (heat - 0.5) * 2 * 4 : 0;
+    const x = cherry.x + Math.sin(this.time * 70) * tremble;
+    const y = cherry.y + bob + Math.cos(this.time * 63) * tremble * 0.6;
+    if (cherry.holder) g.circle(x, y, 22 + Math.sin(this.time * 8) * 2).fill({ color: heat > 0.5 ? 0xff6f2e : 0xffe14d, alpha: 0.35 + heat * 0.2 });
     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.circle(x, y, 12).fill(mixColor(0xe0123a, 0xff8a1e, heat)).stroke({ width: W, color: INK });
     g.ellipse(x - 4, y - 4, 4, 3).fill({ color: 0xffffff, alpha: 0.75 });
+    // Eyes on the nearest player (the holder if held: looking up at them would be odd, so ahead).
+    let lx = 0;
+    let ly = 0;
+    let best = Infinity;
+    for (const p of players.values()) {
+      if (p.id === cherry.holder) continue;
+      const d = Math.hypot(p.x - cherry.x, p.y - cherry.y);
+      if (d < best) {
+        best = d;
+        lx = (p.x - cherry.x) / (d || 1);
+        ly = (p.y - cherry.y) / (d || 1);
+      }
+    }
+    const scared = best < 140 || heat > 0.6;
+    for (const side of [-1, 1]) {
+      const ex = x + side * 4.5;
+      const ey = y + 1;
+      g.ellipse(ex, ey, 3.6, scared ? 4.8 : 4).fill(0xffffff).stroke({ width: 1.2, color: INK });
+      g.circle(ex + lx * 1.4, ey + ly * 1.6, scared ? 1.3 : 1.9).fill(INK);
+    }
+    if (scared) g.ellipse(x, y + 7, 2.2, 2.6).fill(INK);
+    else g.moveTo(x - 3, y + 6).quadraticCurveTo(x, y + 8.5, x + 3, y + 6).stroke({ width: 1.3, color: INK, cap: 'round' });
   }
 }
 
-/** 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') {
+function mixColor(a: number, b: number, t: number): number {
+  const k = Math.max(0, Math.min(1, t));
+  const ch = (s: number): number => Math.round(((a >> s) & 0xff) * (1 - k) + ((b >> s) & 0xff) * k);
+  return (ch(16) << 16) | (ch(8) << 8) | ch(0);
+}
+
+const SPRINKLE_COLORS = [0xff3b6b, 0xffe14d, 0x4dc4ff, 0x9be15d, 0xb18cff, 0xffffff];
+
+/** Draws one item in local coordinates (origin at its center). `seed` varies the look (sprinkle colors). */
+export function paintItem(g: Graphics, kind: EntityKind, lit: boolean, time: number, seed = 0): void {
+  if (kind === 'sprinkle') {
+    g.roundRect(-6, -2, 12, 4, 2).fill(SPRINKLE_COLORS[seed % SPRINKLE_COLORS.length]).stroke({ width: 1.2, color: INK });
+  } else if (kind === 'dragee') {
+    // A sugared almond, pastel and shiny.
+    g.ellipse(0, 0, 8, 6).fill(0xffb3d1).stroke({ width: 2, color: INK });
+    g.ellipse(-2.5, -2, 3, 1.5).fill({ color: 0xffffff, alpha: 0.8 });
+  } else 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 });
@@ -135,7 +175,7 @@ export class ItemsView {
       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);
+      paintItem(g, item.kind, item.lit, this.time, id);
       g.position.set(item.x, item.y);
       g.rotation = item.angle;
     }
@@ -178,6 +218,35 @@ export class CloudsView {
   }
 }
 
+/** Tatie's turrets: a choux head with a piping nozzle aimed at its target, and its owner's pennant. */
+export class TurretsView {
+  readonly graphics = new Graphics();
+  private time = 0;
+
+  update(turrets: TurretState[], dt: number): void {
+    this.time += dt;
+    const g = this.graphics;
+    g.clear();
+    for (const t of turrets) {
+      const c = Math.cos(t.angle);
+      const s = Math.sin(t.angle);
+      const px = -s;
+      const py = c;
+      // Nozzle: a silver cone along the aim.
+      g.poly([t.x + px * 5, t.y + py * 5, t.x + c * 22 + px * 2.5, t.y + s * 22 + py * 2.5, t.x + c * 22 - px * 2.5, t.y + s * 22 - py * 2.5, t.x - px * 5, t.y - py * 5])
+        .fill(0xc0c8d0)
+        .stroke({ width: 2, color: INK, join: 'round' });
+      // Choux head with a cream swirl, and the owner's little flag.
+      g.circle(t.x, t.y, 10).fill(0xe0a050).stroke({ width: 2.5, color: INK });
+      g.ellipse(t.x - 3, t.y - 4, 4, 2).fill({ color: 0xffffff, alpha: 0.45 });
+      g.circle(t.x, t.y - 8, 4.5).fill(0xffffff).stroke({ width: 1.5, color: INK });
+      const wave = Math.sin(this.time * 6 + t.id) * 2;
+      g.moveTo(t.x - 6, t.y - 9).lineTo(t.x - 6, t.y - 26).stroke({ width: 1.5, color: INK });
+      g.poly([t.x - 6, t.y - 26, t.x + 6, t.y - 22 + wave, t.x - 6, t.y - 18]).fill(PLAYER_COLORS[(t.owner - 1) % PLAYER_COLORS.length]).stroke({ width: 1.2, color: INK });
+    }
+  }
+}
+
 export class SpoonsView {
   readonly container = new Container();
   private spoons: Spoon[] = [];

+ 139 - 0
src/renderer/fx/Surprises.ts

@@ -0,0 +1,139 @@
+import { Graphics } from 'pixi.js';
+import { Anim } from '../../shared/characters';
+import { CAT_PAW_RADIUS, HAND_BITE_RADIUS } from '../../shared/constants';
+import type { CherryState, FxEvent, PlayerState, SurpriseId } from '../../shared/protocol';
+import { BLACKOUT_ALPHA, BLACKOUT_FADE_S, OUTLINE_COLOR, QUAKE_SHAKE } from '../config';
+import { fr } from '../i18n/fr';
+
+const INK = OUTLINE_COLOR;
+
+type SurpriseEvent = Extract<FxEvent, { kind: 'surprise' }>;
+
+interface Running {
+  ev: SurpriseEvent;
+  /** performance.now() when it started: the real clock, so a slow frame rate does not stretch it. */
+  start: number;
+  t: number;
+}
+
+/**
+ * Draws the surprise events (server/surprises) in the world: the cat's paw, the child's hand,
+ * the blackout with glowing eyes; and announces them with a big banner.
+ */
+export class SurpriseView {
+  /** Above the players: the paw and the hand pass in front of everything, so does the dark. */
+  readonly graphics = new Graphics();
+  private readonly banner = document.createElement('div');
+  private running: Running[] = [];
+  private bannerTimer: ReturnType<typeof setTimeout> | null = null;
+
+  constructor() {
+    this.banner.id = 'surprise-banner';
+    this.banner.hidden = true;
+    document.body.appendChild(this.banner);
+  }
+
+  start(ev: SurpriseEvent): void {
+    this.running.push({ ev, start: performance.now(), t: 0 });
+    this.banner.textContent = fr.surprises[ev.surprise] ?? ev.surprise;
+    this.banner.hidden = false;
+    // Restart the CSS pop animation.
+    this.banner.classList.remove('pop');
+    void this.banner.offsetWidth;
+    this.banner.classList.add('pop');
+    if (this.bannerTimer) clearTimeout(this.bannerTimer);
+    this.bannerTimer = setTimeout(() => (this.banner.hidden = true), 2600);
+  }
+
+  /** True while a surprise of this kind is going on. */
+  active(id: SurpriseId): boolean {
+    return this.running.some((r) => r.ev.surprise === id);
+  }
+
+  /** Extra screen shake wanted this frame. */
+  get shake(): number {
+    return this.active('quake') ? QUAKE_SHAKE : 0;
+  }
+
+  clear(): void {
+    this.running = [];
+    this.graphics.clear();
+    this.banner.hidden = true;
+  }
+
+  update(width: number, height: number, players: Map<number, PlayerState>, cherry: CherryState | null, localId: number): void {
+    const g = this.graphics;
+    g.clear();
+    const now = performance.now();
+    for (const r of this.running) r.t = (now - r.start) / 1000;
+    this.running = this.running.filter((r) => r.t < r.ev.duration);
+    for (const r of this.running) {
+      const { ev, t } = r;
+      if (ev.surprise === 'cat-paw') this.paw(g, ev, t, width);
+      else if (ev.surprise === 'giant-hand') this.hand(g, ev, t);
+      else if (ev.surprise === 'blackout') this.blackout(g, ev, t, width, height, players, cherry, localId);
+    }
+  }
+
+  /** A huge ginger paw with pink toe beans, its arm reaching in from the side of the screen. */
+  private paw(g: Graphics, ev: SurpriseEvent, t: number, width: number): void {
+    const fromLeft = ev.x < 0;
+    const x1 = fromLeft ? width + CAT_PAW_RADIUS : -CAT_PAW_RADIUS;
+    const x = ev.x + (x1 - ev.x) * Math.min(1, t / ev.duration);
+    const y = ev.y;
+    const r = CAT_PAW_RADIUS * 1.25;
+    const armEnd = fromLeft ? x - 3000 : x + 3000;
+    g.rect(Math.min(x, armEnd), y - r * 0.7, Math.abs(armEnd - x), r * 1.4).fill(0xff9a2e).stroke({ width: 5, color: INK });
+    for (let i = -2; i <= 2; i++) g.moveTo(x - (fromLeft ? 1 : -1) * (r + 40 + i * 70), y - r * 0.6).lineTo(x - (fromLeft ? 1 : -1) * (r + 60 + i * 70), y + r * 0.6).stroke({ width: 6, color: 0xd9741a });
+    g.circle(x, y, r).fill(0xff9a2e).stroke({ width: 5, color: INK });
+    const dir = fromLeft ? 1 : -1;
+    g.ellipse(x + dir * r * 0.2, y + r * 0.15, r * 0.42, r * 0.36).fill(0xffb6c8).stroke({ width: 3, color: INK });
+    for (const [a, s] of [[-0.9, 0.2], [-0.3, 0.22], [0.3, 0.22], [0.9, 0.2]]) {
+      g.circle(x + dir * Math.cos(a) * r * 0.62, y + Math.sin(a) * r * 0.62 - r * 0.15, r * s).fill(0xffb6c8).stroke({ width: 3, color: INK });
+    }
+  }
+
+  /** The child's hand: a shadow grows where it will grab, it comes down, closes, and goes back up. */
+  private hand(g: Graphics, ev: SurpriseEvent, t: number): void {
+    const half = ev.duration / 2;
+    const k = t < half ? t / half : 1 - (t - half) / half;
+    g.ellipse(ev.x, ev.y, HAND_BITE_RADIUS * (0.4 + 0.8 * Math.min(1, t / half)), HAND_BITE_RADIUS * 0.25).fill({ color: INK, alpha: 0.25 });
+    const y = -400 + (ev.y - 60 + 400) * k * k;
+    const closed = t >= half;
+    const palm = 0xffc8a8;
+    const fingers = closed ? 0.5 : 1;
+    for (let i = 0; i < 4; i++) {
+      const fx = ev.x - 54 + i * 36;
+      g.roundRect(fx - 15, y + 30, 30, 70 * fingers, 15).fill(palm).stroke({ width: 5, color: INK });
+    }
+    g.roundRect(ev.x - 75, y - 400, 150, 440, 50).fill(palm).stroke({ width: 5, color: INK });
+    g.roundRect(ev.x + 62, y - 30, 26, 70 * fingers, 13).fill(palm).stroke({ width: 5, color: INK });
+    g.ellipse(ev.x - 20, y - 60, 30, 14).fill({ color: 0xffffff, alpha: 0.25 });
+  }
+
+  /** The lights go out: only the eyes (and the cherry) still glow. */
+  private blackout(
+    g: Graphics,
+    ev: SurpriseEvent,
+    t: number,
+    width: number,
+    height: number,
+    players: Map<number, PlayerState>,
+    cherry: CherryState | null,
+    localId: number,
+  ): void {
+    const fade = Math.min(1, t / BLACKOUT_FADE_S, (ev.duration - t) / BLACKOUT_FADE_S);
+    g.rect(-2000, -2000, width + 4000, height + 4000).fill({ color: 0x0a0820, alpha: BLACKOUT_ALPHA * fade });
+    for (const p of players.values()) {
+      if (p.anim & Anim.Dead || (p.anim & Anim.Invisible && p.id !== localId)) continue;
+      const blink = Math.sin(t * 3 + p.id * 1.7) > 0.96;
+      for (const side of [-1, 1]) {
+        const ex = p.x + p.facing * p.size * 0.3 + side * p.size * 0.2;
+        const ey = p.y - p.size * 0.25;
+        g.ellipse(ex, ey, p.size * 0.22, p.size * 0.22).fill({ color: 0xfff3a0, alpha: 0.25 * fade });
+        g.ellipse(ex, ey, p.size * 0.1, blink ? 1 : p.size * 0.13).fill({ color: 0xfff3a0, alpha: fade });
+      }
+    }
+    if (cherry) g.circle(cherry.x, cherry.y, 22).fill({ color: 0xff3b6b, alpha: 0.3 * fade });
+  }
+}

+ 42 - 1
src/renderer/i18n/fr.ts

@@ -22,6 +22,8 @@ export const fr = {
     pompier: 'Q/D : courir · Espace/Z : sauter · Clic gauche : jet d’eau · Clic droit : détremper · F : lancer la bougie · K : abandonner',
     prout: 'Q/D : courir · Espace/Z : sauter · Clic gauche : coup de cape · Clic droit : propulsion · F : lancer la bougie · K : abandonner',
     chat: 'Q/D : courir · Espace/Z : sauter · Clic gauche : coup de patte · Clic droit : bondir griffes en avant · F : lancer la bougie · K : abandonner',
+    tatie: 'Q/D : courir · Espace/Z : sauter · Clic gauche : rouleau à pâtisserie · Clic droit : poser une tourelle · F : lancer la bougie · K : abandonner',
+    leon: 'Q/D : courir · Espace/Z : sauter · Clic gauche : langue · Clic droit : devenir invisible · F : lancer la bougie · K : abandonner',
     magicien: 'Q/D : courir · Espace/Z : sauter · Clic gauche : baguette · Clic droit : lancer un sort · F : lancer la bougie · K : abandonner',
   } as Record<string, string>,
   fps: (n: number) => `${n} FPS`,
@@ -63,6 +65,13 @@ export const fr = {
     imposed: (leader: string, character: string) => `${leader} jouera ${character} !`,
   },
   stopped: 'L’hôte a arrêté la partie : retour à l’échauffement.',
+  updates: {
+    version: (v: string) => `v${v}`,
+    downloading: (v: string, percent: number) => `Nouvelle version ${v} : téléchargement… ${percent} %`,
+    ready: (v: string) => `Version ${v} prête !`,
+    restart: 'Relancer',
+    manual: (v: string) => `Version ${v} disponible : il faut réinstaller le jeu.`,
+  },
   options: {
     title: 'Options',
     master: 'Volume général',
@@ -70,7 +79,7 @@ export const fr = {
     sfx: 'Bruitages',
     mute: 'Couper le son',
     shake: 'Secousses de l’écran',
-    keys: 'Échap : options · K : abandonner quand tu es coincé (retour par la cuillère)',
+    keys: 'Échap : options · K : abandonner quand tu es coincé (retour par la cuillère) · Contre un mur, saute pour rebondir dessus et grimper (garde la direction du mur)',
     stop: 'Arrêter la partie',
     stopConfirm: 'Arrêter la partie pour tout le monde et revenir à l’échauffement ?',
     quit: 'Retour au menu',
@@ -95,7 +104,25 @@ export const fr = {
     lick: ['SLURP…', 'LAP LAP…', 'RONRON…'],
     pounce: ['MRAOU !', 'FFFT !', 'GRIFFE !'],
     backfire: ['AÏE !', 'OUILLE !', 'OUPS !'],
+    build: ['ET HOP !', 'TADAM !', 'VOILÀ !'],
+    turretDown: ['CRAC !', 'PATATRAS !'],
+    pop: ['POC !', 'TOC !', 'PAF !'],
+    hop: ['HIHI !', 'ATTRAPE-MOI !', 'NIAK NIAK !', 'PAS PAR LÀ !'],
+    hot: ['PATATE CHAUDE !', 'KABOUM CERISE !'],
+    splat: ['SPLAF !', 'FLATCH !', 'SPROTCH !'],
+    whizz: ['WIIIZZ !', 'WOUUUSH !'],
+    pancake: ['CRÊPE !', 'GALETTE !', 'APLATI !'],
+    vanish: ['POUF !', 'OÙ ÇA ?', 'COUCOU…'],
   },
+  /** Surprise events, announced in big letters. */
+  surprises: {
+    'cat-paw': 'Le chat de la maison passe !',
+    quake: 'Tremblement de table !',
+    sprinkles: 'Pluie de vermicelles !',
+    'giant-hand': 'L’enfant a faim !',
+    blackout: 'Panne de courant !',
+  } as Record<string, string>,
+  stolen: (bonus: number) => [`VOLÉ ! +${bonus}`],
   spells: {
     jelly: 'Gélifico !',
     swap: 'Échangeus !',
@@ -181,6 +208,20 @@ export const fr = {
       special: 'Sort au hasard : gelée, échange, lapin géant ou « pfft »',
       flaw: 'Plus il mène, plus ses sorts ratent',
     },
+    tatie: {
+      name: 'Tatie Douille',
+      desc: 'Pâtissière : elle garnit le gâteau de tourelles.',
+      attack: 'Coup de rouleau à pâtisserie',
+      special: 'Pose une tourelle en biscuit qui tire des dragées sur les autres (2 au plus)',
+      flaw: 'Reste plantée le temps de la poser, et la tourelle tombe avec le gâteau dessous',
+    },
+    leon: {
+      name: 'Léon le Caméléon',
+      desc: 'Personne ne le voit venir.',
+      attack: 'Grande langue : creuse un sillon et ramène ce qu’elle attrape',
+      special: 'Devient invisible pour les autres pendant 5 s',
+      flaw: 'Attaquer ou être touché le fait réapparaître, et la cerise flotte au-dessus de lui',
+    },
     random: {
       name: 'Au hasard',
       desc: 'Un gourmand tiré au sort, différent à chaque manche.',

+ 89 - 5
src/renderer/main.ts

@@ -30,13 +30,18 @@ import {
   SHAKE_DECAY,
   SHAKE_MAX,
   SHAKE_PER_PIXEL,
+  SMALL_BLAST_R,
+  SPIN_MIN_SPEED,
+  SPRINKLE_POPUP_MIN_R,
+  CHERRY_TICK_HEAT,
   WHISK_SHAKE,
 } from './config';
 import { GameAudio, type SoundName } from './audio/Audio';
 import { ChunkView } from './entities/ChunkView';
 import { PlayerView } from './entities/PlayerView';
-import { CherryView, CloudsView, CustardView, ItemsView, SpoonsView } from './entities/RoundViews';
+import { CherryView, CloudsView, CustardView, ItemsView, SpoonsView, TurretsView } from './entities/RoundViews';
 import { makeDreamFilter, setDreamPoison, SugarDust } from './fx/Dream';
+import { SurpriseView } from './fx/Surprises';
 import { Particles } from './fx/Particles';
 import { Popups } from './fx/Popups';
 import { fr } from './i18n/fr';
@@ -49,6 +54,7 @@ import { ResultsScreen, RoundHud } from './ui/hud';
 import { LobbyPanel } from './ui/lobbyPanel';
 import { showMenu, type MenuChoice } from './ui/menu';
 import { OptionsScreen } from './ui/options';
+import { mountUpdateBanner } from './ui/updateBanner';
 import { settings } from './settings';
 
 const PORTRAIT_RADIUS = 34;
@@ -144,6 +150,7 @@ async function start(): Promise<void> {
   });
   host.appendChild(app.canvas);
 
+  mountUpdateBanner();
   const audio = new GameAudio();
   const options = new OptionsScreen();
   const { choice, address, port } = await chooseGame(app, options);
@@ -169,11 +176,16 @@ async function start(): Promise<void> {
   const custardView = new CustardView();
   const spoonsView = new SpoonsView();
   const cloudsView = new CloudsView();
+  const turretsView = new TurretsView();
+  const surpriseView = new SurpriseView();
+  /** Seconds before the hot cherry's next tick. */
+  let tickIn = 0;
   // 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(
     dust.back,
     chunksLayer,
+    turretsView.graphics,
     itemsView.container,
     playersLayer,
     cherryView.graphics,
@@ -181,6 +193,7 @@ async function start(): Promise<void> {
     custardView.graphics,
     spoonsView.container,
     particles.graphics,
+    surpriseView.graphics,
     dust.front,
     popups.container,
   );
@@ -321,6 +334,7 @@ async function start(): Promise<void> {
       world.view.container.destroy({ children: true, texture: true, textureSource: true });
     }
     world = null;
+    surpriseView.clear();
     pendingEvents = [];
     pendingHash = null;
     for (const id of [...chunkViews.keys()]) removeChunk(id);
@@ -354,6 +368,26 @@ async function start(): Promise<void> {
       case 'pounce':
         popups.spawn(ev.x, ev.y - size - 16, fr.fxWords.pounce, 30);
         break;
+      case 'build':
+        particles.puff(ev.x, ev.y + size, 10, 0xfff6e4);
+        popups.spawn(ev.x, ev.y - size - 16, fr.fxWords.build, 28);
+        break;
+      case 'turret':
+        // ev is the turret's head here, not the builder.
+        particles.puff(ev.x, ev.y, 3, 0xffffff);
+        break;
+      case 'turretDown':
+        particles.burst(ev.x, ev.y, 14, 0xe0a050, 320);
+        popups.spawn(ev.x, ev.y - 20, fr.fxWords.turretDown, 26);
+        break;
+      case 'tongue':
+        break;
+      case 'vanish':
+      case 'appear':
+        // Sparkles everyone sees: a hint of where he went (or came back).
+        particles.burst(ev.x, ev.y, 12, 0x9be15d, 220);
+        if (ev.cue === 'vanish') popups.spawn(ev.x, ev.y - size - 16, fr.fxWords.vanish, 26);
+        break;
       case 'backfire':
         popups.spawn(ev.x, ev.y - size - 20, fr.fxWords.backfire, 34);
         break;
@@ -393,6 +427,14 @@ async function start(): Promise<void> {
         spoonsView.spawn(ev.x, ev.y);
         break;
       case 'explosion':
+        if (ev.r < SMALL_BLAST_R) {
+          // A turret's dragée or a sugar sprinkle: a little pop, no freeze frame.
+          audio.play('turret', ev.x, ev.y, 0.6);
+          particles.burst(ev.x, ev.y, 6, 0xffb3d1, 300);
+          if (ev.r > SPRINKLE_POPUP_MIN_R) popups.spawn(ev.x, ev.y - 16, fr.fxWords.pop, 22);
+          shake = Math.min(SHAKE_MAX, shake + HIT_SHAKE / 3);
+          break;
+        }
         audio.play('explosion', ev.x, ev.y);
         particles.burst(ev.x, ev.y, 40, 0xffb02e, 650);
         particles.burst(ev.x, ev.y, 20, 0xff6f91, 400);
@@ -413,6 +455,33 @@ async function start(): Promise<void> {
       case 'cue':
         onCue(ev);
         break;
+      case 'surprise':
+        surpriseView.start(ev);
+        audio.play('surprise');
+        if (ev.surprise === 'quake') audio.play('rumble');
+        else if (ev.surprise === 'blackout') audio.play('powerDown');
+        else if (ev.surprise === 'cat-paw') audio.play('pounce');
+        else if (ev.surprise === 'giant-hand') setTimeout(() => audio.play('crush', ev.x, ev.y), (ev.duration / 2) * 1000);
+        break;
+      case 'cherryHop':
+        audio.play('giggle', ev.x, ev.y);
+        popups.spawn(ev.x, ev.y - 26, fr.fxWords.hop, 22);
+        break;
+      case 'cherryBoom':
+        popups.spawn(ev.x, ev.y - 40, fr.fxWords.hot, 40);
+        break;
+      case 'stolen':
+        audio.play('stolen', ev.x, ev.y);
+        popups.spawn(ev.x, ev.y - 50, fr.stolen(ev.bonus), 44);
+        break;
+      case 'splat': {
+        audio.play('splat', ev.x, ev.y);
+        views.get(ev.id)?.splat(ev.nx, ev.ny);
+        popups.spawn(ev.x, ev.y - 30, fr.fxWords.splat, 36);
+        particles.burst(ev.x - ev.nx * 20, ev.y - ev.ny * 20, 10, 0xffffff, 260);
+        shake = Math.min(SHAKE_MAX, shake + HIT_SHAKE);
+        break;
+      }
       case 'whisk':
         audio.play('whisk');
         shake = Math.min(SHAKE_MAX, shake + WHISK_SHAKE);
@@ -536,8 +605,8 @@ async function start(): Promise<void> {
         removeChunk(msg.id);
         break;
       case 'crushed':
-        audio.play('crush', msg.x, msg.y);
-        popups.spawn(msg.x, msg.y, fr.onomatopoeia.crush, 46);
+        audio.play(msg.flat ? 'splat' : 'crush', msg.x, msg.y);
+        popups.spawn(msg.x, msg.y, msg.flat ? fr.fxWords.pancake : fr.onomatopoeia.crush, 46);
         particles.burst(msg.x, msg.y, 24, PLAYER_SPLAT_COLOR, 500);
         shake = Math.min(SHAKE_MAX, shake + CRUSH_SHAKE);
         freezeUntil = performance.now() + FREEZE_FRAME_MS * 2;
@@ -602,10 +671,20 @@ async function start(): Promise<void> {
       if (s) view.update(s);
     }
     itemsView.update(sample.items, dt);
-    cherryView.update(sample.round?.cherry ?? null, dt);
+    cherryView.update(sample.round?.cherry ?? null, dt, sample.players);
+    surpriseView.update(world.terrain.width, world.terrain.height, sample.players, sample.round?.cherry ?? null, localId);
+    shake = Math.max(shake, surpriseView.shake);
+    // The hot potato ticks faster and faster.
+    const heat = sample.round?.cherry?.heat ?? 0;
+    tickIn -= dt;
+    if (heat > CHERRY_TICK_HEAT && tickIn <= 0) {
+      tickIn = 0.15 + (1 - heat) * 0.9;
+      audio.play('tick', sample.round!.cherry!.x, sample.round!.cherry!.y);
+    }
     if (sample.round) custardView.update(sample.round.custardY, world.terrain.width, world.terrain.height, dt, sample.round.finalRush);
     spoonsView.update(dt);
     cloudsView.update(sample.round?.clouds ?? [], dt);
+    turretsView.update(sample.round?.turrets ?? [], dt);
     hud.update(round, rounds, sample.round, states, infos, localId);
     const [aimX, aimY] = screenToWorld(input.mouseX, input.mouseY);
     for (const [id, state] of states) {
@@ -617,7 +696,7 @@ async function start(): Promise<void> {
         views.set(id, view);
         playersLayer.addChild(view.container);
       }
-      const ev = view.update(state, id === localId ? aimX : state.x + state.facing * 100, id === localId ? aimY : state.y, dt);
+      const ev = view.update(state, id === localId ? aimX : state.x + state.facing * 100, id === localId ? aimY : state.y, dt, id === localId);
       if (ev.landed && ev.landingSpeed > LANDING_DUST_MIN_VY) {
         particles.puff(state.x, state.y + state.size, 8);
         audio.play('land', state.x, state.y, Math.min(1, ev.landingSpeed / 1200));
@@ -629,6 +708,11 @@ async function start(): Promise<void> {
       }
       if (ev.stunnedNow) {
         audio.play('hit', state.x, state.y);
+        // Sent flying: whistle away.
+        if (Math.hypot(state.vx, state.vy) > SPIN_MIN_SPEED) {
+          audio.play('whizz', state.x, state.y);
+          popups.spawn(state.x, state.y - state.size - 30, fr.fxWords.whizz, 30);
+        }
         popups.spawn(state.x, state.y - state.size, fr.onomatopoeia.hit, 40);
         particles.burst(state.x, state.y, 10, 0xffe14d, 300);
         shake = Math.min(SHAKE_MAX, shake + HIT_SHAKE);

+ 69 - 0
src/renderer/style.css

@@ -851,3 +851,72 @@ input.invalid {
 .menu-buttons #menu-options {
   margin-bottom: 4px;
 }
+
+/* Game version and self-update progress, bottom-left corner. */
+#update-banner {
+  position: fixed;
+  left: 10px;
+  bottom: 8px;
+  z-index: 50;
+  display: flex;
+  align-items: center;
+  gap: 10px;
+  font-size: 12px;
+  opacity: 0.55;
+  pointer-events: none;
+}
+#update-banner.active {
+  font-size: 15px;
+  opacity: 1;
+  padding: 6px 12px;
+  background: var(--paper);
+  border: 3px solid var(--ink);
+  border-radius: 14px;
+  pointer-events: auto;
+}
+
+/* ---------- Surprise banner ---------- */
+
+#surprise-banner {
+  position: fixed;
+  top: 22%;
+  left: 50%;
+  transform: translateX(-50%) rotate(-3deg);
+  font-size: clamp(30px, 5vw, 64px);
+  font-weight: bold;
+  color: #ffe14d;
+  -webkit-text-stroke: 3px var(--ink);
+  text-shadow: 5px 5px 0 var(--ink);
+  white-space: nowrap;
+  pointer-events: none;
+  z-index: 9;
+}
+
+#surprise-banner[hidden] {
+  display: none;
+}
+
+#surprise-banner.pop {
+  animation: surprise-pop 2.6s ease-out forwards;
+}
+
+@keyframes surprise-pop {
+  0% {
+    transform: translateX(-50%) rotate(-3deg) scale(0.2);
+    opacity: 0;
+  }
+  12% {
+    transform: translateX(-50%) rotate(2deg) scale(1.15);
+    opacity: 1;
+  }
+  20% {
+    transform: translateX(-50%) rotate(-3deg) scale(1);
+  }
+  80% {
+    opacity: 1;
+  }
+  100% {
+    transform: translateX(-50%) rotate(-3deg) scale(1.05) translateY(-20px);
+    opacity: 0;
+  }
+}

+ 34 - 0
src/renderer/ui/updateBanner.ts

@@ -0,0 +1,34 @@
+import type { UpdateStatus } from '../../preload/api';
+import { fr } from '../i18n/fr';
+
+/** Corner badge: the game version, and the self-update progress (src/main/updater.ts). */
+export function mountUpdateBanner(): void {
+  const box = document.createElement('div');
+  box.id = 'update-banner';
+  const text = document.createElement('span');
+  const restart = document.createElement('button');
+  restart.className = 'primary small';
+  restart.textContent = fr.updates.restart;
+  restart.onclick = () => window.updates.restart();
+  box.append(text, restart);
+  document.body.appendChild(box);
+
+  let version = '';
+  const render = (status: UpdateStatus): void => {
+    restart.hidden = status.state !== 'ready';
+    box.classList.toggle('active', status.state === 'downloading' || status.state === 'ready' || status.state === 'manual');
+    if (status.state === 'downloading') text.textContent = fr.updates.downloading(status.version, Math.round(status.progress * 100));
+    else if (status.state === 'ready') text.textContent = fr.updates.ready(status.version);
+    else if (status.state === 'manual') text.textContent = fr.updates.manual(status.version);
+    else text.textContent = version ? fr.updates.version(version) : '';
+  };
+  let last: UpdateStatus = { state: 'idle' };
+  void window.updates.version().then((v) => {
+    version = v;
+    render(last);
+  });
+  window.updates.watch((status) => {
+    last = status;
+    render(status);
+  });
+}

+ 381 - 23
src/server/game.ts

@@ -7,6 +7,7 @@ import {
   type CharacterContext,
   type CharacterStats,
   type ProjectileSpec,
+  type TurretSpec,
 } from '../shared/characters';
 import {
   AIR_CONTROL,
@@ -19,6 +20,23 @@ import {
   CANDLE_THROW_SPEED,
   CAKE_CHECK_INTERVAL_S,
   CHERRY_DROP_SPEED,
+  CHERRY_FLEE_COOLDOWN_S,
+  CHERRY_FLEE_HOP,
+  CHERRY_FLEE_RADIUS,
+  CHERRY_FLEE_SPEED,
+  CHERRY_HOT_BLAST,
+  CHERRY_HOT_S,
+  CHERRY_STEAL_BONUS,
+  CHERRY_STEAL_WINDOW_S,
+  CRUSH_KILL_PIXELS,
+  FLAT_S,
+  SMALL_PROJECTILE_RADIUS,
+  SPLAT_SPEED,
+  SPLAT_STUN_S,
+  SURPRISE_WEIGHTS,
+  SURPRISE_WINDOW,
+  SURPRISES_PER_ROUND,
+  CHERRY_HOLDER_JUMP_MULT,
   CHERRY_POINTS_PER_S,
   CHERRY_RADIUS,
   CHERRY_REGRAB_DELAY,
@@ -71,6 +89,10 @@ import {
   STUN_GUARD_KNOCKBACK,
   STUN_GUARD_S,
   TICK_DT,
+  WALL_JUMP_PUSH,
+  WALL_JUMP_UP,
+  WALL_NORMAL_X,
+  WALL_SLIDE_SPEED,
   WHISK_CRACK_POWER,
   WHISK_CRACK_RADIUS,
   WHISK_CRACKS,
@@ -82,7 +104,7 @@ import {
 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, EntityKind, FxEvent, ItemKind, ItemState, PlayerInfo, PlayerState, RoundState } from '../shared/protocol';
+import type { ChunkInfo, ChunkState, EntityKind, FxEvent, ItemKind, ItemState, PlayerInfo, PlayerState, RoundState, SurpriseId, TurretState } from '../shared/protocol';
 import { Rng } from '../shared/rng';
 import type { Rect, TerrainBitmap } from '../shared/terrain/bitmap';
 import { DetachFinder, type DetachedComponent } from '../shared/terrain/detach';
@@ -90,6 +112,7 @@ import { applyCells, applyTerrainEvent, rasterizeChunk, type SequencedEvent, typ
 import type { TerrainOp } from '../shared/terrain/ops';
 import { rleEncode } from '../shared/terrain/rle';
 import { MODIFIERS, type Modifier, type ModifierContext } from './modifiers';
+import { SURPRISES, type Surprise, type SurpriseContext } from './surprises';
 import { FallingChunk, type FixtureTag } from './physics/fallingChunk';
 import { TerrainColliders } from './physics/terrainColliders';
 import { MatchStats } from './stats';
@@ -122,6 +145,9 @@ interface ServerPlayer {
   facing: number;
   grounded: boolean;
   sinceGrounded: number;
+  /** Wall touched in the air: -1 on the left, 1 on the right, 0 none; and how long ago. */
+  wallSide: number;
+  sinceWall: number;
   jumpBuffer: number;
   attackCooldown: number;
   specialCooldown: number;
@@ -139,6 +165,11 @@ interface ServerPlayer {
   cough: number;
   /** Drenched by Bébé Pompier: seconds left. */
   soaked: number;
+  /** Flattened into a pancake: seconds left. */
+  flat: number;
+  /** Speed (px/s) and velocity at the end of the previous step, to notice a slam into a wall. */
+  lastVx: number;
+  lastVy: number;
   /** Raw buttons of the previous tick (the suicide key works even when stunned). */
   prevRaw: number;
   item: ItemKind | null;
@@ -186,18 +217,53 @@ const YARN_PLAYER_MARGIN = 3;
 /** Physics collision category of players (projectiles can opt out of hitting them). */
 const CATEGORY_PLAYER = 0x0002;
 
+/** A turret built by Tatie Douille (see TurretSpec). */
+interface Turret {
+  id: number;
+  owner: number;
+  spec: TurretSpec;
+  /** Head position (px). */
+  x: number;
+  y: number;
+  /** A pixel inside the base: when it is no longer solid, the turret has lost its footing. */
+  baseX: number;
+  baseY: number;
+  angle: number;
+  age: number;
+  reload: number;
+}
+
+/** A turret's base is laid in this tick's ops: its footing is only checked after this delay (s). */
+const TURRET_SETTLE_S = 0.1;
+/** A turret with nothing to shoot at looks again this often (s). */
+const TURRET_SCAN_S = 0.2;
+/** Line of sight: sample spacing (px), and the part next to the head that is not checked (px). */
+const TURRET_SIGHT_STEP = 4;
+const TURRET_SIGHT_SKIP = 14;
+/** Dragées leave from the tip of the nozzle, clear of the turret's own base (px). */
+const TURRET_MUZZLE = 26;
+
 interface Cherry {
   body: Body;
   holder: number;
   /** Player who cannot grab it back yet, and for how long. */
   blocked: number;
   blockedFor: number;
+  /** Seconds in its current holder's hands (hot potato). */
+  heldFor: number;
+  /** Seconds before it may hop away again. */
+  fleeIn: number;
+  /** Who knocked it out of whose hands, and how long the steal bonus stays open. */
+  thief: number;
+  victim: number;
+  stealFor: number;
 }
 
 export interface Crush {
   id: number;
   x: number;
   y: number;
+  flat: boolean;
 }
 
 /** What happened during one tick, for the transport to broadcast. */
@@ -247,7 +313,12 @@ export class Game {
   private readonly chunks = new Map<number, FallingChunk>();
   private nextChunkId = 1;
   /** Players hit hard enough by a chunk during the current world step. */
-  private readonly crushedThisStep = new Set<number>();
+  /** Players hit hard enough by a chunk during the current world step, with the size of the biggest one (px). */
+  private readonly crushedThisStep = new Map<number, number>();
+  /** Speed of each falling chunk before the current world step (px/s). */
+  private readonly chunkSpeedBefore = new Map<number, number>();
+  /** Pixel count of each falling chunk (small ones only flatten). */
+  private readonly chunkPixels = new Map<number, number>();
   private nextPlayerId = 1;
   private nextSpawn = 0;
 
@@ -260,10 +331,16 @@ export class Game {
   /** FX produced outside step() bookkeeping (hits, pickups), flushed into the step result. */
   private fx: FxEvent[] = [];
   private readonly modifiers: Modifier[] = [];
+  /** Round times (s since the start) of the surprises still to come, and the one going on. */
+  private surpriseAt: number[] = [];
+  private surprise: { s: Surprise; t: number } | null = null;
+  private readonly surpriseCtx: SurpriseContext;
   private readonly modifierCtx: ModifierContext;
   /** Side wind this tick (px/s²). */
   private wind = 0;
   private clouds: { x: number; y: number; r: number; life: number; maxLife: number; owner: number }[] = [];
+  private turrets: Turret[] = [];
+  private nextTurretId = 1;
   /** Recently soaked areas, which sag for a while (Bébé Pompier). */
   private soakZones: { x: number; y: number; r: number; time: number; next: number }[] = [];
   /** Seconds before the next count of the cake left. */
@@ -296,7 +373,39 @@ export class Game {
         const make = MODIFIERS[id];
         if (make) this.modifiers.push(make());
       }
+      // Surprises at random times, away from the very start and the final rush.
+      const [from, beforeEnd] = SURPRISE_WINDOW;
+      const to = this.rules.duration - beforeEnd;
+      if (to > from) for (let i = 0; i < SURPRISES_PER_ROUND; i++) this.surpriseAt.push(this.rng.range(from, to));
+      this.surpriseAt.sort((a, b) => a - b);
     }
+    this.surpriseCtx = {
+      rng: this.rng,
+      terrain: this.terrain,
+      queueOp: (op) => this.queueOp(op),
+      players: () =>
+        this.alivePlayers().map((p) => {
+          const pos = p.body.getPosition();
+          return { id: p.info.id, x: pos.x * PPM, y: pos.y * PPM, r: p.bodyRadius, grounded: p.grounded };
+        }),
+      fling: (id, vx, vy, stun) => {
+        const p = this.players.get(id);
+        if (!p || p.dead > 0) return;
+        p.body.setLinearVelocity({ x: vx / PPM, y: vy / PPM });
+        p.body.setAwake(true);
+        if (stun > 0) this.stunPlayer(p, stun);
+        if (stun > 0 && this.cherry?.holder === id) this.dropCherry(p);
+      },
+      launch: (spec, x, y, vx, vy) => this.throwEntity(spec.kind, spec, 0, x, y, vx, vy),
+      top: (x) => {
+        const cx = Math.round(x);
+        // The plate is not cake: a column whose top is the plate has nothing to grab.
+        for (let y = 0; y < Math.min(this.terrain.height, this.custardY); y++) {
+          if (this.terrain.isSolid(cx, y)) return this.terrain.get(cx, y) === MATERIAL_PLATE ? null : y;
+        }
+        return null;
+      },
+    };
     this.modifierCtx = {
       rng: this.rng,
       terrain: this.terrain,
@@ -361,6 +470,8 @@ export class Game {
       facing: 1,
       grounded: false,
       sinceGrounded: Infinity,
+      wallSide: 0,
+      sinceWall: Infinity,
       jumpBuffer: 0,
       attackCooldown: 0,
       specialCooldown: 0,
@@ -372,6 +483,9 @@ export class Game {
       poison: 0,
       cough: 0,
       soaked: 0,
+      flat: 0,
+      lastVx: 0,
+      lastVy: 0,
       prevRaw: 0,
       item: null,
       score: 0,
@@ -387,6 +501,7 @@ export class Game {
     if (this.cherry?.holder === id) this.dropCherry(p);
     this.world.destroyBody(p.body);
     this.players.delete(id);
+    this.turrets = this.turrets.filter((t) => t.owner !== id);
   }
 
   /** Moves a player (debug tools and tests). */
@@ -412,13 +527,17 @@ export class Game {
   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), {
+    // Dragées and sprinkles are small: their little blast must reach the cake they land on.
+    const radius = kind === 'sprinkle' || kind === 'dragee' ? SMALL_PROJECTILE_RADIUS : ITEM_RADIUS;
+    body.createFixture(new Circle(radius / PPM), {
       density: 0.6,
       friction: 0.6,
       restitution: 0.25,
       userData: { item: id } satisfies FixtureTag,
       // A ball of yarn flies through players: it must not stick to its thrower or wrap anyone.
       filterMaskBits: kind === 'yarn' ? ~CATEGORY_PLAYER & 0xffff : 0xffff,
+      // Sprinkles rain down together: they never hit one another.
+      filterGroupIndex: kind === 'sprinkle' ? -1 : 0,
     });
     this.items.set(id, { id, kind, body, age: 0, thrown: null });
     return id;
@@ -452,19 +571,26 @@ export class Game {
     this.syncTerrain(result);
 
     this.crushedThisStep.clear();
+    this.chunkSpeedBefore.clear();
+    for (const c of this.chunks.values()) this.chunkSpeedBefore.set(c.id, c.speed());
     this.world.step(TICK_DT, 8, 3);
-    for (const id of this.crushedThisStep) {
+    for (const [id, pixels] of this.crushedThisStep) {
       const p = this.players.get(id);
       if (!p || p.dead > 0) continue;
       const pos = p.body.getPosition();
-      result.crushed.push({ id, x: pos.x * PPM, y: pos.y * PPM });
-      this.kill(p, 'crushed');
+      // A small chunk only flattens its victim into a pancake for a while.
+      const flat = pixels < CRUSH_KILL_PIXELS;
+      if (flat && p.flat > 0) continue;
+      result.crushed.push({ id, x: pos.x * PPM, y: pos.y * PPM, flat });
+      if (flat) this.flatten(p);
+      else this.kill(p, 'crushed');
     }
     for (const p of this.players.values()) this.postStep(p);
     this.updateRound();
     this.updateCherry();
     this.updateItems();
     this.updateClouds();
+    this.updateTurrets();
     this.updateSoakZones();
     this.updateChunks(result);
     this.syncTerrain(result);
@@ -493,7 +619,8 @@ export class Game {
           (p.dead > 0 ? Anim.Dead : 0) |
           (p.boost > 0 ? Anim.Boosted : 0) |
           (p.poison > 0 ? Anim.Poisoned : 0) |
-          (p.soaked > 0 ? Anim.Soaked : 0),
+          (p.soaked > 0 ? Anim.Soaked : 0) |
+          (p.flat > 0 ? Anim.Flat : 0),
         score: Math.floor(p.score),
         item: p.item,
       };
@@ -514,7 +641,7 @@ export class Game {
     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 };
+      cherry = { x: pos.x * PPM, y: pos.y * PPM, holder: this.cherry.holder, heat: this.cherry.holder ? Math.min(1, this.cherry.heldFor / CHERRY_HOT_S) : 0 };
     }
     return {
       custardY: this.custardY,
@@ -522,6 +649,7 @@ export class Game {
       finalRush: this.rules !== null && this.timeLeft <= FINAL_RUSH_S,
       wind: this.wind,
       clouds: this.clouds.map((c) => [c.x, c.y, c.r, c.life / c.maxLife]),
+      turrets: this.turrets.map((t): TurretState => ({ id: t.id, x: t.x, y: t.y, angle: t.angle, owner: t.owner })),
       cherry,
     };
   }
@@ -562,6 +690,7 @@ export class Game {
     if (applyCells(this.terrain, 'detach', x0, y0, w, h, c.mask).changed) this.log({ kind: 'detach', id, x: x0, y: y0, w, h, mask, debris }, result);
     if (debris) return;
     this.chunks.set(id, new FallingChunk(this.world, id, c.mask, w, h, x0, y0, this.materials, mask));
+    this.chunkPixels.set(id, c.pixelCount);
     this.stats.add(owner, 'detached');
   }
 
@@ -643,6 +772,7 @@ export class Game {
   private removeChunk(chunk: FallingChunk): void {
     this.world.destroyBody(chunk.body);
     this.chunks.delete(chunk.id);
+    this.chunkPixels.delete(chunk.id);
   }
 
   private onPostSolve(contact: Contact, impulse: ContactImpulse): void {
@@ -652,10 +782,11 @@ export class Game {
     const chunkId = a?.chunk ?? b?.chunk;
     if (playerId === undefined || chunkId === undefined) return;
     const chunk = this.chunks.get(chunkId);
-    if (!chunk || !chunk.canCrush || chunk.speed() < CRUSH_MIN_SPEED) return;
+    // Speed before the impact: a small chunk stops dead on the player it lands on.
+    if (!chunk || !chunk.canCrush || Math.max(chunk.speed(), this.chunkSpeedBefore.get(chunkId) ?? 0) < CRUSH_MIN_SPEED) return;
     let total = 0;
     for (const n of impulse.normalImpulses) total += n;
-    if (total > CRUSH_IMPULSE) this.crushedThisStep.add(playerId);
+    if (total > CRUSH_IMPULSE) this.crushedThisStep.set(playerId, Math.max(this.crushedThisStep.get(playerId) ?? 0, this.chunkPixels.get(chunkId) ?? Infinity));
   }
 
   // ---------------------------------------------------------------- players
@@ -689,6 +820,7 @@ export class Game {
       return;
     }
     p.stun = Math.max(0, p.stun - TICK_DT);
+    p.flat = Math.max(0, p.flat - TICK_DT);
     p.stunLock = Math.max(0, p.stunLock - TICK_DT);
     p.soaked = Math.max(0, p.soaked - TICK_DT);
     p.boost = Math.max(0, p.boost - TICK_DT);
@@ -716,10 +848,22 @@ export class Game {
     }
 
     p.jumpBuffer = pressed & Button.Jump ? JUMP_BUFFER_TIME : Math.max(0, p.jumpBuffer - TICK_DT);
+    const jumpSpeed =
+      stats.jump * Math.sqrt(mobility) * (p.soaked > 0 ? SOAKED_JUMP_MULT : 1) * (this.cherry?.holder === p.info.id ? CHERRY_HOLDER_JUMP_MULT : 1);
+    const towardWall = !locked && p.wallSide !== 0 && isDown(input, p.wallSide > 0 ? Button.Right : Button.Left);
     if (p.jumpBuffer > 0 && p.sinceGrounded <= COYOTE_TIME) {
-      vy = -stats.jump * Math.sqrt(mobility) * (p.soaked > 0 ? SOAKED_JUMP_MULT : 1);
+      vy = -jumpSpeed;
       p.jumpBuffer = 0;
       p.sinceGrounded = Infinity;
+    } else if (p.jumpBuffer > 0 && p.sinceWall <= COYOTE_TIME && p.wallSide !== 0) {
+      // Wall jump: kick off the wall, up and a little away.
+      vy = -jumpSpeed * WALL_JUMP_UP;
+      vx = -p.wallSide * WALL_JUMP_PUSH;
+      p.jumpBuffer = 0;
+      p.sinceWall = Infinity;
+    } else if (towardWall && p.sinceWall === 0 && vy > WALL_SLIDE_SPEED) {
+      // Holding toward a wall slows the fall.
+      vy = WALL_SLIDE_SPEED;
     } else if (released & Button.Jump && vy < 0) {
       vy *= JUMP_CUT;
     }
@@ -754,19 +898,47 @@ export class Game {
   private postStep(p: ServerPlayer): void {
     if (p.dead > 0) return;
     p.grounded = false;
+    let wall = 0;
+    // The contact facing the previous velocity the most: a slam into it is a cartoon splat.
+    const lastSpeed = Math.hypot(p.lastVx, p.lastVy);
+    let slam: { nx: number; ny: number } | null = null;
+    let slamDot = 0;
     for (let edge = p.body.getContactList(); edge; edge = edge.next) {
       const contact = edge.contact;
       if (!contact.isTouching()) continue;
       const normal = contact.getWorldManifold(null)?.normal;
       if (!normal) continue;
       // The manifold normal points from fixture A to fixture B; flip it so it points toward the player.
-      const ny = contact.getFixtureA().getBody() === p.body ? -normal.y : normal.y;
-      if (ny < GROUND_NORMAL_Y) {
-        p.grounded = true;
-        break;
+      const flip = contact.getFixtureA().getBody() === p.body ? -1 : 1;
+      const nx = normal.x * flip;
+      const ny = normal.y * flip;
+      const dot = (p.lastVx * nx + p.lastVy * ny) / (lastSpeed || 1);
+      if (dot < slamDot) {
+        slamDot = dot;
+        slam = { nx, ny };
       }
+      if (ny < GROUND_NORMAL_Y) p.grounded = true;
+      // A wall on the left pushes the player right (+x), and the other way round.
+      else if (Math.abs(nx) > WALL_NORMAL_X) wall = nx > 0 ? -1 : 1;
     }
     p.sinceGrounded = p.grounded ? 0 : p.sinceGrounded + TICK_DT;
+    const vel = p.body.getLinearVelocity();
+    // Only someone sent flying by a hit (stunned) splats: a long fall onto the floor is just a landing.
+    if (slam && p.stun > 0 && lastSpeed > SPLAT_SPEED && slamDot < -0.6 && Math.hypot(vel.x, vel.y) * PPM < lastSpeed * 0.5) {
+      const pos = p.body.getPosition();
+      this.fx.push({ kind: 'splat', id: p.info.id, x: pos.x * PPM, y: pos.y * PPM, nx: slam.nx, ny: slam.ny });
+      // Stuck to the wall a moment longer.
+      p.stun = Math.max(p.stun, SPLAT_STUN_S);
+    }
+    p.lastVx = vel.x * PPM;
+    p.lastVy = vel.y * PPM;
+    if (!p.grounded && wall !== 0) {
+      p.wallSide = wall;
+      p.sinceWall = 0;
+    } else {
+      p.sinceWall += TICK_DT;
+      if (p.grounded) p.wallSide = 0;
+    }
     // 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;
@@ -942,8 +1114,15 @@ export class Game {
       target.body.setLinearVelocity({ x: ((nx / len) * kb) / PPM, y: ((ny / len) * kb) / PPM });
       this.stunPlayer(target, 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);
+      // A hit holder lets the cherry go (readme §4); the attacker may steal it.
+      if (this.cherry?.holder === target.info.id) {
+        this.dropCherry(target);
+        if (attacker) {
+          this.cherry.thief = attacker.info.id;
+          this.cherry.victim = target.info.id;
+          this.cherry.stealFor = CHERRY_STEAL_WINDOW_S;
+        }
+      }
       this.stats.add(target.info.id, 'hitTaken');
       if (attacker) this.stats.add(attacker.info.id, 'hits');
       count++;
@@ -961,6 +1140,15 @@ export class Game {
     p.stunLock = seconds + STUN_GUARD_S;
   }
 
+  /** Flattened into a pancake by a small chunk: stuck for FLAT_S (whatever the stun guard says). */
+  private flatten(p: ServerPlayer): void {
+    if (this.cherry?.holder === p.info.id) this.dropCherry(p);
+    this.stats.add(p.info.id, 'hitTaken');
+    p.flat = FLAT_S;
+    p.stun = FLAT_S;
+    p.stunLock = FLAT_S + STUN_GUARD_S;
+  }
+
   /** Bébé Pompier's spray: drenched players run and jump less for a while. */
   private drench(by: ServerPlayer, x: number, y: number, r: number): number {
     let count = 0;
@@ -983,6 +1171,7 @@ export class Game {
       vx: vel.x * PPM,
       vy: vel.y * PPM,
       grounded: p.grounded,
+      carryingCherry: this.cherry?.holder === p.info.id,
       facing: p.facing,
       input,
       emitOp: (op, onApplied) => this.queueOp(op, onApplied, p.info.id),
@@ -997,6 +1186,7 @@ export class Game {
       shove: (x, y, r, vx, vy, fraction) => this.shove(p, x, y, r, vx, vy, fraction),
       drench: (x, y, r) => this.drench(p, x, y, r),
       cloud: (x, y, r, life) => this.clouds.push({ x, y, r, life, maxLife: life, owner: p.info.id }),
+      buildTurret: (x, y, spec) => this.buildTurret(p, x, y, spec),
       swapWithRandomPlayer: () => this.swapWithRandom(p),
       cue: (cue) => {
         const at = p.body.getPosition();
@@ -1005,6 +1195,117 @@ export class Game {
     };
   }
 
+  /**
+   * Builds a turret on the ground near (x, y): straight down from there, or up to the surface
+   * when (x, y) is inside the cake. Its base is a disc of terrain half sunk in the ground.
+   */
+  private buildTurret(by: ServerPlayer, x: number, y: number, spec: TurretSpec): boolean {
+    const gx = Math.round(x);
+    let gy = Math.round(y);
+    const solid = (py: number): boolean => this.terrain.isSolid(gx, py);
+    if (solid(gy)) {
+      // Inside the cake: up to its surface.
+      let up = 0;
+      while (up < spec.groundReach && solid(gy - 1)) {
+        gy--;
+        up++;
+      }
+      if (solid(gy - 1)) return false;
+    } else {
+      let down = 0;
+      while (down < spec.groundReach && !solid(gy)) {
+        gy++;
+        down++;
+      }
+      if (!solid(gy)) return false;
+    }
+    const headY = gy - spec.height;
+    // No turret inside a player.
+    for (const p of this.alivePlayers()) {
+      const pos = p.body.getPosition();
+      if (Math.hypot(pos.x * PPM - gx, pos.y * PPM - (gy + headY) / 2) < p.bodyRadius + spec.baseRadius) return false;
+    }
+    const mine = this.turrets.filter((t) => t.owner === by.info.id);
+    if (mine.length >= spec.max) this.turrets = this.turrets.filter((t) => t !== mine[0]);
+    this.queueOp({ kind: 'fill', x: gx, y: gy, r: Math.round(spec.baseRadius), material: Math.round(spec.material) }, undefined, by.info.id);
+    this.turrets.push({
+      id: this.nextTurretId++,
+      owner: by.info.id,
+      spec,
+      x: gx,
+      y: headY,
+      baseX: gx,
+      baseY: gy - Math.round(spec.baseRadius / 2),
+      angle: -Math.PI / 2,
+      age: 0,
+      reload: spec.interval / 2,
+    });
+    return true;
+  }
+
+  /**
+   * Turrets fall with the cake they stand on, wear out, and shoot sugared almonds at the
+   * nearest player they can see (never their builder).
+   */
+  private updateTurrets(): void {
+    if (this.turrets.length === 0) return;
+    const gone: Turret[] = [];
+    for (const t of this.turrets) {
+      t.age += TICK_DT;
+      if (t.age > t.spec.life || (t.age > TURRET_SETTLE_S && !this.terrain.isSolid(t.baseX, t.baseY))) {
+        gone.push(t);
+        continue;
+      }
+      t.reload -= TICK_DT;
+      if (t.reload > 0) continue;
+      const target = this.turretTarget(t);
+      if (!target) {
+        t.reload = TURRET_SCAN_S;
+        continue;
+      }
+      t.reload = t.spec.interval;
+      const pos = target.body.getPosition();
+      const dx = pos.x * PPM - t.x;
+      const dy = pos.y * PPM - t.y;
+      const dist = Math.hypot(dx, dy);
+      const speed = t.spec.speed;
+      // Aim a little high: the dragée drops by g·t²/2 on its way (t ≈ dist / speed).
+      const vx = (dx / dist) * speed;
+      const vy = (dy / dist) * speed - (GRAVITY_PX * dist) / speed / 2;
+      t.angle = Math.atan2(vy, vx);
+      const start = TURRET_MUZZLE;
+      this.throwEntity(t.spec.projectile.kind, t.spec.projectile, t.owner, t.x + Math.cos(t.angle) * start, t.y + Math.sin(t.angle) * start, vx, vy);
+      this.fx.push({ kind: 'cue', id: t.owner, cue: 'turret', x: t.x, y: t.y });
+    }
+    for (const t of gone) this.fx.push({ kind: 'cue', id: t.owner, cue: 'turretDown', x: t.x, y: t.y });
+    if (gone.length > 0) this.turrets = this.turrets.filter((t) => !gone.includes(t));
+  }
+
+  /** The nearest living player in range, other than its builder, in plain sight of the turret's head. */
+  private turretTarget(t: Turret): ServerPlayer | null {
+    let best: ServerPlayer | null = null;
+    let bestDist = Infinity;
+    for (const p of this.alivePlayers()) {
+      if (p.info.id === t.owner) continue;
+      const pos = p.body.getPosition();
+      const dx = pos.x * PPM - t.x;
+      const dy = pos.y * PPM - t.y;
+      const dist = Math.hypot(dx, dy);
+      if (dist > t.spec.range || dist >= bestDist) continue;
+      let clear = true;
+      for (let d = TURRET_SIGHT_SKIP; d < dist - p.bodyRadius; d += TURRET_SIGHT_STEP) {
+        if (this.terrain.isSolid(Math.round(t.x + (dx / dist) * d), Math.round(t.y + (dy / dist) * d))) {
+          clear = false;
+          break;
+        }
+      }
+      if (!clear) continue;
+      best = p;
+      bestDist = dist;
+    }
+    return best;
+  }
+
   /** Rank by this round's score: 0 = last, 1 = leader, 0.5 when alone or everyone is tied. */
   private standing(p: ServerPlayer): number {
     const others = [...this.players.values()].filter((o) => o !== p);
@@ -1117,6 +1418,7 @@ export class Game {
   private updateRound(): void {
     if (!this.rules) return;
     for (const m of this.modifiers) m.tick(this.modifierCtx, TICK_DT);
+    this.updateSurprise();
     if (this.wind !== 0) {
       // Loose things drift too.
       const push = (body: Body): void => {
@@ -1137,6 +1439,26 @@ export class Game {
     this.custardY = Math.max(0, this.custardY - speed * TICK_DT);
   }
 
+  /** Starts a surprise now (also used by tests and debug tools). */
+  startSurprise(id: SurpriseId): void {
+    const s = SURPRISES[id](this.surpriseCtx);
+    this.surprise = { s, t: 0 };
+    this.fx.push({ kind: 'surprise', surprise: id, x: s.x, y: s.y, duration: s.duration });
+  }
+
+  private updateSurprise(): void {
+    const elapsed = (this.rules?.duration ?? 0) - this.timeLeft;
+    if (!this.surprise && this.surpriseAt.length > 0 && elapsed >= this.surpriseAt[0]) {
+      this.surpriseAt.shift();
+      this.startSurprise(this.rng.weighted(SURPRISE_WEIGHTS as Record<SurpriseId, number>));
+    }
+    const active = this.surprise;
+    if (!active) return;
+    active.s.tick(this.surpriseCtx, active.t, TICK_DT);
+    active.t += TICK_DT;
+    if (active.t >= active.s.duration) this.surprise = null;
+  }
+
   /** Solid pixels above the custard, plate excluded: what is left to stand on and fight over. */
   private cakeLeft(): number {
     const { width, data } = this.terrain;
@@ -1154,13 +1476,15 @@ export class Game {
     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 };
+    this.cherry = { body, holder: 0, blocked: 0, blockedFor: 0, heldFor: 0, fleeIn: 0, thief: 0, victim: 0, stealFor: 0 };
   }
 
   private updateCherry(): void {
     const cherry = this.cherry;
     if (!cherry) return;
     cherry.blockedFor = Math.max(0, cherry.blockedFor - TICK_DT);
+    cherry.stealFor = Math.max(0, cherry.stealFor - TICK_DT);
+    cherry.fleeIn = Math.max(0, cherry.fleeIn - 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.
@@ -1168,26 +1492,60 @@ export class Game {
       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);
+      // Hot potato: held too long, it blows up in their hands.
+      cherry.heldFor += TICK_DT;
+      if (cherry.heldFor >= CHERRY_HOT_S) {
+        const at = cherry.body.getPosition();
+        this.fx.push({ kind: 'cherryBoom', id: holder.info.id, x: at.x * PPM, y: at.y * PPM });
+        this.dropCherry(holder);
+        this.explodeAt(pos.x * PPM, pos.y * PPM, CHERRY_HOT_BLAST, 0, null);
+      }
       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;
+      // Back on the cake, anywhere it can rest (not always at the top: diggers get their chance).
+      const spots = this.landingSpots(CHERRY_RADIUS, Math.min(this.custardY, this.terrain.height) - CHERRY_RADIUS - 4);
+      const [x, y] = spots.length > 0 ? spots[this.rng.int(0, spots.length - 1)] : this.map.cherrySpawn;
       cherry.body.setPosition({ x: x / PPM, y: y / PPM });
+      this.fx.push({ kind: 'pickup', id: 0, item: 'cherry', x, y }); // shows everyone where it is now
       cherry.body.setLinearVelocity({ x: 0, y: 0 });
       return;
     }
+    let nearest: ServerPlayer | null = null;
+    let nearestDist = Infinity;
     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;
+      const dist = Math.hypot(pp.x - pos.x, pp.y - pos.y) * PPM;
+      if (dist < nearestDist) {
+        nearest = p;
+        nearestDist = dist;
+      }
+      if (dist > p.bodyRadius + CHERRY_RADIUS + 4) continue;
       cherry.holder = p.info.id;
+      cherry.heldFor = 0;
       cherry.body.setActive(false);
       this.fx.push({ kind: 'pickup', id: p.info.id, item: 'cherry', x: pos.x * PPM, y: pos.y * PPM });
+      // Knocked out of someone's hands and grabbed right away: stolen!
+      if (cherry.stealFor > 0 && cherry.thief === p.info.id) {
+        p.score += CHERRY_STEAL_BONUS;
+        this.fx.push({ kind: 'stolen', id: p.info.id, from: cherry.victim, bonus: CHERRY_STEAL_BONUS, x: pos.x * PPM, y: pos.y * PPM });
+      }
+      cherry.stealFor = 0;
       return;
     }
+    // Alive: resting, it hops away from whoever comes close (it can still be cornered).
+    const v = cherry.body.getLinearVelocity();
+    if (nearest && nearestDist < CHERRY_FLEE_RADIUS && cherry.fleeIn === 0 && Math.hypot(v.x, v.y) * PPM < 40) {
+      const away = pos.x >= nearest.body.getPosition().x ? 1 : -1;
+      cherry.body.setLinearVelocity({ x: (away * CHERRY_FLEE_SPEED) / PPM, y: -CHERRY_FLEE_HOP / PPM });
+      cherry.body.setAwake(true);
+      cherry.fleeIn = CHERRY_FLEE_COOLDOWN_S;
+      this.fx.push({ kind: 'cherryHop', x: pos.x * PPM, y: pos.y * PPM });
+    }
   }
 
   /** The holder lets the cherry go: it pops out and rolls (readme §4). */
@@ -1256,7 +1614,7 @@ export class Game {
   }
 
   private pickUp(p: ServerPlayer, item: Item, x: number, y: number): void {
-    if (item.kind === 'firecracker' || item.kind === 'yarn') return; // projectiles are not pickups
+    if (item.kind === 'firecracker' || item.kind === 'yarn' || item.kind === 'dragee' || item.kind === 'sprinkle') 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';
@@ -1294,7 +1652,7 @@ export class Game {
   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;
+    const fuse = spec?.kind === 'yarn' ? Infinity : spec ? spec.fuse : CANDLE_FUSE_S;
     const [anchorX, anchorY] = spec?.kind === 'yarn' ? this.yarnAnchor(owner, x, y) : [x, y];
     item.thrown = { owner, age: 0, fuse, arm: spec ? PROJECTILE_ARM_S : CANDLE_ARM_S, spec, anchorX, anchorY };
     item.body.setLinearVelocity({ x: vx / PPM, y: vy / PPM });
@@ -1318,7 +1676,7 @@ export class Game {
     }
     if (t.fuse <= 0 || hit) {
       this.removeItem(item);
-      this.explodeAt(x, y, spec?.kind === 'firecracker' ? spec.blast : CANDLE_BLAST, t.owner, null);
+      this.explodeAt(x, y, spec ? spec.blast : CANDLE_BLAST, t.owner, null);
     }
   }
 

+ 172 - 0
src/server/surprises/index.ts

@@ -0,0 +1,172 @@
+import type { ProjectileSpec } from '../../shared/characters';
+import {
+  CAT_PAW_KNOCKBACK,
+  CAT_PAW_LIFT,
+  CAT_PAW_POWER,
+  CAT_PAW_RADIUS,
+  CAT_PAW_STUN,
+  HAND_BITE_POWER,
+  HAND_BITE_RADIUS,
+  HAND_GRAB_RADIUS,
+  HAND_TOSS_SPEED,
+  QUAKE_CRACK_POWER,
+  QUAKE_CRACK_RADIUS,
+  QUAKE_CRACKS,
+  QUAKE_JOLT,
+  QUAKE_PERIOD_S,
+  SPRINKLE_BLAST,
+  SPRINKLE_PERIOD_S,
+  SPRINKLE_SPEED,
+  SURPRISE_DURATIONS,
+} from '../../shared/constants';
+import type { SurpriseId } from '../../shared/protocol';
+import type { Rng } from '../../shared/rng';
+import type { TerrainBitmap } from '../../shared/terrain/bitmap';
+import type { TerrainOp } from '../../shared/terrain/ops';
+
+// Surprise events (readme §4): once or twice a round, something from the kitchen turns the
+// game upside down. Every one goes through the terrain or the players; the client draws it.
+
+/** What a surprise may do. Implemented by the server Game. */
+export interface SurpriseContext {
+  readonly rng: Rng;
+  readonly terrain: TerrainBitmap;
+  queueOp(op: TerrainOp): void;
+  /** Living players: id, position and radius. */
+  players(): { id: number; x: number; y: number; r: number; grounded: boolean }[];
+  /** Sets a player's velocity (px/s) and stuns them (0 = no stun). */
+  fling(id: number, vx: number, vy: number, stun: number): void;
+  launch(spec: ProjectileSpec, x: number, y: number, vx: number, vy: number): void;
+  /** Highest solid pixel of column x (the top of the cake), or null. */
+  top(x: number): number | null;
+}
+
+export interface Surprise {
+  readonly id: SurpriseId;
+  /** Where it happens (meaning depends on the surprise, see the client). */
+  readonly x: number;
+  readonly y: number;
+  readonly duration: number;
+  /** `t`: seconds since it started. */
+  tick(ctx: SurpriseContext, t: number, dt: number): void;
+}
+
+/** A random column with cake in it, and its top (or the middle of the map if none). */
+function randomTop(ctx: SurpriseContext): [number, number] {
+  for (let tries = 0; tries < 60; tries++) {
+    const x = ctx.rng.int(60, ctx.terrain.width - 60);
+    const y = ctx.top(x);
+    if (y !== null) return [x, y];
+  }
+  return [ctx.terrain.width / 2, ctx.terrain.height / 2];
+}
+
+/** "Le chat de la maison passe !": a giant paw sweeps across the summit of the cake. */
+function catPaw(ctx: SurpriseContext): Surprise {
+  const fromLeft = ctx.rng.next() < 0.5;
+  // It scrapes the summit: lower, it would saw through the tiers and send the whole cake down.
+  let top = ctx.terrain.height;
+  for (let x = 0; x < ctx.terrain.width; x += 8) top = Math.min(top, ctx.top(x) ?? top);
+  const y = top + CAT_PAW_RADIUS * 0.6;
+  const x0 = fromLeft ? -CAT_PAW_RADIUS : ctx.terrain.width + CAT_PAW_RADIUS;
+  const x1 = fromLeft ? ctx.terrain.width + CAT_PAW_RADIUS : -CAT_PAW_RADIUS;
+  const dir = fromLeft ? 1 : -1;
+  const duration = SURPRISE_DURATIONS['cat-paw'];
+  const hit = new Set<number>();
+  return {
+    id: 'cat-paw',
+    x: x0,
+    y,
+    duration,
+    tick(c, t) {
+      const x = x0 + (x1 - x0) * Math.min(1, t / duration);
+      c.queueOp({ kind: 'carve', x: Math.round(x), y: Math.round(y), r: CAT_PAW_RADIUS, power: CAT_PAW_POWER });
+      for (const p of c.players()) {
+        if (hit.has(p.id) || Math.hypot(p.x - x, p.y - y) > CAT_PAW_RADIUS + p.r) continue;
+        hit.add(p.id);
+        c.fling(p.id, dir * CAT_PAW_KNOCKBACK, -CAT_PAW_LIFT, CAT_PAW_STUN);
+      }
+    },
+  };
+}
+
+/** "Tremblement de table !": the whole cake jumps, players hop around, cracks open. */
+function quake(): Surprise {
+  let next = 0;
+  return {
+    id: 'quake',
+    x: 0,
+    y: 0,
+    duration: SURPRISE_DURATIONS.quake,
+    tick(c, t) {
+      if (t < next) return;
+      next += QUAKE_PERIOD_S;
+      for (const p of c.players()) if (p.grounded) c.fling(p.id, c.rng.range(-1, 1) * QUAKE_JOLT * 0.6, -QUAKE_JOLT, 0);
+      const { width, height } = c.terrain;
+      for (let n = 0; n < QUAKE_CRACKS; n++) {
+        for (let tries = 0; tries < 30; tries++) {
+          const x = c.rng.int(0, width - 1);
+          const y = c.rng.int(0, height - 1);
+          if (!c.terrain.isSolid(x, y)) continue;
+          c.queueOp({ kind: 'carve', x, y, r: QUAKE_CRACK_RADIUS, power: QUAKE_CRACK_POWER });
+          break;
+        }
+      }
+    },
+  };
+}
+
+/** "Pluie de vermicelles !": sugar sprinkles rain down and nibble the cake everywhere. */
+function sprinkles(): Surprise {
+  let next = 0;
+  const spec: ProjectileSpec = { kind: 'sprinkle', fuse: 8, blast: SPRINKLE_BLAST };
+  return {
+    id: 'sprinkles',
+    x: 0,
+    y: 0,
+    duration: SURPRISE_DURATIONS.sprinkles,
+    tick(c, t) {
+      while (next <= t) {
+        next += SPRINKLE_PERIOD_S;
+        const x = c.rng.int(20, c.terrain.width - 20);
+        c.launch(spec, x, -20, c.rng.range(-60, 60), SPRINKLE_SPEED);
+      }
+    },
+  };
+}
+
+/** "L'enfant a faim !": a giant hand comes down, grabs a fistful of cake and whoever is there. */
+function giantHand(ctx: SurpriseContext): Surprise {
+  const [x, y] = randomTop(ctx);
+  const duration = SURPRISE_DURATIONS['giant-hand'];
+  let done = false;
+  return {
+    id: 'giant-hand',
+    x,
+    y,
+    duration,
+    tick(c, t) {
+      // The shadow grows for the first half (time to run), then the hand closes.
+      if (done || t < duration / 2) return;
+      done = true;
+      c.queueOp({ kind: 'carve', x: Math.round(x), y: Math.round(y + HAND_BITE_RADIUS * 0.4), r: HAND_BITE_RADIUS, power: HAND_BITE_POWER });
+      for (const p of c.players()) {
+        if (Math.hypot(p.x - x, p.y - y) > HAND_GRAB_RADIUS) continue;
+        c.fling(p.id, c.rng.range(-0.4, 0.4) * HAND_TOSS_SPEED, -HAND_TOSS_SPEED, 0.8);
+      }
+    },
+  };
+}
+
+/** "Panne de courant !": the lights go out (drawn by the clients; only eyes glow). */
+function blackout(): Surprise {
+  return { id: 'blackout', x: 0, y: 0, duration: SURPRISE_DURATIONS.blackout, tick() {} };
+}
+
+export const SURPRISES: Record<SurpriseId, (ctx: SurpriseContext) => Surprise> = {
+  'cat-paw': catPaw,
+  quake,
+  sprinkles,
+  'giant-hand': giantHand,
+  blackout,
+};

+ 49 - 1
src/shared/characters/Character.ts

@@ -37,6 +37,10 @@ export const Anim = {
   Underground: 1 << 7,
   /** Drenched by Bébé Pompier's spray: slower run and jump. */
   Soaked: 1 << 8,
+  /** Léon le Caméléon blending in: hidden from the other players. */
+  Invisible: 1 << 9,
+  /** Flattened into a pancake by a small falling chunk. */
+  Flat: 1 << 10,
 } as const;
 
 /** A random spell of the Magicien Raté. */
@@ -54,9 +58,36 @@ export interface Blast {
 export type ProjectileSpec =
   /** Explodes on contact (after arming) or when the fuse runs out. */
   | { kind: 'firecracker'; fuse: number; blast: Blast }
+  /** A sugar pellet shot by a turret: same behaviour as a firecracker, drawn differently. */
+  | { kind: 'dragee'; fuse: number; blast: Blast }
+  /** A sugar sprinkle from the "pluie de vermicelles" surprise. */
+  | { kind: 'sprinkle'; fuse: number; blast: Blast }
   /** Trails a thread tied under the thrower; where it hits, the thread is laid taut and a wool blob sticks. */
   | { kind: 'yarn'; life: number; trailRadius: number; blobRadius: number; material: number };
 
+/**
+ * A turret built by Tatie Douille. Its base is terrain (a disc of `material` laid on the ground):
+ * when the cake under the base is gone, the turret goes with it.
+ */
+export interface TurretSpec {
+  /** Disc of terrain laid as the base (px), and its material id. */
+  baseRadius: number;
+  material: number;
+  /** The head sits this far above the ground (px). */
+  height: number;
+  /** How far it looks for a target (px), how often it shoots (s), how long it lasts (s). */
+  range: number;
+  interval: number;
+  life: number;
+  /** Turrets per player: building one more removes the oldest. */
+  max: number;
+  /** How far below (or above, if inside the cake) the aim point it looks for the ground (px). */
+  groundReach: number;
+  /** Speed of what it shoots (px/s). */
+  speed: number;
+  projectile: ProjectileSpec;
+}
+
 /** What a character may read and do. Implemented by the server simulation. */
 export interface CharacterContext {
   readonly x: number;
@@ -64,6 +95,8 @@ export interface CharacterContext {
   readonly vx: number;
   readonly vy: number;
   readonly grounded: boolean;
+  /** Holding the cherry (it weighs the holder down). */
+  readonly carryingCherry: boolean;
   /** -1 left, 1 right */
   readonly facing: number;
   readonly input: InputState;
@@ -93,13 +126,28 @@ export interface CharacterContext {
   drench(x: number, y: number, r: number): number;
   /** Leaves a toxic cloud: other players inside are poisoned (blurred vision, coughing). */
   cloud(x: number, y: number, r: number, life: number): void;
+  /** Builds a turret on the ground near (x, y). Returns false when there is no room or no ground. */
+  buildTurret(x: number, y: number, spec: TurretSpec): boolean;
   /** Swaps places with another player at random. Returns false if alone. */
   swapWithRandomPlayer(): boolean;
   /** A visual/sound cue everyone notices (e.g. "PROUT !", a spell). */
   cue(kind: CharacterCue): void;
 }
 
-export type CharacterCue = 'prout' | 'water' | `spell-${Spell}` | 'emerge' | 'lick' | 'pounce' | 'backfire';
+export type CharacterCue =
+  | 'prout'
+  | 'water'
+  | `spell-${Spell}`
+  | 'emerge'
+  | 'lick'
+  | 'pounce'
+  | 'backfire'
+  | 'build'
+  | 'turret'
+  | 'turretDown'
+  | 'tongue'
+  | 'vanish'
+  | 'appear';
 
 /** Base class for all characters. Pure logic: no physics engine, no rendering. */
 export abstract class Character {

+ 63 - 0
src/shared/characters/Leon.ts

@@ -0,0 +1,63 @@
+import { Anim, Character, type CharacterContext } from './Character';
+import { aimDir } from './Mamie';
+
+/**
+ * Léon le Caméléon.
+ * - Attack: shoots his long sticky tongue toward the aim. It licks a groove through the cake,
+ *   and whatever it catches at the tip is pulled back to him: players (who drop the cherry),
+ *   items, falling chunks.
+ * - Special: blends in and turns invisible for the other players for a while (press again to
+ *   show up early).
+ * - Flaw: attacking or being hit shows him at once, and a cherry he holds floats in plain sight.
+ */
+export class Leon extends Character {
+  private tongueTimer = 0;
+  private hidden = 0;
+
+  onAttack(ctx: CharacterContext): void {
+    const p = this.stats.params;
+    this.reveal(ctx);
+    const [dx, dy] = aimDir(ctx);
+    // The groove licked through the cake on the way.
+    for (let d = this.size; d <= this.size + p.tongueReach; d += p.tongueStep) {
+      ctx.emitOp({ kind: 'carve', x: Math.round(ctx.x + dx * d), y: Math.round(ctx.y + dy * d), r: Math.round(p.tongueCarve), power: Math.round(p.tonguePower) });
+    }
+    // Caught at the tip: stuck, then pulled back to him.
+    const tx = ctx.x + dx * (this.size + p.tongueReach);
+    const ty = ctx.y + dy * (this.size + p.tongueReach);
+    ctx.hit(tx, ty, p.tongueRadius, 0, p.tongueStun);
+    ctx.shove(tx, ty, p.tongueRadius, -dx * p.tonguePull, -dy * p.tonguePull - p.tongueLift, 1);
+    ctx.cue('tongue');
+    this.tongueTimer = p.tongueAnim;
+  }
+
+  onSpecial(ctx: CharacterContext): void {
+    if (this.hidden > 0) {
+      this.reveal(ctx);
+      return;
+    }
+    this.hidden = this.stats.params.invisibleTime;
+    ctx.cue('vanish');
+  }
+
+  override onHit(ctx: CharacterContext): void {
+    this.reveal(ctx);
+  }
+
+  override onTick(ctx: CharacterContext, dt: number): void {
+    this.tongueTimer = Math.max(0, this.tongueTimer - dt);
+    if (this.hidden <= 0) return;
+    this.hidden -= dt;
+    if (this.hidden <= 0) this.reveal(ctx);
+  }
+
+  override anim(): number {
+    return (this.tongueTimer > 0 ? Anim.Attack : 0) | (this.hidden > 0 ? Anim.Invisible : 0);
+  }
+
+  private reveal(ctx: CharacterContext): void {
+    if (this.hidden === 0) return;
+    this.hidden = 0;
+    ctx.cue('appear');
+  }
+}

+ 2 - 1
src/shared/characters/Prout.ts

@@ -28,7 +28,8 @@ export class Prout extends Character {
 
   onSpecial(ctx: CharacterContext): void {
     const p = this.stats.params;
-    if (this.puffsUsed >= p.airPuffs) return;
+    // The cherry is heavy: fewer thrusts while he holds it.
+    if (this.puffsUsed >= (ctx.carryingCherry ? p.cherryAirPuffs : p.airPuffs)) return;
     this.puffsUsed++;
     const [dx] = aimDir(ctx);
     ctx.setVelocity(ctx.vx + dx * p.puffSide, Math.min(ctx.vy, 0) - p.puffLift);

+ 75 - 0
src/shared/characters/Tatie.ts

@@ -0,0 +1,75 @@
+import { Anim, Character, type CharacterContext, type TurretSpec } from './Character';
+import { aimDir } from './Mamie';
+
+/**
+ * Tatie Douille, the pastry chef.
+ * - Attack: rolling pin swipe (it knocks a bit of cake off too).
+ * - Special: pipes a turret on the ground toward the aim. Its base is biscuit laid on the cake;
+ *   the head shoots sugared almonds (dragées) at the nearest player it can see. When the cake
+ *   under it is gone, the turret is gone. Two at most: a third replaces the oldest.
+ * - Flaw: she stands still while piping a turret, and a turret falls with the cake under it.
+ */
+export class Tatie extends Character {
+  private pinTimer = 0;
+  private buildTimer = 0;
+
+  onAttack(ctx: CharacterContext): void {
+    const p = this.stats.params;
+    const [dx, dy] = aimDir(ctx);
+    const reach = this.size + p.pinReach;
+    const x = ctx.x + dx * reach;
+    const y = ctx.y + dy * reach;
+    ctx.hit(x, y, p.pinRadius, p.pinKnockback, p.pinStun);
+    ctx.emitOp({ kind: 'carve', x: Math.round(x), y: Math.round(y), r: Math.round(p.pinCarve), power: Math.round(p.pinPower) });
+    this.pinTimer = p.pinAnim;
+  }
+
+  onSpecial(ctx: CharacterContext): void {
+    const p = this.stats.params;
+    let dx = ctx.input.aimX - ctx.x;
+    let dy = ctx.input.aimY - ctx.y;
+    const dist = Math.hypot(dx, dy);
+    if (dist > p.buildReach) {
+      dx = (dx / dist) * p.buildReach;
+      dy = (dy / dist) * p.buildReach;
+    }
+    if (ctx.buildTurret(ctx.x + dx, ctx.y + dy, this.turret())) {
+      ctx.cue('build');
+      this.buildTimer = p.buildAnim;
+    }
+  }
+
+  override onTick(_ctx: CharacterContext, dt: number): void {
+    this.pinTimer = Math.max(0, this.pinTimer - dt);
+    this.buildTimer = Math.max(0, this.buildTimer - dt);
+  }
+
+  /** Piping a turret takes her whole attention. */
+  override busy(): boolean {
+    return this.buildTimer > 0;
+  }
+
+  override anim(): number {
+    return (this.pinTimer > 0 ? Anim.Attack : 0) | (this.buildTimer > 0 ? Anim.Special : 0);
+  }
+
+  private turret(): TurretSpec {
+    const p = this.stats.params;
+    return {
+      baseRadius: p.turretBaseRadius,
+      material: p.turretMaterial,
+      height: p.turretHeight,
+      range: p.turretRange,
+      interval: p.turretInterval,
+      life: p.turretLife,
+      max: p.turretMax,
+      groundReach: p.turretGroundReach,
+      speed: p.drageeSpeed,
+      projectile: {
+        kind: 'dragee',
+        fuse: p.drageeFuse,
+        blast: { r: p.drageeRadius, power: p.drageePower, knockback: p.drageeKnockback, stun: p.drageeStun },
+      },
+    };
+  }
+}

+ 5 - 1
src/shared/characters/index.ts

@@ -2,12 +2,14 @@ import { Castor } from './Castor';
 import type { Character, CharacterStats } from './Character';
 import { Chat } from './Chat';
 import { Gege } from './Gege';
+import { Leon } from './Leon';
 import { Generic } from './Generic';
 import { Magicien } from './Magicien';
 import { Mamie } from './Mamie';
 import { Pompier } from './Pompier';
 import { Prout } from './Prout';
 import { Pyromanchot } from './Pyromanchot';
+import { Tatie } from './Tatie';
 
 // Menu order (readme §4 table), then the test character.
 const registry: Record<string, new (stats: CharacterStats) => Character> = {
@@ -19,6 +21,8 @@ const registry: Record<string, new (stats: CharacterStats) => Character> = {
   prout: Prout,
   chat: Chat,
   magicien: Magicien,
+  tatie: Tatie,
+  leon: Leon,
   generic: Generic,
 };
 
@@ -39,4 +43,4 @@ export function createCharacter(stats: CharacterStats): Character {
 }
 
 export { Anim, Character, parseCharacterStats } from './Character';
-export type { Blast, CharacterContext, CharacterCue, CharacterStats, ProjectileSpec, Spell } from './Character';
+export type { Blast, CharacterContext, CharacterCue, CharacterStats, ProjectileSpec, Spell, TurretSpec } from './Character';

+ 64 - 1
src/shared/constants.ts

@@ -2,7 +2,7 @@
 // (characters, maps, materials) whenever they belong to a specific entity.
 
 /** Bumped on every incompatible protocol change. */
-export const PROTOCOL_VERSION = 10;
+export const PROTOCOL_VERSION = 12;
 
 export const NET_PORT = 47100;
 export const DISCOVERY_PORT = 47101;
@@ -174,6 +174,64 @@ export const JUMP_BUFFER_TIME = 0.1;
 /** Vertical speed multiplier applied when jump is released while rising. */
 export const JUMP_CUT = 0.5;
 export const AIR_CONTROL = 0.6;
+/**
+ * Wall jump, for everyone (no character is stuck under a tier): touching a wall in the air,
+ * jump kicks off it (WALL_JUMP_UP × the jump, WALL_JUMP_PUSH px/s away); holding toward the wall
+ * brings you back to kick again, and slows the fall to WALL_SLIDE_SPEED px/s.
+ */
+export const WALL_NORMAL_X = 0.7;
+export const WALL_JUMP_UP = 1;
+export const WALL_JUMP_PUSH = 170;
+export const WALL_SLIDE_SPEED = 90;
+/** The cherry is heavy: its holder jumps this much (and Captain Prout gets fewer thrusts). */
+export const CHERRY_HOLDER_JUMP_MULT = 0.8;
+// The cherry is alive (readme §4). Tune by playing.
+/** Free and resting, it hops away from a player closer than this (px), at most once per cooldown (s). */
+export const CHERRY_FLEE_RADIUS = 90;
+export const CHERRY_FLEE_COOLDOWN_S = 1.2;
+export const CHERRY_FLEE_SPEED = 220;
+export const CHERRY_FLEE_HOP = 380;
+/** Hot potato: held this long by the same player, it explodes in their hands (s). */
+export const CHERRY_HOT_S = 20;
+export const CHERRY_HOT_BLAST = { r: 40, power: 30, knockback: 700, stun: 0.6 };
+/** Knocking the cherry out of someone's hands and grabbing it within this delay (s) steals it: bonus points. */
+export const CHERRY_STEAL_WINDOW_S = 2.5;
+export const CHERRY_STEAL_BONUS = 3;
+
+// Cartoon hits. Tune by playing.
+/** A player flying faster than this (px/s) who slams into a wall or the floor goes "SPLAF". */
+export const SPLAT_SPEED = 650;
+export const SPLAT_STUN_S = 0.4;
+/** A crushing chunk smaller than this (px) only flattens its victim into a pancake for FLAT_S. */
+export const CRUSH_KILL_PIXELS = 6000;
+export const FLAT_S = 2;
+
+// Surprise events (server/surprises). Tune by playing.
+/** Surprises per round, at random times between SURPRISE_WINDOW[0] s and SURPRISE_WINDOW[1] s before the end. */
+export const SURPRISES_PER_ROUND = 2;
+export const SURPRISE_WINDOW: [number, number] = [25, 20];
+export const SURPRISE_WEIGHTS = { 'cat-paw': 3, quake: 2, sprinkles: 2, 'giant-hand': 3, blackout: 2 } as const;
+export const SURPRISE_DURATIONS = { 'cat-paw': 1.8, quake: 2.5, sprinkles: 4, 'giant-hand': 1.8, blackout: 6 } as const;
+export const CAT_PAW_RADIUS = 46;
+export const CAT_PAW_POWER = 50;
+export const CAT_PAW_KNOCKBACK = 900;
+export const CAT_PAW_LIFT = 350;
+export const CAT_PAW_STUN = 0.5;
+export const QUAKE_PERIOD_S = 0.3;
+export const QUAKE_JOLT = 420;
+export const QUAKE_CRACKS = 4;
+export const QUAKE_CRACK_RADIUS = 9;
+export const QUAKE_CRACK_POWER = 35;
+export const SPRINKLE_PERIOD_S = 0.06;
+export const SPRINKLE_SPEED = 300;
+export const SPRINKLE_BLAST = { r: 9, power: 25, knockback: 160, stun: 0 };
+/** Body radius of dragées and sprinkles (px). */
+export const SMALL_PROJECTILE_RADIUS = 5;
+export const HAND_BITE_RADIUS = 85;
+export const HAND_BITE_POWER = 55;
+export const HAND_GRAB_RADIUS = 110;
+export const HAND_TOSS_SPEED = 1000;
+
 /** Contact normal Y below which a contact counts as ground (y points down). */
 export const GROUND_NORMAL_Y = -0.5;
 /** A growing body's physics fixture is rebuilt once its radius drifts this far (px). */
@@ -191,3 +249,8 @@ export const OUTLINE_PX = 4;
 export const RENDER_MARGIN = 12;
 /** Chunks within this distance of a modified pixel are marked dirty (contours need 1 px, rendering RENDER_MARGIN). */
 export const DIRTY_MARGIN = RENDER_MARGIN;
+
+/** Git repository whose tags and refs/builds/* publish the self-updates (src/main/updates.ts). */
+export const UPDATE_REPO_URL = 'https://git.idleman.fr/idleman/foodmageddon';
+/** Delay before the packaged app looks for an update, so startup stays smooth (ms). */
+export const UPDATE_CHECK_DELAY_MS = 3000;

+ 28 - 2
src/shared/protocol.ts

@@ -39,7 +39,7 @@ export interface PlayerState {
 
 export type ItemKind = 'candle' | 'smarties' | 'whisk';
 /** Things in flight: pickable items, and projectiles thrown by characters. */
-export type EntityKind = ItemKind | 'firecracker' | 'yarn';
+export type EntityKind = ItemKind | 'firecracker' | 'yarn' | 'dragee' | 'sprinkle';
 
 /** An item lying around, falling, or thrown (lit candle, firecracker, yarn ball). */
 export interface ItemState {
@@ -53,13 +53,27 @@ export interface ItemState {
   thread?: [number, number];
 }
 
+/** A turret (Tatie Douille): its head, where it aims (radians), and whose it is. */
+export interface TurretState {
+  id: number;
+  x: number;
+  y: number;
+  angle: number;
+  owner: number;
+}
+
 export interface CherryState {
   x: number;
   y: number;
   /** Player holding it, 0 when it rolls free. */
   holder: number;
+  /** Hot potato: 0 when just picked up, 1 when it explodes in the holder's hands. */
+  heat: number;
 }
 
+/** Surprise events (server/surprises). */
+export type SurpriseId = 'cat-paw' | 'quake' | 'sprinkles' | 'giant-hand' | 'blackout';
+
 /** Round-wide state carried by every snapshot. Null fields are inactive (warm-up). */
 export interface RoundState {
   custardY: number;
@@ -71,6 +85,7 @@ export interface RoundState {
   wind: number;
   /** Toxic clouds: [x, y, radius, life left 0..1]. */
   clouds: [number, number, number, number][];
+  turrets: TurretState[];
   cherry: CherryState | null;
 }
 
@@ -82,6 +97,16 @@ export type FxEvent =
   | { kind: 'pickup'; id: number; item: ItemKind | 'cherry'; x: number; y: number }
   | { kind: 'cherryDrop'; id: number; x: number; y: number }
   | { kind: 'whisk'; id: number }
+  /** A surprise starts: (x, y) depends on it (where the paw comes from, where the hand grabs). */
+  | { kind: 'surprise'; surprise: SurpriseId; x: number; y: number; duration: number }
+  /** The free cherry hops away from someone. */
+  | { kind: 'cherryHop'; x: number; y: number }
+  /** Held too long, the cherry exploded in its holder's hands. */
+  | { kind: 'cherryBoom'; id: number; x: number; y: number }
+  /** `id` knocked the cherry out of `from`'s hands and grabbed it: bonus points. */
+  | { kind: 'stolen'; id: number; from: number; bonus: number; x: number; y: number }
+  /** A player slammed into a wall or the floor; (nx, ny) points away from it. */
+  | { kind: 'splat'; id: number; x: number; y: number; nx: number; ny: number }
   /** A character's signature cue (a fart, a water jet, a spell...), at its position. */
   | { kind: 'cue'; id: number; cue: CharacterCue; x: number; y: number };
 
@@ -216,7 +241,8 @@ export type ServerMessage =
   | { t: 'terrain'; seq: number; ev: TerrainEvent }
   /** A chunk left the game without merging (fell off the map). */
   | { t: 'chunkRemoved'; id: number }
-  | { t: 'crushed'; id: number; x: number; y: number }
+  /** `flat`: only flattened into a pancake (small chunk), not out of the round. */
+  | { t: 'crushed'; id: number; x: number; y: number; flat: boolean }
   | { t: 'snapshot'; tick: number; players: PlayerState[]; chunks: ChunkState[]; items: ItemState[]; round: RoundState }
   | { t: 'fx'; ev: FxEvent }
   | {

+ 123 - 1
tests/characters.test.ts

@@ -38,7 +38,7 @@ function press(game: Game, id: number, buttons: number, x: number, y: number): F
 
 describe('roster', () => {
   it('every character has data that loads', () => {
-    expect(CHARACTER_IDS).toEqual(['castor', 'mamie', 'pyromanchot', 'gege', 'pompier', 'prout', 'chat', 'magicien', 'generic']);
+    expect(CHARACTER_IDS).toEqual(['castor', 'mamie', 'pyromanchot', 'gege', 'pompier', 'prout', 'chat', 'magicien', 'tatie', 'leon', 'generic']);
     for (const id of CHARACTER_IDS) expect(loadCharacterStats(ASSETS, id).id).toBe(id);
   });
 });
@@ -416,3 +416,125 @@ describe('Magicien Raté', () => {
     throw new Error('no rabbit in 60 casts');
   });
 });
+
+describe('Tatie Douille', () => {
+  it('builds a turret on the ground, which shoots the others but never her', () => {
+    const game = newGame();
+    const tatie = game.addPlayer('Tatie', 'tatie');
+    const victim = game.addPlayer('Victime', 'generic');
+    game.teleport(tatie.id, 600, 420); // middle tier top
+    game.teleport(victim.id, 770, 440); // further along the middle tier, in sight
+    run(game, 60);
+    const t = me(game, tatie.id);
+    const fx = press(game, tatie.id, Button.Special, t.x + 60, t.y);
+    expect(fx).toContainEqual(expect.objectContaining({ kind: 'cue', cue: 'build' }));
+    run(game, 2);
+    const [turret] = game.roundState().turrets;
+    expect(turret).toMatchObject({ owner: tatie.id });
+    // Its base is cake: biscuit right under the head.
+    expect(game.terrain.data[(turret.y + 14) * game.terrain.width + turret.x]).toBe(5);
+    let shots = 0;
+    let victimHit = false;
+    for (let i = 0; i < 4 * TICK_RATE; i++) {
+      const step = game.step().fx;
+      shots += step.filter((e) => e.kind === 'cue' && e.cue === 'turret').length;
+      if (me(game, victim.id).anim & Anim.Stunned) victimHit = true;
+    }
+    expect(shots).toBeGreaterThanOrEqual(2);
+    expect(victimHit).toBe(true);
+    // Its own shots never knock it down.
+    expect(game.roundState().turrets).toHaveLength(1);
+    expect(game.stats.get(tatie.id, 'hits')).toBeGreaterThan(0);
+  });
+
+  it('a turret falls with the cake under it, and a third one replaces the oldest', () => {
+    const game = newGame();
+    const tatie = game.addPlayer('Tatie', 'tatie');
+    game.teleport(tatie.id, 600, 420);
+    run(game, 60);
+    // Three turrets along the exposed part of the middle tier (x 520 to 780).
+    for (const x of [560, 650, 720]) {
+      press(game, tatie.id, Button.Special, x, me(game, tatie.id).y);
+      run(game, Math.ceil(2.6 * TICK_RATE));
+    }
+    const turrets = game.roundState().turrets;
+    expect(turrets).toHaveLength(2);
+    expect(turrets[0].x).toBeGreaterThan(600); // the first one (x ≈ 560) was replaced
+    // Blow the ground away under one of them.
+    const target = turrets[0];
+    game.queueOp({ kind: 'carve', x: target.x, y: target.y + 18, r: 30, power: 99 });
+    const fx = run(game, 10);
+    expect(fx).toContainEqual(expect.objectContaining({ kind: 'cue', cue: 'turretDown' }));
+    expect(game.roundState().turrets.map((t) => t.id)).toEqual([turrets[1].id]);
+  });
+
+  it('cannot build in thin air', () => {
+    const game = newGame();
+    const tatie = game.addPlayer('Tatie', 'tatie');
+    game.teleport(tatie.id, 150, 300); // left of the cake: only the custard below
+    run(game, 2);
+    const t = me(game, tatie.id);
+    const fx = press(game, tatie.id, Button.Special, t.x - 100, t.y);
+    expect(fx.some((e) => e.kind === 'cue' && e.cue === 'build')).toBe(false);
+    expect(game.roundState().turrets).toHaveLength(0);
+  });
+});
+
+describe('Léon le Caméléon', () => {
+  it('turns invisible, and shows up again when he attacks', () => {
+    const game = newGame();
+    const leon = game.addPlayer('Léon', 'leon');
+    run(game, 60);
+    const l = me(game, leon.id);
+    const fx = press(game, leon.id, Button.Special, l.x, l.y);
+    expect(fx).toContainEqual(expect.objectContaining({ kind: 'cue', cue: 'vanish' }));
+    expect(me(game, leon.id).anim & Anim.Invisible).toBeTruthy();
+    run(game, TICK_RATE);
+    expect(me(game, leon.id).anim & Anim.Invisible).toBeTruthy();
+    const back = press(game, leon.id, Button.Attack, l.x + 100, l.y);
+    expect(back).toContainEqual(expect.objectContaining({ kind: 'cue', cue: 'appear' }));
+    expect(me(game, leon.id).anim & Anim.Invisible).toBeFalsy();
+  });
+
+  it('invisibility wears off on its own, and a hit reveals him', () => {
+    const game = newGame();
+    const leon = game.addPlayer('Léon', 'leon');
+    const cat = game.addPlayer('Chat', 'chat');
+    game.teleport(leon.id, 600, 420);
+    run(game, 60);
+    const l = me(game, leon.id);
+    press(game, leon.id, Button.Special, l.x, l.y);
+    run(game, Math.ceil(loadCharacterStats(ASSETS, 'leon').params.invisibleTime * TICK_RATE) + 2);
+    expect(me(game, leon.id).anim & Anim.Invisible).toBeFalsy();
+
+    run(game, 6 * TICK_RATE); // special cooldown
+    const l2 = me(game, leon.id);
+    press(game, leon.id, Button.Special, l2.x, l2.y);
+    expect(me(game, leon.id).anim & Anim.Invisible).toBeTruthy();
+    game.teleport(cat.id, l2.x - 40, l2.y);
+    run(game, 1);
+    press(game, cat.id, Button.Attack, l2.x, l2.y);
+    expect(me(game, leon.id).anim & Anim.Invisible).toBeFalsy();
+  });
+
+  it('his tongue pulls a player back to him and licks a groove in the cake', () => {
+    const game = newGame();
+    const leon = game.addPlayer('Léon', 'leon');
+    const victim = game.addPlayer('Victime', 'generic');
+    game.teleport(leon.id, 600, 420);
+    run(game, 60);
+    const l = me(game, leon.id);
+    game.teleport(victim.id, l.x + 125, l.y - 10);
+    run(game, 1);
+    press(game, leon.id, Button.Attack, l.x + 125, l.y - 10);
+    expect(me(game, victim.id).vx).toBeLessThan(-300);
+    expect(me(game, victim.id).anim & Anim.Stunned).toBeTruthy();
+    // Aimed down into the cake: a groove.
+    const solid = (): number => game.terrain.data.reduce((n, m) => n + (m !== 0 ? 1 : 0), 0);
+    run(game, TICK_RATE);
+    const before = solid();
+    const l2 = me(game, leon.id);
+    press(game, leon.id, Button.Attack, l2.x + 60, l2.y + 100);
+    expect(solid()).toBeLessThan(before - 200);
+  });
+});

+ 188 - 0
tests/fun.test.ts

@@ -0,0 +1,188 @@
+import { describe, expect, it } from 'vitest';
+import { loadCharacterStats, loadMap } from '../src/server/assets';
+import { Game } from '../src/server/game';
+import { Anim } from '../src/shared/characters';
+import { CHERRY_HOT_S, CHERRY_STEAL_BONUS, CRUSH_KILL_PIXELS, PIXELS_PER_METER, SURPRISE_DURATIONS, TICK_RATE } from '../src/shared/constants';
+import { Button } from '../src/shared/input';
+import type { FxEvent, SurpriseId } from '../src/shared/protocol';
+import { ASSETS, realMaterials } from './helpers';
+
+const materials = realMaterials();
+const PPM = PIXELS_PER_METER;
+
+function newRound(seed = 1, duration = 180): 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)!;
+const solid = (game: Game): number => game.terrain.data.reduce((n, m) => n + (m !== 0 ? 1 : 0), 0);
+
+interface CherryHandle {
+  body: { setPosition(p: { x: number; y: number }): void; setLinearVelocity(v: { x: number; y: number }): void };
+}
+const cherryOf = (game: Game): CherryHandle => (game as unknown as { cherry: CherryHandle }).cherry;
+
+describe('surprises', () => {
+  it('two of them happen during a round, at random times', () => {
+    // A short round keeps the test fast: surprises come between 25 s and 20 s before the end.
+    const game = newRound(3, 60);
+    const fx = run(game, 60 * TICK_RATE);
+    expect(fx.filter((e) => e.kind === 'surprise')).toHaveLength(2);
+  });
+
+  it('each one runs to its end without trouble, and the terrain stays consistent', () => {
+    for (const id of Object.keys(SURPRISE_DURATIONS) as SurpriseId[]) {
+      const game = newRound();
+      game.addPlayer('Témoin', 'generic');
+      run(game, 30);
+      game.startSurprise(id);
+      run(game, Math.ceil((SURPRISE_DURATIONS[id] + 1) * TICK_RATE));
+      expect(game.roundOver, id).toBe(false);
+    }
+  });
+
+  it('the cat paw scrapes the summit of the cake and sends whoever is up there flying', () => {
+    const game = newRound();
+    const { id } = game.addPlayer('Balayé', 'generic');
+    game.teleport(id, 1024, 240); // top tier, the summit
+    run(game, 60);
+    const before = solid(game);
+    game.startSurprise('cat-paw');
+    let flung = false;
+    for (let i = 0; i < SURPRISE_DURATIONS['cat-paw'] * TICK_RATE + 5; i++) {
+      run(game, 1);
+      if (Math.abs(me(game, id).vx) > 500) flung = true;
+    }
+    expect(flung).toBe(true);
+    expect(solid(game)).toBeLessThan(before);
+  });
+
+  it('the giant hand grabs a fistful of cake and tosses whoever stands there', () => {
+    const game = newRound(7);
+    const { id } = game.addPlayer('Attrapé', 'generic');
+    run(game, 10);
+    const before = solid(game);
+    const fx = run(game, 1).concat(((): FxEvent[] => {
+      game.startSurprise('giant-hand');
+      return run(game, 1);
+    })());
+    const hand = fx.find((e) => e.kind === 'surprise')!;
+    expect(hand).toMatchObject({ surprise: 'giant-hand' });
+    if (hand.kind !== 'surprise') return;
+    // Stand right where the hand comes down.
+    game.teleport(id, hand.x, hand.y - 20);
+    let tossed = false;
+    for (let i = 0; i < SURPRISE_DURATIONS['giant-hand'] * TICK_RATE; i++) {
+      run(game, 1);
+      if (me(game, id).vy < -600) tossed = true;
+    }
+    expect(tossed).toBe(true);
+    expect(solid(game)).toBeLessThan(before - 5000);
+  });
+
+  it('sugar sprinkles rain down and nibble the cake', () => {
+    const game = newRound();
+    run(game, 10);
+    const before = solid(game);
+    game.startSurprise('sprinkles');
+    const fx = run(game, (SURPRISE_DURATIONS.sprinkles + 2) * TICK_RATE);
+    expect(fx.filter((e) => e.kind === 'explosion').length).toBeGreaterThan(20);
+    expect(solid(game)).toBeLessThan(before);
+  });
+});
+
+describe('the living cherry', () => {
+  it('hops away from a player who comes close', () => {
+    const game = newRound();
+    const { id } = game.addPlayer('Chasseur', 'generic');
+    run(game, 2 * TICK_RATE); // the cherry lands on the top tier
+    const c = game.roundState().cherry!;
+    game.teleport(id, c.x - 70, c.y - 10);
+    const fx = run(game, 10);
+    expect(fx.some((e) => e.kind === 'cherryHop')).toBe(true);
+  });
+
+  it('hot potato: held too long, it explodes in the holder’s hands', () => {
+    const game = newRound();
+    const { id } = game.addPlayer('Gourmand', 'generic');
+    run(game, 2 * TICK_RATE);
+    const p = me(game, id);
+    cherryOf(game).body.setPosition({ x: p.x / PPM, y: p.y / PPM });
+    run(game, 2);
+    expect(game.roundState().cherry!.holder).toBe(id);
+    const fx = run(game, Math.ceil(CHERRY_HOT_S * TICK_RATE));
+    expect(fx).toContainEqual(expect.objectContaining({ kind: 'cherryBoom', id }));
+    expect(game.roundState().cherry!.holder).not.toBe(id);
+  });
+
+  it('knocking it out of someone’s hands and grabbing it is a steal: bonus points', () => {
+    const game = newRound();
+    const holder = game.addPlayer('Volé', 'generic');
+    const thief = game.addPlayer('Voleur', 'castor');
+    game.teleport(holder.id, 600, 420);
+    game.teleport(thief.id, 560, 420);
+    run(game, 60);
+    const h = me(game, holder.id);
+    cherryOf(game).body.setPosition({ x: h.x / PPM, y: h.y / PPM });
+    run(game, 2);
+    expect(game.roundState().cherry!.holder).toBe(holder.id);
+    // Bite: the cherry pops out; put it in the thief's mouth right away.
+    const t = me(game, thief.id);
+    game.setInput(thief.id, { buttons: Button.Attack, aimX: Math.round(h.x), aimY: Math.round(h.y) });
+    run(game, 1);
+    game.setInput(thief.id, { buttons: 0, aimX: 0, aimY: 0 });
+    expect(game.roundState().cherry!.holder).toBe(0);
+    cherryOf(game).body.setPosition({ x: t.x / PPM, y: t.y / PPM });
+    cherryOf(game).body.setLinearVelocity({ x: 0, y: 0 });
+    const fx = run(game, 2);
+    expect(fx).toContainEqual(expect.objectContaining({ kind: 'stolen', id: thief.id, from: holder.id, bonus: CHERRY_STEAL_BONUS }));
+    expect(me(game, thief.id).score).toBeGreaterThanOrEqual(CHERRY_STEAL_BONUS);
+  });
+});
+
+describe('cartoon hits', () => {
+  it('a small falling chunk flattens a player into a pancake instead of killing them', () => {
+    const game = newRound();
+    const { id } = game.addPlayer('Crêpe', 'generic');
+    game.teleport(id, 400, 680); // bottom tier, open sky above
+    run(game, 30);
+    // A small block of biscuit (under CRUSH_KILL_PIXELS) dropped from high above.
+    const { width, data } = game.terrain;
+    const side = Math.floor(Math.sqrt(CRUSH_KILL_PIXELS / 2));
+    // Built hanging in the air: it is not anchored, so the next detach search drops it.
+    for (let y = 300; y < 300 + side; y++) for (let x = 400 - side / 2; x < 400 + side / 2; x++) data[y * width + Math.round(x)] = 5;
+    game.terrain.markDirty({ x0: 300, y0: 280, x1: 500, y1: 300 + side + 10 });
+    game.queueOp({ kind: 'carve', x: 400, y: 300 + side, r: 2, power: 99 }); // triggers the detach search there
+    let crushedFlat = false;
+    for (let i = 0; i < 2 * TICK_RATE && !crushedFlat; i++) {
+      const res = game.step();
+      if (res.crushed.some((c) => c.id === id && c.flat)) crushedFlat = true;
+    }
+    expect(crushedFlat).toBe(true);
+    const p = me(game, id);
+    expect(p.anim & Anim.Flat).toBeTruthy();
+    expect(p.anim & Anim.Dead).toBe(0);
+  });
+
+  it('a player knocked into a wall goes SPLAF', () => {
+    const game = newRound();
+    const cat = game.addPlayer('Chat', 'chat');
+    const victim = game.addPlayer('Victime', 'generic');
+    game.teleport(cat.id, 420, 680); // bottom tier, middle tier's wall at x = 520
+    game.teleport(victim.id, 470, 680);
+    run(game, 30);
+    const c = me(game, cat.id);
+    game.setInput(cat.id, { buttons: Button.Special, aimX: 600, aimY: Math.round(c.y) });
+    run(game, 1);
+    game.setInput(cat.id, { buttons: 0, aimX: 600, aimY: Math.round(c.y) });
+    const fx = run(game, 30);
+    expect(fx).toContainEqual(expect.objectContaining({ kind: 'splat', id: victim.id }));
+  });
+});

+ 1 - 1
tests/net.test.ts

@@ -173,7 +173,7 @@ describe('LAN server (M3)', () => {
       for (const h of c.hashChecks) expect(h.mine).toBe(h.server);
     }
     expect(a.terrain.hash()).toBe(b.terrain.hash());
-  });
+  }, 15_000); // 600 ticks of real networking: slow when the whole suite runs in parallel
 
   it('a player leaving is announced and an empty server goes back to the lobby', async () => {
     const s = await startServer();

+ 70 - 3
tests/rules.test.ts

@@ -2,7 +2,7 @@ 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 { Anim, PLAYABLE_CHARACTER_IDS } from '../src/shared/characters';
 import { CHERRY_REGRAB_DELAY, FINAL_RUSH_S, MIN_CAKE_PIXELS, RESPAWN_DELAY_S, SMARTIES_DURATION_S, STUN_GUARD_S, TICK_RATE } from '../src/shared/constants';
 import { Button } from '../src/shared/input';
 import type { FxEvent } from '../src/shared/protocol';
@@ -77,12 +77,14 @@ describe('custard and the spoon', () => {
 
   it('the spoon finds the last little island of cake', () => {
     const game = newRound();
-    // Wipe the cake, plate excluded, except for a 120 px block on the far right.
+    // Wipe the cake, except for the plate and a 120 px block on the far right.
     const { width, height, data } = game.terrain;
     for (let y = 0; y < height; y++) {
       for (let x = 0; x < width; x++) {
         const i = y * width + x;
-        if (data[i] !== 255 && !(x >= 1600 && x < 1720 && y >= 820)) data[i] = 0;
+        // (The raised ends of the plate go too: they would be ledges as well.)
+        const plate = data[i] === 255 && x >= 220 && x < 1830;
+        if (!plate && !(x >= 1600 && x < 1720 && y >= 820 && data[i] !== 255)) data[i] = 0;
       }
     }
     game.terrain.markDirty({ x0: 0, y0: 0, x1: width, y1: height });
@@ -283,3 +285,68 @@ describe('trophies', () => {
     expect(t.find((x) => x.id === 'pyromaniac')).toBeUndefined();
   });
 });
+
+describe('getting up', () => {
+  /** Holds toward the wall and taps jump, like a player climbing; returns the highest y reached. */
+  function climb(game: Game, id: number, ticks: number): number {
+    let best = Infinity;
+    for (let i = 0; i < ticks; i++) {
+      const jump = i % 12 < 6 ? Button.Jump : 0;
+      game.setInput(id, { buttons: Button.Right | jump, aimX: 2000, aimY: 0 });
+      game.step();
+      best = Math.min(best, me(game, id).y);
+    }
+    return best;
+  }
+
+  it('every character can climb a tier wall by wall-jumping', () => {
+    for (const character of PLAYABLE_CHARACTER_IDS) {
+      const game = newRound();
+      const { id } = game.addPlayer('Grimpeur', character);
+      game.teleport(id, 470, 670); // bottom tier, against the middle tier's wall (x = 520, 230 px high)
+      run(game, 30);
+      expect(climb(game, id, 6 * TICK_RATE), character).toBeLessThan(470);
+    }
+  });
+
+  it('the cherry is heavy: its holder jumps lower', () => {
+    const jumpHeight = (holding: boolean): number => {
+      const game = newRound();
+      const { id } = game.addPlayer('Sauteur', 'generic');
+      game.teleport(id, 400, 680);
+      run(game, 30);
+      if (holding) {
+        const cherry = (game as unknown as { cherry: { body: { setPosition(p: { x: number; y: number }): void } } }).cherry;
+        const p = me(game, id);
+        cherry.body.setPosition({ x: p.x / 32, y: p.y / 32 });
+        run(game, 2);
+        expect(game.roundState().cherry!.holder).toBe(id);
+      }
+      const y0 = me(game, id).y;
+      game.setInput(id, { buttons: Button.Jump, aimX: 0, aimY: 0 });
+      let top = y0;
+      for (let i = 0; i < TICK_RATE; i++) {
+        game.step();
+        top = Math.min(top, me(game, id).y);
+      }
+      return y0 - top;
+    };
+    expect(jumpHeight(true)).toBeLessThan(jumpHeight(false) * 0.75);
+  });
+
+  it('a cherry that falls in the custard comes back on the cake, not always at the top', () => {
+    const tops = new Set<number>();
+    for (const seed of [1, 2, 3, 4]) {
+      const game = newRound(180, seed);
+      const cherry = (game as unknown as { cherry: { body: { setPosition(p: { x: number; y: number }): void } } }).cherry;
+      cherry.body.setPosition({ x: 100 / 32, y: 1010 / 32 });
+      run(game, 2);
+      const c = game.roundState().cherry!;
+      expect(c.y).toBeLessThan(game.custardLevel);
+      run(game, TICK_RATE); // it lands on something
+      expect(game.roundState().cherry!.y).toBeLessThan(game.custardLevel - 10);
+      tops.add(Math.round(c.y / 100));
+    }
+    expect(tops.size).toBeGreaterThan(1);
+  });
+});

+ 54 - 0
tests/updates.test.ts

@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import { compareVersions, newestBuild, parseAdvertisedRefs, parseManifest, rawFileUrl, sameElectronMajor } from '../src/main/updates';
+
+const sha = (c: string): string => c.repeat(40);
+
+describe('self-update helpers', () => {
+  it('compares versions numerically', () => {
+    expect(compareVersions('0.10.0', '0.9.9')).toBeGreaterThan(0);
+    expect(compareVersions('1.2.3', '1.2.3')).toBe(0);
+    expect(compareVersions('1.2.3', '1.3.0')).toBeLessThan(0);
+    expect(() => compareVersions('v1.2.3', '1.0.0')).toThrow();
+  });
+
+  it('parses the refs advertised by git smart HTTP', () => {
+    const body =
+      '001e# service=git-upload-pack\n0000' +
+      `00fa${sha('a')} refs/heads/main\0multi_ack thin-pack agent=git/2.47.3\n` +
+      `003f${sha('b')} refs/builds/v0.2.0\n` +
+      `003f${sha('c')} refs/tags/v0.2.0\n0000`;
+    const refs = parseAdvertisedRefs(body);
+    expect(refs.get('refs/heads/main')).toBe(sha('a'));
+    expect(refs.get('refs/builds/v0.2.0')).toBe(sha('b'));
+    expect(refs.get('refs/tags/v0.2.0')).toBe(sha('c'));
+  });
+
+  it('picks the newest build above the running version', () => {
+    const refs = new Map([
+      ['refs/builds/v0.2.0', sha('a')],
+      ['refs/builds/v0.10.0', sha('b')],
+      ['refs/builds/vbroken', sha('c')],
+      ['refs/tags/v9.0.0', sha('d')],
+    ]);
+    expect(newestBuild(refs, '0.1.0')).toEqual({ version: '0.10.0', sha: sha('b') });
+    expect(newestBuild(refs, '0.10.0')).toBeNull();
+  });
+
+  it('rejects unsafe or incomplete manifests', () => {
+    const file = { path: 'app.asar', size: 3, sha256: 'f'.repeat(64) };
+    const ok = { version: '0.2.0', electron: '38.8.6', files: [file] };
+    expect(parseManifest(ok, '0.2.0').files).toHaveLength(1);
+    expect(() => parseManifest(ok, '0.3.0')).toThrow(/expected 0.3.0/);
+    expect(() => parseManifest({ ...ok, files: [file, { ...file, path: '../evil.exe' }] }, '0.2.0')).toThrow(/unsafe/);
+    expect(() => parseManifest({ ...ok, files: [file, { ...file, path: 'C:/evil.exe' }] }, '0.2.0')).toThrow(/unsafe/);
+    expect(() => parseManifest({ ...ok, files: [{ ...file, path: 'assets/a.png' }] }, '0.2.0')).toThrow(/app.asar/);
+  });
+
+  it('builds raw URLs and compares Electron runtimes', () => {
+    expect(rawFileUrl('https://git.example/u/r', 'abc', 'app.asar.unpacked/node_modules/@scope/x.node')).toBe(
+      'https://git.example/u/r/raw/abc/app.asar.unpacked/node_modules/%40scope/x.node',
+    );
+    expect(sameElectronMajor('38.8.6', '38.1.0')).toBe(true);
+    expect(sameElectronMajor('39.0.0', '38.8.6')).toBe(false);
+  });
+});