Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(office): arcade floor with ten playable retro cabinets

rubenluetke10-beep4b4a2762dc9d
diff --git a/docs/agent-society/office-map.md b/docs/agent-society/office-map.md
index 82be990659..d5f5fcb655 100644
--- a/docs/agent-society/office-map.md
+++ b/docs/agent-society/office-map.md
@@ -133,9 +133,9 @@ A second floor for the coding agents that run in the Agentic IDE's terminal
panes. It shares the office's engine, style and controls; only the people and
the floor plan differ.
-- **Elevator**: the reception elevator is a checkpoint on both floors. Its
- panel offers "Up to the coding floor" in the agents office and "Down to the
- agents office" on the coding floor. The ride is a short door-like fade, and
+- **Elevator**: the reception elevator is a checkpoint on every floor. Its
+ call button opens the floor picker (see §5e; before the arcade floor it
+ simply went up or down). The ride is a short door-like fade, and
the person steps out at the elevator of the other floor. The floor survives
a remount of the stage.
- **Floor plan** (`buildOfficeLayout(agents, { variant: "coding" })`): one
@@ -262,6 +262,40 @@ maintainer's review of this reference before they follow: the lead suite, the
reception desk, the team room table and chairs, the lockers and
mirror, the coffee bar, the water cooler and the arcade.
+## 5e. Arcade floor (2026-10-02)
+
+A third floor on top of the building: a retro arcade hall with ten playable
+cabinets. No agents work here; it is a place for the person (and their pet,
+which follows like on the coding floor).
+
+- **Elevator**: pressing the call button (click, or E at the doors) opens a
+ floor picker (`ElevatorPanel.tsx`) that lists all three floors top first;
+ a click, Enter on the focused floor or the floor's number key (0 agents,
+ 1 coding, 2 arcade) rides there, Escape closes it. The call button shows
+ up, down or both arrows depending on the floor (`callDirection`).
+- **Floor plan** (`arcade/arcadeFloorLayout.ts`, `buildArcadeLayout()`): a
+ fixed hall with the main room, a prize counter corner and a snack bar by
+ the elevator. Cabinets are furniture of kind `retroCabinet` with the id
+ `cabinet-<gameId>`; the person plays standing 0.85 m in front of one
+ (`OfficePlayer` nearest-interactable, E opens it). Tests prove every play
+ spot is reachable from the elevator.
+- **Look** (`arcade/ArcadeHall.tsx`, `ArcadeHallProps.tsx`,
+ `arcadeHallLook.ts`, `arcadeScreens.ts`): blacklight carpet, neon from
+ self-lit materials (one shadow light, three small point lights), merged
+ geometry per machine, two-frame attract screens on every cabinet; the
+ cabinet the person stands at shows its game's title screen live.
+- **Games** (`arcade/games/*.ts`, contract in `arcade/retroGame.ts`, registry
+ in `arcade/arcadeGames.ts`): Neon Snake, Brick Breaker, Paddle Duel, Block
+ Drop, Maze Muncher, Desert Dash, Pixel Raiders, Road Hopper and City
+ Defense are original Canvas 2D games (pure state + fixed 60 Hz step, no
+ assets, no ROMs), code-split and loaded on first play. Asteroid Run, the
+ break room's 3D game, has a cabinet here too.
+- **Cabinet overlay** (`arcade/RetroArcadeOverlay.tsx`): a modal at the
+ cabinet with marquee, crisp integer scaling, start / pause (P, blur) /
+ game over, best score per game in localStorage, keyboard, gamepad, mouse
+ where a game aims with it, and a touch pad on coarse pointers. Escape or E
+ leaves.
+
## 6. Plan
1. First map (done 2026-09-28).
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/ArcadeHall.tsx b/jarvis/ui/web/frontend/src/components/society/arcade/ArcadeHall.tsx
new file mode 100644
index 0000000000..f0edbee4e4
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/ArcadeHall.tsx
@@ -0,0 +1,442 @@
+/**
+ * The arcade floor: a neon-lit 80s/90s arcade hall floating in a violet
+ * night — the top floor of the building. A blacklight carpet, two midnight
+ * back walls with neon signs (the camera looks in from the south-east like
+ * into a doll's house; the walls are one-sided, so from behind they vanish),
+ * glass railings on the open sides, the prize corner and the snack bar, and
+ * every machine of the layout.
+ *
+ * Renders everything floor-specific; OfficeScene adds the person, the
+ * camera, the elevator's call button and the checkpoint marker on top.
+ *
+ * Light budget: one shadow-casting sun, a hemisphere and an ambient light
+ * and three small point lights. The neon look comes from self-lit materials.
+ * Screens: every cabinet shows its game's two-frame attract screen (flipped
+ * by moving a texture offset, nothing redrawn); the cabinet the person stands
+ * at runs its game's own title screen live, a dozen frames a second.
+ */
+import { useEffect, useMemo, useRef, useState } from "react";
+import { Stars } from "@react-three/drei";
+import { useFrame, type ThreeEvent } from "@react-three/fiber";
+import {
+ AdditiveBlending, BoxGeometry, Color, InstancedMesh, MeshBasicMaterial, MeshStandardMaterial, Object3D, PlaneGeometry, RepeatWrapping,
+ type BufferGeometry, type Texture,
+} from "three";
+import { useT } from "@/i18n";
+import { cachedCanvasTexture } from "../office/canvasMaterials";
+import { Box, Railing } from "../office/OfficeFurniture";
+import { FurniturePiece } from "../office/OfficeProps";
+import { RoomSign, RoomWalls } from "../office/OfficeRooms";
+import type { Furniture, OfficeLayout, Point, Rect, Room } from "../office/officeLayout";
+import { ARCADE_GAMES, gameForCabinet, isRetroGame, loadRetroGame } from "./arcadeGames";
+import { ARCADE_WALL_INSET, arcadeDecor } from "./arcadeFloorLayout";
+import {
+ CARPET_METRES, drawCarpet, drawGlowSpot, drawPrizeCarpet, drawSnackFloor, drawWallPanels, HALL, HALL_MAT, PartKit, ROOM_FLOOR_METRES,
+} from "./arcadeHallLook";
+import { CABINET_SCREEN } from "./ArcadeHallProps";
+import { createLiveScreen, medallionMaterial, neonMaterial, setScreenFrame, type LiveScreen, type NeonSymbol } from "./arcadeScreens";
+
+export interface ArcadeHallProps {
+ layout: OfficeLayout;
+ onFloorClick: (event: ThreeEvent<MouseEvent>) => void;
+ /** Furniture id of the cabinet the person stands at, or null. */
+ nearCabinet: string | null;
+ awake: boolean;
+ reduced: boolean;
+}
+
+/** Height of the back walls. */
+const WALL_H = 3.0;
+/** Seconds each attract frame stays on the cabinets' screens. */
+const ATTRACT_FRAME_S = 0.6;
+/** Seconds between two steps of the dance pad's light chase. */
+const PAD_STEP_S = 0.45;
+
+/** A cached base texture, cloned per surface with its own repeat (the clone belongs to the caller). */
+function repeated(base: Texture | null, repeatX: number, repeatY: number): Texture | null {
+ if (!base) return null;
+ const map = base.clone();
+ map.wrapS = map.wrapT = RepeatWrapping;
+ map.anisotropy = 8;
+ map.repeat.set(repeatX, repeatY);
+ map.needsUpdate = true;
+ return map;
+}
+
+// ---------------------------------------------------------------------------
+// Slab, carpets, walls
+// ---------------------------------------------------------------------------
+
+const RIM = new MeshBasicMaterial({ color: HALL.rim, toneMapped: false });
+const STRIP = {
+ magenta: new MeshBasicMaterial({ color: HALL.neon.magenta, toneMapped: false }),
+ cyan: new MeshBasicMaterial({ color: HALL.neon.cyan, toneMapped: false }),
+};
+const UNIT_PLANE = new PlaneGeometry(1, 1);
+const UNIT_BOX = new BoxGeometry(1, 1, 1);
+/** The dance pad's dark frame between its lit tiles. */
+const PAD_BASE = new MeshStandardMaterial({ color: "#07060d", roughness: 0.4 });
+
+/** The slab: a dark edge with a glowing rim, and the blacklight carpet everyone walks (and clicks) on. */
+function HallSlab({ layout, onFloorClick }: { layout: OfficeLayout; onFloorClick: (event: ThreeEvent<MouseEvent>) => void }) {
+ const { minX, maxX, minZ, maxZ } = layout.bounds;
+ const w = maxX - minX, d = maxZ - minZ, cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2;
+ const carpet = useMemo(() => {
+ const map = repeated(cachedCanvasTexture("arcade:carpet", 512, 512, drawCarpet), w / CARPET_METRES, d / CARPET_METRES);
+ // The neon fibres glow faintly under the "blacklight"; the near-black ground barely does.
+ return new MeshStandardMaterial({
+ color: map ? "#ffffff" : HALL.carpet.base, map, roughness: 0.95,
+ emissive: map ? "#ffffff" : "#000000", emissiveMap: map, emissiveIntensity: 0.22,
+ });
+ }, [w, d]);
+ const edge = useMemo(() => new MeshStandardMaterial({ color: HALL.slabEdge, roughness: 0.8 }), []);
+ useEffect(() => () => { carpet.map?.dispose(); carpet.dispose(); edge.dispose(); }, [carpet, edge]);
+ const glow = 0.05;
+ return (
+ <group>
+ <Box size={[w, 0.6, d]} position={[cx, -0.3, cz]} material={edge} cast={false} />
+ {/* The rim runs just below the floor's edge on all four sides. */}
+ <mesh geometry={UNIT_BOX} material={RIM} position={[cx, -0.06, maxZ]} scale={[w + glow, glow, glow]} />
+ <mesh geometry={UNIT_BOX} material={RIM} position={[maxX, -0.06, cz]} scale={[glow, glow, d + glow]} />
+ <mesh geometry={UNIT_BOX} material={RIM} position={[cx, -0.06, minZ]} scale={[w + glow, glow, glow]} />
+ <mesh geometry={UNIT_BOX} material={RIM} position={[minX, -0.06, cz]} scale={[glow, glow, d + glow]} />
+ <mesh position={[cx, 0.001, cz]} rotation={[-Math.PI / 2, 0, 0]} material={carpet} receiveShadow onClick={onFloorClick}>
+ <planeGeometry args={[w, d]} />
+ </mesh>
+ </group>
+ );
+}
+
+/** The prize corner's plum star carpet and the snack bar's diner checker, laid over the hall's carpet. */
+function RoomCarpet({ room, onFloorClick }: { room: Room; onFloorClick: (event: ThreeEvent<MouseEvent>) => void }) {
+ const w = room.maxX - room.minX, d = room.maxZ - room.minZ;
+ const material = useMemo(() => {
+ const prizes = room.kind === "prizes";
+ const base = cachedCanvasTexture(`arcade:floor:${room.kind}`, 256, 256, prizes ? drawPrizeCarpet : drawSnackFloor);
+ const map = repeated(base, w / ROOM_FLOOR_METRES, d / ROOM_FLOOR_METRES);
+ return new MeshStandardMaterial({ color: map ? "#ffffff" : prizes ? HALL.prizes.base : HALL.snack.red, map, roughness: prizes ? 0.95 : 0.4 });
+ }, [room.kind, w, d]);
+ useEffect(() => () => { material.map?.dispose(); material.dispose(); }, [material]);
+ return (
+ <mesh position={[(room.minX + room.maxX) / 2, 0.004, (room.minZ + room.maxZ) / 2]} rotation={[-Math.PI / 2, 0, 0]}
+ material={material} receiveShadow onClick={onFloorClick}>
+ <planeGeometry args={[w, d]} />
+ </mesh>
+ );
+}
+
+interface NeonSign { symbol: NeonSymbol; wall: "north" | "west"; along: number; y: number; size: number }
+
+/** Where the neon signs hang: over the prize counter, the pinballs, both ends of cabinet row A, the dance pad, the claws and the snack bar. */
+function neonSigns(layout: OfficeLayout): NeonSign[] {
+ const at = (id: string): Point | null => layout.furniture.find((f) => f.id === id) ?? null;
+ const room = (kind: Room["kind"]) => layout.rooms.find((r) => r.kind === kind) ?? null;
+ const signs: NeonSign[] = [];
+ const prizes = room("prizes"), snack = room("snack"), hall = room("arcade");
+ if (prizes) signs.push({ symbol: "ticket", wall: "north", along: (prizes.minX + prizes.maxX) / 2, y: 2.72, size: 0.62 });
+ const pinball = at("pinball-1");
+ if (pinball) signs.push({ symbol: "bolt", wall: "north", along: pinball.x, y: 2.45, size: 0.95 });
+ const rowA = layout.furniture.filter((f) => f.kind === "retroCabinet" && f.rotationY === 0 && hall && f.z < hall.minZ + 1.5);
+ if (rowA.length > 0) {
+ const xs = rowA.map((f) => f.x);
+ signs.push({ symbol: "joystick", wall: "north", along: Math.min(...xs) - 0.95, y: 2.35, size: 0.9 });
+ signs.push({ symbol: "star", wall: "north", along: Math.max(...xs) + 0.95, y: 2.35, size: 0.9 });
+ }
+ if (hall) signs.push({ symbol: "alien", wall: "north", along: hall.maxX - 2.7, y: 2.2, size: 1.2 });
+ const claws = layout.furniture.filter((f) => f.kind === "clawMachine");
+ if (claws.length > 0) signs.push({ symbol: "claw", wall: "west", along: claws.reduce((s, c) => s + c.z, 0) / claws.length, y: 2.45, size: 0.9 });
+ if (snack) {
+ signs.push({ symbol: "coin", wall: "west", along: snack.minZ + 1.4, y: 2.1, size: 0.8 });
+ signs.push({ symbol: "soda", wall: "west", along: snack.minZ + 4.4, y: 2.2, size: 1.0 });
+ }
+ return signs;
+}
+
+/** The north and west walls: midnight panels with neon strips along the top and the foot, and the neon signs. */
+function BackWalls({ layout }: { layout: OfficeLayout }) {
+ const { minX, maxX, minZ, maxZ } = layout.bounds;
+ const west = minX + ARCADE_WALL_INSET, east = maxX - ARCADE_WALL_INSET, north = minZ + ARCADE_WALL_INSET, south = maxZ - ARCADE_WALL_INSET;
+ const northLen = east - west, westLen = south - north;
+ const [northWall, westWall] = useMemo(() => {
+ const base = cachedCanvasTexture("arcade:wall", 256, 256, drawWallPanels);
+ const make = (length: number) => {
+ const map = repeated(base, length / 2.4, 1);
+ return new MeshStandardMaterial({ color: map ? "#ffffff" : HALL.wall.base, map, roughness: 0.85 });
+ };
+ return [make(northLen), make(westLen)];
+ }, [northLen, westLen]);
+ useEffect(() => () => { for (const m of [northWall, westWall]) { m.map?.dispose(); m.dispose(); } }, [northWall, westWall]);
+ const signs = useMemo(() => neonSigns(layout), [layout]);
+ const strip = (key: string, wall: "north" | "west", y: number, h: number, material: MeshBasicMaterial) => wall === "north"
+ ? <mesh key={key} geometry={UNIT_PLANE} material={material} position={[(west + east) / 2, y, north + 0.012]} scale={[northLen, h, 1]} />
+ : <mesh key={key} geometry={UNIT_PLANE} material={material} position={[west + 0.012, y, (north + south) / 2]} rotation={[0, Math.PI / 2, 0]}
+ scale={[westLen, h, 1]} />;
+ return (
+ <group>
+ {/* One-sided planes facing into the hall: from outside (an orbiting camera) the walls disappear. */}
+ <mesh position={[(west + east) / 2, WALL_H / 2, north]} material={northWall} receiveShadow>
+ <planeGeometry args={[northLen, WALL_H]} />
+ </mesh>
+ <mesh position={[west, WALL_H / 2, (north + south) / 2]} rotation={[0, Math.PI / 2, 0]} material={westWall} receiveShadow>
+ <planeGeometry args={[westLen, WALL_H]} />
+ </mesh>
+ {strip("n-top", "north", WALL_H - 0.12, 0.045, STRIP.magenta)}
+ {strip("w-top", "west", WALL_H - 0.12, 0.045, STRIP.magenta)}
+ {strip("n-foot", "north", 0.16, 0.03, STRIP.cyan)}
+ {strip("w-foot", "west", 0.16, 0.03, STRIP.cyan)}
+ {signs.map((sign) => (
+ <mesh key={sign.symbol} geometry={UNIT_PLANE} material={neonMaterial(sign.symbol)} scale={[sign.size, sign.size, 1]}
+ position={sign.wall === "north" ? [sign.along, sign.y, north + 0.02] : [west + 0.02, sign.y, sign.along]}
+ rotation={sign.wall === "north" ? [0, 0, 0] : [0, Math.PI / 2, 0]} />
+ ))}
+ <Railing from={[west, south]} to={[east, south]} />
+ <Railing from={[east, south]} to={[east, north]} />
+ </group>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Lights
+// ---------------------------------------------------------------------------
+
+function HallLights({ layout }: { layout: OfficeLayout }) {
+ const { minX, maxX, minZ, maxZ } = layout.bounds;
+ const span = Math.max(maxX - minX, maxZ - minZ);
+ const hall = layout.rooms.find((r) => r.kind === "arcade");
+ const prizes = layout.rooms.find((r) => r.kind === "prizes");
+ const hockey = layout.furniture.find((f) => f.kind === "airHockey");
+ return (
+ <>
+ <hemisphereLight args={[HALL.sky, HALL.ground, 0.8]} />
+ <ambientLight intensity={0.2} />
+ <directionalLight position={[maxX + 10, 26, maxZ + 6]} intensity={1.15} color={HALL.sun} castShadow
+ shadow-mapSize={[2048, 2048]} shadow-bias={-0.0004} shadow-normalBias={0.03}
+ shadow-camera-left={-span * 0.7} shadow-camera-right={span * 0.7}
+ shadow-camera-top={span * 0.7} shadow-camera-bottom={-span * 0.7} shadow-camera-far={120} />
+ {hall && <pointLight position={[(hall.minX + hall.maxX) / 2, 2.9, hall.minZ + 4]} color={HALL.neon.magenta} intensity={9} distance={10} decay={2} />}
+ {prizes && <pointLight position={[(prizes.minX + prizes.maxX) / 2, 2.6, prizes.maxZ]} color="#ffb36b" intensity={7} distance={8} decay={2} />}
+ {hockey && <pointLight position={[hockey.x, 2.4, hockey.z]} color={HALL.neon.cyan} intensity={6} distance={8} decay={2} />}
+ </>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Floor decor
+// ---------------------------------------------------------------------------
+
+let tableGeometry: BufferGeometry | null = null;
+/** A bistro table on a chrome pedestal with three red stools round it, inside the layout's SNACK_TABLE_HALF footprint. */
+function bistroTable(): BufferGeometry {
+ if (!tableGeometry) {
+ const kit = new PartKit();
+ kit.cylinder(0.22, 0.03, [0, 0.015, 0], HALL.chrome, { segments: 18 });
+ kit.cylinder(0.04, 0.7, [0, 0.38, 0], HALL.chrome, { segments: 10 });
+ kit.cylinder(0.37, 0.03, [0, 0.735, 0], HALL.chrome, { segments: 24 });
+ kit.cylinder(0.35, 0.02, [0, 0.755, 0], HALL.snack.cream, { segments: 24 });
+ for (let i = 0; i < 3; i += 1) {
+ const a = (i / 3) * Math.PI * 2 + Math.PI / 6;
+ const x = Math.cos(a) * 0.45, z = Math.sin(a) * 0.45;
+ kit.cylinder(0.13, 0.02, [x, 0.01, z], HALL.chrome, { segments: 14 });
+ kit.cylinder(0.022, 0.6, [x, 0.31, z], HALL.chrome, { segments: 8 });
+ kit.cylinder(0.16, 0.07, [x, 0.635, z], "#c0392b", { segments: 18 });
+ }
+ tableGeometry = kit.build();
+ }
+ return tableGeometry;
+}
+
+function SnackTables({ tables }: { tables: Point[] }) {
+ const geometry = bistroTable();
+ return <>{tables.map((t) => <mesh key={`${t.x}:${t.z}`} geometry={geometry} material={HALL_MAT.gloss} position={[t.x, 0, t.z]} castShadow receiveShadow />)}</>;
+}
+
+const PAD_TILES = 4;
+const PAD_COLOURS = [HALL.neon.magenta, HALL.neon.cyan, HALL.neon.yellow, HALL.neon.green, HALL.neon.violet];
+
+/** Light step `n` of the pad's chase: every third diagonal bright, the rest dimmed. */
+function paintPad(mesh: InstancedMesh, bright: Color[], dim: Color[], n: number): void {
+ for (let r = 0; r < PAD_TILES; r += 1) {
+ for (let c = 0; c < PAD_TILES; c += 1) {
+ const k = (r + c + n) % PAD_COLOURS.length;
+ mesh.setColorAt(r * PAD_TILES + c, (r + c + n) % 3 === 0 ? bright[k] : dim[k]);
+ }
+ }
+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
+}
+
+/** A light-up dance floor of 4 × 4 tiles; the colours chase diagonally while the floor is awake. */
+function DancePad({ pad, animate }: { pad: Rect; animate: boolean }) {
+ const w = pad.maxX - pad.minX, d = pad.maxZ - pad.minZ;
+ const tile = Math.min(w, d) / PAD_TILES;
+ const { mesh, bright, dim } = useMemo(() => {
+ const geometry = new PlaneGeometry(tile * 0.9, tile * 0.9).rotateX(-Math.PI / 2);
+ const material = new MeshBasicMaterial({ color: "#ffffff", toneMapped: false });
+ const made = new InstancedMesh(geometry, material, PAD_TILES * PAD_TILES);
+ const dummy = new Object3D();
+ for (let r = 0; r < PAD_TILES; r += 1) {
+ for (let c = 0; c < PAD_TILES; c += 1) {
+ dummy.position.set(pad.minX + (c + 0.5) * tile, 0.008, pad.minZ + (r + 0.5) * tile);
+ dummy.updateMatrix();
+ made.setMatrixAt(r * PAD_TILES + c, dummy.matrix);
+ }
+ }
+ made.instanceMatrix.needsUpdate = true;
+ made.computeBoundingSphere();
+ return {
+ mesh: made,
+ bright: PAD_COLOURS.map((c) => new Color(c)),
+ dim: PAD_COLOURS.map((c) => new Color(c).multiplyScalar(0.28)),
+ };
+ }, [pad.minX, pad.minZ, tile]);
+ const step = useRef(0);
+ const since = useRef(0);
+ useEffect(() => paintPad(mesh, bright, dim, step.current), [mesh, bright, dim]);
+ useEffect(() => () => { mesh.geometry.dispose(); (mesh.material as MeshBasicMaterial).dispose(); mesh.dispose(); }, [mesh]);
+ useFrame((_, dt) => {
+ if (!animate) return;
+ since.current += dt;
+ if (since.current < PAD_STEP_S) return;
+ since.current = 0;
+ step.current += 1;
+ paintPad(mesh, bright, dim, step.current);
+ });
+ return (
+ <group>
+ <mesh position={[(pad.minX + pad.maxX) / 2, 0.004, (pad.minZ + pad.maxZ) / 2]} rotation={[-Math.PI / 2, 0, 0]} material={PAD_BASE} receiveShadow>
+ <planeGeometry args={[w, d]} />
+ </mesh>
+ <primitive object={mesh} />
+ </group>
+ );
+}
+
+function Medallion({ at }: { at: Point & { r: number } }) {
+ if (at.r <= 0) return null;
+ return (
+ <mesh position={[at.x, 0.006, at.z]} rotation={[-Math.PI / 2, 0, 0]} material={medallionMaterial()} renderOrder={1}>
+ <planeGeometry args={[at.r * 2, at.r * 2]} />
+ </mesh>
+ );
+}
+
+/** The coloured pool of light each cabinet throws on the carpet in front of it; one instanced draw for all of them. */
+function CabinetGlows({ cabinets }: { cabinets: Furniture[] }) {
+ const mesh = useMemo(() => {
+ const map = cachedCanvasTexture("arcade:glow-spot", 128, 128, drawGlowSpot);
+ const material = new MeshBasicMaterial({
+ map, color: "#ffffff", transparent: true, opacity: map ? 1 : 0, depthWrite: false, blending: AdditiveBlending, toneMapped: false,
+ });
+ const made = new InstancedMesh(new PlaneGeometry(1, 1).rotateX(-Math.PI / 2), material, Math.max(1, cabinets.length));
+ const dummy = new Object3D();
+ const colour = new Color();
+ cabinets.forEach((cabinet, i) => {
+ const ahead = 0.75;
+ dummy.position.set(cabinet.x + Math.sin(cabinet.rotationY) * ahead, 0.012, cabinet.z + Math.cos(cabinet.rotationY) * ahead);
+ dummy.rotation.set(0, cabinet.rotationY, 0);
+ dummy.scale.set(1.15, 1, 0.95);
+ dummy.updateMatrix();
+ made.setMatrixAt(i, dummy.matrix);
+ made.setColorAt(i, colour.set(gameForCabinet(cabinet.id)?.look.accent ?? HALL.neon.violet));
+ });
+ made.count = cabinets.length;
+ made.instanceMatrix.needsUpdate = true;
+ if (made.instanceColor) made.instanceColor.needsUpdate = true;
+ made.computeBoundingSphere();
+ return made;
+ }, [cabinets]);
+ useEffect(() => () => { mesh.geometry.dispose(); (mesh.material as MeshBasicMaterial).dispose(); mesh.dispose(); }, [mesh]);
+ return <primitive object={mesh} />;
+}
+
+// ---------------------------------------------------------------------------
+// Screens
+// ---------------------------------------------------------------------------
+
+/** Flips every attract screen between its two frames; neighbours in the registry run out of step. */
+function AttractScreens({ animate }: { animate: boolean }) {
+ const since = useRef(0);
+ const frame = useRef<0 | 1>(0);
+ useFrame((_, dt) => {
+ if (!animate) return;
+ since.current += dt;
+ if (since.current < ATTRACT_FRAME_S) return;
+ since.current = 0;
+ frame.current = frame.current === 0 ? 1 : 0;
+ for (let i = 0; i < ARCADE_GAMES.length; i += 1) setScreenFrame(ARCADE_GAMES[i], ((frame.current + i) % 2) as 0 | 1);
+ });
+ return null;
+}
+
+const PREVIEW_GEOMETRY = new PlaneGeometry(CABINET_SCREEN.w, CABINET_SCREEN.h);
+
+/**
+ * The cabinet the person stands at shows its game's own title screen, live.
+ * A game whose code fails to load (or is still being written) keeps its
+ * static attract screen: the preview is decoration, the overlay reports
+ * real load errors when the person starts the game.
+ */
+function LivePreview({ cabinet }: { cabinet: Furniture }) {
+ const game = gameForCabinet(cabinet.id);
+ const [screen, setScreen] = useState<LiveScreen | null>(null);
+ useEffect(() => {
+ if (!game || !isRetroGame(game.id)) return undefined;
+ let alive = true;
+ let made: LiveScreen | null = null;
+ loadRetroGame(game.id).then((retro) => {
+ if (!alive) return;
+ made = createLiveScreen(retro);
+ setScreen(made);
+ }, () => {
+ // See above: no preview, the static attract screen stays.
+ });
+ return () => {
+ alive = false;
+ made?.dispose();
+ };
+ }, [game]);
+ useFrame((_, dt) => screen?.tick(dt));
+ if (!screen) return null;
+ return (
+ <group position={[cabinet.x, 0, cabinet.z]} rotation={[0, cabinet.rotationY, 0]}>
+ <mesh geometry={PREVIEW_GEOMETRY} material={screen.material} position={[0, CABINET_SCREEN.y, CABINET_SCREEN.z + 0.003]}
+ rotation={[CABINET_SCREEN.tilt, 0, 0]} />
+ </group>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// The hall
+// ---------------------------------------------------------------------------
+
+export function ArcadeHall({ layout, onFloorClick, nearCabinet, awake, reduced }: ArcadeHallProps) {
+ const t = useT();
+ const background = useMemo(() => new Color(HALL.space), []);
+ const { minX, maxX, minZ, maxZ } = layout.bounds;
+ const span = Math.max(maxX - minX, maxZ - minZ);
+ const cabinets = useMemo(() => layout.furniture.filter((f) => f.kind === "retroCabinet"), [layout]);
+ const decor = useMemo(() => arcadeDecor(layout.rooms), [layout]);
+ const near = nearCabinet ? cabinets.find((c) => c.id === nearCabinet) ?? null : null;
+ const animate = awake && !reduced;
+ return (
+ <>
+ <primitive attach="background" object={background} />
+ <fog attach="fog" args={[HALL.space, span * 2.2, span * 4.5]} />
+ <Stars radius={span * 3} depth={span} count={2200} factor={4} saturation={0.35} fade speed={reduced ? 0 : 0.3} />
+ <HallLights layout={layout} />
+ <HallSlab layout={layout} onFloorClick={onFloorClick} />
+ {layout.rooms.filter((r) => r.kind === "prizes" || r.kind === "snack").map((room) => (
+ <RoomCarpet key={room.id} room={room} onFloorClick={onFloorClick} />
+ ))}
+ <BackWalls layout={layout} />
+ <RoomWalls walls={layout.walls} />
+ {layout.rooms.map((room) => <RoomSign key={room.id} room={room} label={t(`society.office.room_${room.kind}`)} />)}
+ {layout.furniture.map((item) => <FurniturePiece key={item.id} item={item} />)}
+ <SnackTables tables={decor.tables} />
+ <DancePad pad={decor.pad} animate={animate} />
+ <Medallion at={decor.medallion} />
+ <CabinetGlows cabinets={cabinets} />
+ <AttractScreens animate={animate} />
+ {near && animate && <LivePreview key={near.id} cabinet={near} />}
+ </>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/ArcadeHallProps.tsx b/jarvis/ui/web/frontend/src/components/society/arcade/ArcadeHallProps.tsx
new file mode 100644
index 0000000000..ea6954cb13
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/ArcadeHallProps.tsx
@@ -0,0 +1,410 @@
+/**
+ * The arcade floor's machines (merged into PROP_RENDERERS): the playable
+ * upright cabinets, the prize counter, the token changer, claw machines,
+ * the air-hockey table, pinball machines and the snack-bar counter.
+ *
+ * Every piece is built in local space centred on the origin, front facing
+ * +z, inside its FURNITURE_SIZE box. Matte parts of a piece are baked into
+ * one vertex-coloured geometry and its lights into another (arcadeHallLook's
+ * PartKit), built once per kind — per game for cabinets — and shared by every
+ * copy; faces and screens are cached canvas materials (arcadeScreens). So a
+ * cabinet costs four draw calls however much detail it has.
+ */
+import { BoxGeometry, PlaneGeometry, type BufferGeometry, type Material } from "three";
+import type { Furniture, FurnitureKind } from "../office/officeLayout";
+import { gameForCabinet, type ArcadeGameInfo } from "./arcadeGames";
+import { HALL, HALL_MAT, lcg, PartKit, type Vec3 } from "./arcadeHallLook";
+import { BLANK_LOOK, FACES, marqueeMaterial, screenMaterial } from "./arcadeScreens";
+
+/** Where a cabinet's screen sits in the cabinet's own space (front +z): centre, size and backward lean. */
+export const CABINET_SCREEN = { y: 1.38, z: 0.064, w: 0.5, h: 0.375, tilt: -0.12 } as const;
+/** The lit marquee above the screen. */
+const CABINET_MARQUEE = { y: 1.82, z: 0.062, w: 0.64, h: 0.16 } as const;
+
+const GEO = {
+ screen: new PlaneGeometry(CABINET_SCREEN.w, CABINET_SCREEN.h),
+ marquee: new PlaneGeometry(CABINET_MARQUEE.w, CABINET_MARQUEE.h),
+ box: new BoxGeometry(1, 1, 1),
+ plane: new PlaneGeometry(1, 1),
+};
+
+/** A stable small hash of an id, to vary machines of the same kind. */
+function variantOf(id: string, count: number): number {
+ let hash = 0;
+ for (const ch of id) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0;
+ return hash % count;
+}
+
+/** A self-lit or glass face: a unit plane scaled to `size`. */
+function Face({ size, position, rotation, material }: {
+ size: [number, number]; position: Vec3; rotation?: Vec3; material: Material;
+}) {
+ return <mesh geometry={GEO.plane} material={material} position={position} rotation={rotation} scale={[size[0], size[1], 1]} />;
+}
+
+/** A glass box: a unit cube scaled to `size`. */
+function Glass({ size, position }: { size: Vec3; position: Vec3 }) {
+ return <mesh geometry={GEO.box} material={HALL_MAT.glass} position={position} scale={size} />;
+}
+
+/** The two baked geometries of a piece: matte paint and lights. */
+interface Baked { paint: BufferGeometry; glow: BufferGeometry }
+
+function BakedPiece({ baked, gloss = false }: { baked: Baked; gloss?: boolean }) {
+ return (
+ <>
+ <mesh geometry={baked.paint} material={gloss ? HALL_MAT.gloss : HALL_MAT.paint} castShadow receiveShadow />
+ <mesh geometry={baked.glow} material={HALL_MAT.glow} />
+ </>
+ );
+}
+
+const bakedCache = new Map<string, Baked>();
+
+/** Build a piece's two geometries once per key; every copy of the piece draws from the same buffers. */
+function bake(key: string, build: (paint: PartKit, glow: PartKit) => void): Baked {
+ let baked = bakedCache.get(key);
+ if (!baked) {
+ const paint = new PartKit(), glow = new PartKit();
+ build(paint, glow);
+ baked = { paint: paint.build(), glow: glow.build() };
+ bakedCache.set(key, baked);
+ }
+ return baked;
+}
+
+/** Plush toys: a squashed body, a head and two round ears, each in one colour. */
+function plush(kit: PartKit, x: number, y: number, z: number, r: number, colour: string): void {
+ kit.sphere(r, [x, y + r * 0.9, z], colour, [1, 0.9, 0.9], 9);
+ const head = y + r * 1.75;
+ kit.sphere(r * 0.75, [x, head, z + r * 0.05], colour, undefined, 9);
+ kit.sphere(r * 0.28, [x - r * 0.5, head + r * 0.6, z], colour, undefined, 6);
+ kit.sphere(r * 0.28, [x + r * 0.5, head + r * 0.6, z], colour, undefined, 6);
+}
+
+// ---------------------------------------------------------------------------
+// Retro cabinet
+// ---------------------------------------------------------------------------
+
+/**
+ * A classic upright: side panels in the game's body colour with two racing
+ * stripes, neon T-molding along their front edges, a slanted control panel
+ * with a joystick and two buttons, a coin door with lit slots, the tube in a
+ * black bezel and the lit marquee on top.
+ */
+function cabinetParts(game: ArcadeGameInfo | null): Baked {
+ const look = game?.look ?? BLANK_LOOK;
+ return bake(`arcade:cabinet:${game?.id ?? "blank"}`, (paint, glow) => {
+ const tilt = 0.22;
+ for (const side of [-1, 1]) {
+ const x = side * 0.3575;
+ paint.box([0.035, 0.98, 0.69], [x, 0.49, -0.045], look.body);
+ paint.box([0.035, 0.94, 0.51], [x, 1.45, -0.135], look.body);
+ const sx = side * 0.378;
+ paint.box([0.006, 0.07, 0.62], [sx, 0.55, -0.05], look.accent, [0.55, 0, 0]);
+ paint.box([0.006, 0.07, 0.62], [sx, 0.75, -0.05], look.marqueeText, [0.55, 0, 0]);
+ paint.box([0.006, 0.06, 0.4], [sx, 1.5, -0.14], look.accent, [0.55, 0, 0]);
+ glow.box([0.04, 0.98, 0.012], [x, 0.49, 0.306], look.accent);
+ glow.box([0.04, 0.94, 0.012], [x, 1.45, 0.126], look.accent);
+ glow.box([0.04, 0.012, 0.19], [x, 0.986, 0.215], look.accent);
+ }
+ paint.box([0.68, 0.98, 0.64], [0, 0.49, -0.07], look.trim);
+ paint.box([0.6, 0.1, 0.02], [0, 0.06, 0.26], HALL.black);
+ paint.box([0.24, 0.3, 0.02], [0, 0.5, 0.26], HALL.steel);
+ glow.box([0.035, 0.05, 0.008], [-0.055, 0.56, 0.274], "#ff4b2b");
+ glow.box([0.035, 0.05, 0.008], [0.055, 0.56, 0.274], "#ff4b2b");
+ // Control panel, its front edge tipped down towards the player.
+ paint.box([0.68, 0.06, 0.3], [0, 0.99, 0.17], look.trim, [tilt, 0, 0]);
+ paint.cylinder(0.009, 0.07, [-0.16, 1.045, 0.2], HALL.black, { segments: 8 });
+ paint.sphere(0.03, [-0.16, 1.09, 0.2], look.accent, undefined, 12);
+ glow.cylinder(0.025, 0.016, [0.04, 1.02, 0.2], look.accent, { rotation: [tilt, 0, 0], segments: 14 });
+ glow.cylinder(0.025, 0.016, [0.13, 1.02, 0.2], look.marqueeText, { rotation: [tilt, 0, 0], segments: 14 });
+ // Upper cabinet: the tube's housing, the bezel, the marquee box and the top cap.
+ paint.box([0.68, 0.76, 0.42], [0, 1.42, -0.17], look.trim);
+ paint.box([0.62, 0.52, 0.02], [0, CABINET_SCREEN.y, 0.05], HALL.black, [CABINET_SCREEN.tilt, 0, 0]);
+ paint.box([0.7, 0.2, 0.4], [0, CABINET_MARQUEE.y, -0.14], look.body);
+ paint.box([0.72, 0.03, 0.46], [0, 1.935, -0.15], look.trim);
+ });
+}
+
+function RetroCabinet({ item }: { item: Furniture }) {
+ const game = gameForCabinet(item.id);
+ return (
+ <group>
+ <BakedPiece baked={cabinetParts(game)} />
+ <mesh geometry={GEO.screen} material={screenMaterial(game)} position={[0, CABINET_SCREEN.y, CABINET_SCREEN.z]}
+ rotation={[CABINET_SCREEN.tilt, 0, 0]} />
+ <mesh geometry={GEO.marquee} material={marqueeMaterial(game)} position={[0, CABINET_MARQUEE.y, CABINET_MARQUEE.z]} />
+ </group>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Prize counter
+// ---------------------------------------------------------------------------
+
+/**
+ * The redemption counter: a glass display case of small prizes with a lit
+ * ticket strip on its base and a register on top, and behind it a plum shelf
+ * wall of plush toys under neon shelf lights.
+ */
+function prizeParts(): Baked {
+ return bake("arcade:prize-counter", (paint, glow) => {
+ const plum = "#3b1d4a", deep = "#2a1240", cream = "#efe6f4";
+ const rand = lcg(0x9e1ce);
+ const colour = () => HALL.plush[Math.floor(rand() * HALL.plush.length)];
+ paint.box([3.3, 0.35, 0.42], [0, 0.175, 0.21], plum);
+ paint.box([3.26, 0.02, 0.38], [0, 0.36, 0.21], "#1b0b24");
+ for (const x of [-1.635, 1.635]) for (const z of [0.03, 0.39]) paint.box([0.03, 0.64, 0.03], [x, 0.68, z], HALL.chrome);
+ paint.box([3.36, 0.04, 0.44], [0, 1.02, 0.21], cream);
+ // Small prizes in the case: balls, boxes and little plush.
+ for (let i = 0; i < 11; i += 1) {
+ const x = -1.45 + i * 0.29, kind = i % 3;
+ if (kind === 0) paint.sphere(0.05, [x, 0.42, 0.2], colour(), undefined, 10);
+ else if (kind === 1) paint.box([0.1, 0.1, 0.1], [x, 0.42, 0.22], colour(), [0, 0.4, 0]);
+ else plush(paint, x, 0.37, 0.2, 0.045, colour());
+ }
+ // The register on the counter.
+ paint.box([0.32, 0.16, 0.24], [1.25, 1.12, 0.2], HALL.steel);
+ glow.box([0.2, 0.05, 0.008], [1.25, 1.15, 0.324], HALL.neon.green);
+ // The shelf wall.
+ paint.box([3.4, 2.15, 0.06], [0, 1.075, -0.42], deep);
+ paint.box([3.3, 1.0, 0.3], [0, 0.5, -0.24], plum);
+ for (const x of [-1.675, 1.675]) paint.box([0.05, 2.15, 0.36], [x, 1.075, -0.27], deep);
+ for (const y of [1.28, 1.62, 1.96]) {
+ paint.box([3.3, 0.03, 0.3], [0, y, -0.24], cream);
+ glow.box([3.3, 0.012, 0.012], [0, y - 0.022, -0.085], HALL.neon.cyan);
+ for (let i = 0; i < 8; i += 1) {
+ plush(paint, -1.4 + i * 0.4 + (rand() - 0.5) * 0.06, y + 0.015, -0.24, 0.065 + rand() * 0.015, colour());
+ }
+ }
+ // A big bear sits on the counter's end.
+ plush(paint, -1.38, 1.04, 0.2, 0.1, HALL.plush[0]);
+ glow.box([3.3, 0.025, 0.012], [0, 0.355, 0.426], HALL.neon.magenta);
+ });
+}
+
+function PrizeCounter() {
+ return (
+ <group>
+ <BakedPiece baked={prizeParts()} />
+ <Glass size={[3.26, 0.62, 0.38]} position={[0, 0.68, 0.21]} />
+ <Face size={[1.6, 0.3]} position={[0, 0.19, 0.4215]} material={FACES.prizeSign()} />
+ </group>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Token changer
+// ---------------------------------------------------------------------------
+
+/** A golden change machine: a bill slot, a lit panel (bill → coins), a coin tray and a lit header. */
+function tokenParts(): Baked {
+ return bake("arcade:token-machine", (paint, glow) => {
+ paint.box([0.58, 0.06, 0.46], [0, 0.03, 0], HALL.black);
+ paint.box([0.56, 1.52, 0.44], [0, 0.82, -0.02], "#d9a521");
+ paint.box([0.46, 0.86, 0.02], [0, 1.0, 0.21], "#1c1c24");
+ paint.box([0.26, 0.1, 0.1], [0, 0.38, 0.2], HALL.steel);
+ glow.box([0.58, 0.12, 0.46], [0, 1.64, -0.02], HALL.neon.yellow);
+ glow.box([0.2, 0.02, 0.008], [0, 0.68, 0.224], HALL.neon.green);
+ });
+}
+
+function TokenMachine() {
+ return (
+ <group>
+ <BakedPiece baked={tokenParts()} gloss />
+ <Face size={[0.4, 0.5]} position={[0, 1.08, 0.2215]} material={FACES.token()} />
+ </group>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Claw machine
+// ---------------------------------------------------------------------------
+
+const CLAW_BODIES = ["#d23b6a", "#1fa4b8"] as const;
+
+/** A claw crane: a coloured base with a prize chute, a glass box full of plush, the claw on its gantry, a bulb-lit header. */
+function clawParts(variant: number): Baked {
+ return bake(`arcade:claw:${variant}`, (paint, glow) => {
+ const body = CLAW_BODIES[variant % CLAW_BODIES.length];
+ const rand = lcg(0xc1a3 + variant * 97);
+ paint.box([0.96, 0.85, 0.96], [0, 0.425, 0], body);
+ paint.box([0.28, 0.26, 0.02], [0.24, 0.36, 0.49], HALL.black);
+ paint.box([0.9, 0.06, 0.14], [0, 0.88, 0.42], HALL.steel);
+ paint.cylinder(0.008, 0.06, [-0.22, 0.94, 0.42], HALL.black, { segments: 8 });
+ paint.sphere(0.026, [-0.22, 0.98, 0.42], "#e0443e", undefined, 10);
+ glow.cylinder(0.024, 0.014, [0.0, 0.917, 0.42], HALL.neon.yellow, { segments: 14 });
+ for (const x of [-0.46, 0.46]) for (const z of [-0.46, 0.46]) paint.box([0.04, 0.9, 0.04], [x, 1.3, z], body);
+ paint.box([0.96, 0.25, 0.96], [0, 1.875, 0], body);
+ paint.box([0.9, 0.02, 0.9], [0, 0.86, 0], "#2a1240");
+ // The drop chute in the front-right corner, and a pile of plush everywhere else.
+ paint.box([0.26, 0.2, 0.26], [0.3, 0.97, 0.3], "#c9d3e6");
+ for (let i = 0; i < 16; i += 1) {
+ const x = -0.34 + rand() * 0.68, z = -0.34 + rand() * 0.68;
+ if (x > 0.12 && z > 0.12) continue;
+ plush(paint, x, 0.87 + rand() * 0.06, z, 0.055 + rand() * 0.02, HALL.plush[Math.floor(rand() * HALL.plush.length)]);
+ }
+ // The claw hanging from its gantry.
+ paint.box([0.9, 0.025, 0.025], [0, 1.732, -0.05], HALL.chrome);
+ paint.cylinder(0.006, 0.25, [-0.05, 1.62, -0.05], HALL.chrome, { segments: 6 });
+ paint.sphere(0.035, [-0.05, 1.48, -0.05], HALL.chrome, undefined, 10);
+ for (let k = 0; k < 3; k += 1) {
+ const a = (k / 3) * Math.PI * 2;
+ paint.box([0.012, 0.12, 0.012], [-0.05 + Math.cos(a) * 0.04, 1.42, -0.05 + Math.sin(a) * 0.04], HALL.chrome, [0, -a, 0.35]);
+ }
+ glow.box([0.9, 0.015, 0.9], [0, 1.742, 0], "#ffe6f2");
+ for (let i = 0; i < 9; i += 1) glow.sphere(0.018, [-0.4 + i * 0.1, 1.765, 0.485], HALL.neon.yellow, undefined, 6);
+ });
+}
+
+function ClawMachine({ item }: { item: Furniture }) {
+ return (
+ <group>
+ <BakedPiece baked={clawParts(variantOf(item.id, CLAW_BODIES.length))} />
+ <Glass size={[0.88, 0.86, 0.88]} position={[0, 1.31, 0]} />
+ <Face size={[0.8, 0.2]} position={[0, 1.875, 0.481]} material={FACES.clawHeader()} />
+ </group>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Air hockey
+// ---------------------------------------------------------------------------
+
+/** An air-hockey table: a blue cabinet with neon side strips, white rails, two mallets and a puck. */
+function hockeyParts(): Baked {
+ return bake("arcade:air-hockey", (paint, glow) => {
+ paint.box([1.9, 0.56, 1.0], [0, 0.38, 0], "#1f3a8a");
+ for (const x of [-0.85, 0.85]) for (const z of [-0.42, 0.42]) paint.box([0.12, 0.1, 0.12], [x, 0.05, z], HALL.black);
+ paint.box([1.94, 0.1, 1.04], [0, 0.7, 0], "#16285e");
+ for (const z of [-0.56, 0.56]) paint.box([2.1, 0.12, 0.08], [0, 0.74, z], "#e9edf5");
+ for (const x of [-1.01, 1.01]) paint.box([0.08, 0.12, 1.04], [x, 0.74, 0], "#e9edf5");
+ const mallet = (x: number, colour: string) => {
+ paint.cylinder(0.06, 0.035, [x, 0.7675, 0], colour, { segments: 18 });
+ paint.cylinder(0.022, 0.06, [x, 0.815, 0], colour, { segments: 12 });
+ };
+ mallet(-0.75, "#e0443e");
+ mallet(0.75, "#3b82f6");
+ paint.cylinder(0.04, 0.012, [0.18, 0.756, 0.12], "#ff3d7f", { segments: 16 });
+ for (const z of [-0.505, 0.505]) glow.box([1.8, 0.03, 0.01], [0, 0.5, z], HALL.neon.cyan);
+ });
+}
+
+function AirHockey() {
+ return (
+ <group>
+ <BakedPiece baked={hockeyParts()} />
+ <Face size={[1.94, 1.04]} position={[0, 0.751, 0]} rotation={[-Math.PI / 2, 0, 0]} material={FACES.airHockey()} />
+ </group>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Pinball
+// ---------------------------------------------------------------------------
+
+const PINBALL_BODIES = ["#2a1050", "#0f3a4a", "#4a1022"] as const;
+/** The playfield's tilt (back raised) and the tilted cabinet's centre. */
+const PINBALL = { tilt: 0.07, y: 0.88, depth: 1.3 } as const;
+
+/** The legs and the backbox; they stand straight. */
+function pinballStand(variant: number): Baked {
+ return bake(`arcade:pinball-stand:${variant}`, (paint, glow) => {
+ const body = PINBALL_BODIES[variant % PINBALL_BODIES.length];
+ for (const x of [-0.32, 0.32]) {
+ paint.box([0.05, 0.78, 0.05], [x, 0.39, 0.6], HALL.chrome);
+ paint.box([0.05, 0.86, 0.05], [x, 0.43, -0.55], HALL.chrome);
+ }
+ paint.box([0.7, 0.8, 0.16], [0, 1.45, -0.62], body);
+ glow.box([0.66, 0.02, 0.012], [0, 1.84, -0.535], HALL.neon.magenta);
+ glow.box([0.02, 0.66, 0.012], [-0.33, 1.47, -0.535], HALL.neon.cyan);
+ glow.box([0.02, 0.66, 0.012], [0.33, 1.47, -0.535], HALL.neon.cyan);
+ });
+}
+
+/** The tilted cabinet in its own frame (origin = the cabinet's centre): body, rails, bumpers, lights and buttons. */
+function pinballTable(variant: number): Baked {
+ return bake(`arcade:pinball-table:${variant}`, (paint, glow) => {
+ const body = PINBALL_BODIES[variant % PINBALL_BODIES.length];
+ paint.box([0.7, 0.24, PINBALL.depth], [0, 0, 0], body);
+ for (const x of [-0.335, 0.335]) paint.box([0.03, 0.08, PINBALL.depth], [x, 0.15, 0], HALL.chrome);
+ paint.box([0.22, 0.14, 0.01], [0, -0.03, 0.655], HALL.steel);
+ // Bumpers where the playfield texture draws their rings (u, v from its top-left corner).
+ const lights = [HALL.neon.magenta, HALL.neon.yellow, HALL.neon.cyan];
+ [[0.32, 0.28], [0.62, 0.24], [0.48, 0.4]].forEach(([u, v], i) => {
+ const x = (u - 0.5) * 0.62, z = (v - 0.5) * 1.22;
+ paint.cylinder(0.045, 0.04, [x, 0.141, z], "#e9e2d6", { segments: 14 });
+ glow.sphere(0.025, [x, 0.168, z], lights[i], [1, 0.6, 1], 10);
+ });
+ for (const x of [-0.36, 0.36]) glow.box([0.02, 0.04, 0.04], [x, 0.05, 0.55], HALL.neon.yellow);
+ glow.box([0.035, 0.03, 0.006], [-0.05, 0.0, 0.661], "#ff4b2b");
+ glow.box([0.035, 0.03, 0.006], [0.05, 0.0, 0.661], "#ff4b2b");
+ paint.cylinder(0.012, 0.05, [0.25, 0.02, 0.665], HALL.chrome, { rotation: [Math.PI / 2, 0, 0], segments: 8 });
+ });
+}
+
+function Pinball({ item }: { item: Furniture }) {
+ const variant = variantOf(item.id, PINBALL_BODIES.length);
+ return (
+ <group>
+ <BakedPiece baked={pinballStand(variant)} />
+ <group position={[0, PINBALL.y, 0]} rotation={[PINBALL.tilt, 0, 0]}>
+ <BakedPiece baked={pinballTable(variant)} />
+ <Face size={[0.62, 1.22]} position={[0, 0.121, 0]} rotation={[-Math.PI / 2, 0, 0]} material={FACES.playfield()} />
+ <Face size={[0.64, 1.24]} position={[0, 0.19, 0]} rotation={[-Math.PI / 2, 0, 0]} material={HALL_MAT.glass} />
+ </group>
+ <Face size={[0.62, 0.62]} position={[0, 1.47, -0.539]} material={FACES.backglass()} />
+ </group>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Snack counter
+// ---------------------------------------------------------------------------
+
+/** A diner counter: red front with chrome bands and a lit menu strip, a cream top with cups, a tray and a bell. */
+function snackParts(): Baked {
+ return bake("arcade:snack-counter", (paint, glow) => {
+ paint.box([2.5, 0.98, 0.62], [0, 0.51, 0.04], "#b8323a");
+ paint.box([2.5, 0.1, 0.02], [0, 0.05, 0.36], HALL.chrome);
+ paint.box([2.6, 0.05, 0.8], [0, 1.025, 0], HALL.snack.cream);
+ const cups = ["#e0443e", "#2de2e6", "#ffd23f", "#e0443e"];
+ cups.forEach((colour, i) => {
+ const x = 0.15 + i * 0.12;
+ paint.cylinder(0.035, 0.08, [x, 1.09, 0.12], colour, { radiusTop: 0.042, segments: 12 });
+ paint.cylinder(0.043, 0.008, [x, 1.134, 0.12], "#f4f1ea", { segments: 12 });
+ paint.cylinder(0.004, 0.012, [x + 0.01, 1.142, 0.12], "#ffffff", { segments: 5 });
+ });
+ paint.box([0.36, 0.015, 0.26], [-0.6, 1.058, 0.05], "#e0443e");
+ paint.cylinder(0.06, 0.022, [-0.66, 1.077, 0.05], "#e0a24a", { segments: 14 });
+ paint.cylinder(0.063, 0.018, [-0.66, 1.097, 0.05], "#6b3a1e", { segments: 14 });
+ paint.sphere(0.06, [-0.66, 1.106, 0.05], "#e0a24a", [1, 0.55, 1], 12);
+ paint.box([0.08, 0.07, 0.05], [-0.48, 1.1, 0.05], "#e0443e");
+ for (let i = -2; i <= 2; i += 1) paint.box([0.008, 0.06, 0.008], [-0.48 + i * 0.013, 1.115, 0.05], HALL.neon.yellow);
+ paint.box([0.12, 0.09, 0.08], [0.95, 1.095, -0.1], HALL.chrome);
+ paint.sphere(0.04, [1.12, 1.05, 0.15], "#d9a521", [1, 0.7, 1], 12);
+ glow.box([2.5, 0.025, 0.012], [0, 0.92, 0.356], HALL.neon.cyan);
+ glow.box([2.5, 0.025, 0.012], [0, 0.15, 0.356], HALL.neon.magenta);
+ });
+}
+
+function SnackCounter() {
+ return (
+ <group>
+ <BakedPiece baked={snackParts()} gloss />
+ <Face size={[2.2, 0.4]} position={[0, 0.58, 0.3505]} material={FACES.snackMenu()} />
+ </group>
+ );
+}
+
+export const ARCADE_RENDERERS = {
+ retroCabinet: ({ item }) => <RetroCabinet item={item} />,
+ prizeCounter: () => <PrizeCounter />,
+ tokenMachine: () => <TokenMachine />,
+ clawMachine: ({ item }) => <ClawMachine item={item} />,
+ airHockey: () => <AirHockey />,
+ pinball: ({ item }) => <Pinball item={item} />,
+ snackCounter: () => <SnackCounter />,
+} satisfies Partial<Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element>>;
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.test.tsx b/jarvis/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.test.tsx
new file mode 100644
index 0000000000..e7f20c0a14
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.test.tsx
@@ -0,0 +1,204 @@
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
+import { loadLocaleChunk } from "@/i18n";
+import type { RetroGame, RetroDrawInfo } from "./retroGame";
+import { RetroArcadeOverlay } from "./RetroArcadeOverlay";
+import { bestKey, clearBestMemory } from "./retroScores";
+
+/** A tiny game: A scores 10 per press, B ends the run (B with up held wins). */
+interface FakeState { score: number; over: boolean; won: boolean; steps: number }
+const draws: RetroDrawInfo[] = [];
+let lastState: FakeState | null = null;
+const fakeGame: RetroGame<FakeState> = {
+ id: "neon-snake",
+ width: 40,
+ height: 30,
+ create: () => (lastState = { score: 0, over: false, won: false, steps: 0 }),
+ step: (s, input) => {
+ s.steps++;
+ if (input.pressed.a) s.score += 10;
+ if (input.b) { s.over = true; s.won = input.up; }
+ },
+ draw: (_ctx, _s, info) => { draws.push({ ...info }); },
+ status: (s) => ({ score: s.score, lives: 3, over: s.over, won: s.won }),
+};
+const loadFake = async () => fakeGame as RetroGame<unknown>;
+
+/** Animation frames run only when the test says so, with explicit timestamps. */
+let frames = new Map<number, FrameRequestCallback>();
+let nextFrame = 1;
+let clock = 0;
+function frame(ms = 1000 / 60) {
+ clock += ms;
+ const due = frames;
+ frames = new Map();
+ act(() => { for (const cb of due.values()) cb(clock); });
+}
+
+const key = (type: "keyDown" | "keyUp", code: string, keyName = code) => fireEvent[type](window, { code, key: keyName });
+const phase = () => screen.getByRole("dialog").getAttribute("data-phase");
+
+beforeAll(async () => { await loadLocaleChunk("society"); });
+
+beforeEach(() => {
+ frames = new Map();
+ clock = 0;
+ draws.length = 0;
+ lastState = null;
+ clearBestMemory();
+ window.localStorage.clear();
+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => { frames.set(nextFrame, cb); return nextFrame++; });
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => { frames.delete(id); });
+ // jsdom has no 2D canvas; the fake game only needs a context to be handed one.
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({} as CanvasRenderingContext2D);
+});
+
+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+
+async function mount(onClose = vi.fn(), loadGame = loadFake) {
+ render(<RetroArcadeOverlay gameId="neon-snake" onClose={onClose} loadGame={loadGame} />);
+ const dialog = screen.getByRole("dialog", { name: "Neon Snake" });
+ await vi.waitFor(() => expect(dialog.getAttribute("data-phase")).toBe("ready"));
+ return { dialog, onClose };
+}
+
+describe("retro arcade overlay", () => {
+ test("opens as a modal on the title screen and draws the idle game", async () => {
+ const { dialog } = await mount();
+ expect(dialog.getAttribute("aria-modal")).toBe("true");
+ expect(dialog.getAttribute("data-state")).toBe("open");
+ expect(document.activeElement).toBe(dialog);
+ frame();
+ expect(draws.at(-1)?.idle).toBe(true);
+ expect(dialog.querySelector("canvas")?.width).toBe(40);
+ });
+
+ test("starts on Space, hands each press to exactly one step, and pauses on P", async () => {
+ await mount();
+ frame();
+ key("keyDown", "Space", " ");
+ frame();
+ expect(phase()).toBe("playing");
+ key("keyUp", "Space", " ");
+ // The press that started the run never reaches the game.
+ frame();
+ expect(lastState?.score).toBe(0);
+ expect(draws.at(-1)?.idle).toBe(false);
+
+ key("keyDown", "KeyJ", "j");
+ frame(3 * (1000 / 60));
+ expect(lastState?.score).toBe(10);
+ frame();
+ expect(lastState?.score).toBe(10);
+ key("keyUp", "KeyJ", "j");
+
+ key("keyDown", "KeyP", "p");
+ expect(phase()).toBe("paused");
+ const steps = lastState?.steps;
+ frame();
+ frame();
+ expect(lastState?.steps).toBe(steps);
+ expect(draws.at(-1)?.idle).toBe(true);
+ key("keyUp", "KeyP", "p");
+ key("keyDown", "KeyP", "p");
+ frame();
+ expect(phase()).toBe("playing");
+ });
+
+ test("ends a run, keeps the best score and waits before a restart", async () => {
+ await mount();
+ frame();
+ key("keyDown", "Enter", "Enter");
+ frame();
+ key("keyUp", "Enter", "Enter");
+ for (let i = 0; i < 2; i++) {
+ key("keyDown", "Space", " ");
+ frame();
+ key("keyUp", "Space", " ");
+ }
+ key("keyDown", "KeyX", "x");
+ frame();
+ key("keyUp", "KeyX", "x");
+ expect(phase()).toBe("over");
+ expect(window.localStorage.getItem(bestKey("neon-snake"))).toBe("20");
+ expect(document.querySelector(".retro-cab-newbest")).toBeTruthy();
+
+ // A fire key still hammered right after the end does not skip the result.
+ key("keyDown", "Space", " ");
+ frame(100);
+ expect(phase()).toBe("over");
+ key("keyUp", "Space", " ");
+ key("keyDown", "Enter", "Enter");
+ frame(700);
+ expect(phase()).toBe("playing");
+ expect(lastState?.score).toBe(0);
+ });
+
+ test("Escape leaves, the office never sees the key, and focus returns", async () => {
+ const opener = document.createElement("button");
+ document.body.appendChild(opener);
+ opener.focus();
+ const officeSaw = vi.fn();
+ document.addEventListener("keydown", officeSaw, true);
+ const { onClose } = await mount();
+ frame();
+ key("keyDown", "Escape", "Escape");
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(officeSaw).not.toHaveBeenCalled();
+ cleanup();
+ expect(frames.size).toBe(0);
+ expect(document.activeElement).toBe(opener);
+ document.removeEventListener("keydown", officeSaw, true);
+ opener.remove();
+ });
+
+ test("E and the backdrop leave too", async () => {
+ const { onClose } = await mount();
+ key("keyDown", "KeyE", "e");
+ expect(onClose).toHaveBeenCalledTimes(1);
+ fireEvent.pointerDown(screen.getByRole("dialog").parentElement as HTMLElement);
+ expect(onClose).toHaveBeenCalledTimes(2);
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+ expect(onClose).toHaveBeenCalledTimes(3);
+ });
+
+ test("losing the window pauses and forgets held keys", async () => {
+ await mount();
+ frame();
+ key("keyDown", "Enter", "Enter");
+ frame();
+ key("keyDown", "KeyX", "x");
+ fireEvent.blur(window);
+ expect(phase()).toBe("paused");
+ key("keyDown", "Enter", "Enter");
+ frame();
+ frame();
+ expect(phase()).toBe("playing");
+ expect(lastState?.over).toBe(false);
+ });
+
+ test("shows an error with a retry when the game cannot load", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ let fail = true;
+ const flaky = async () => {
+ if (fail) { fail = false; throw new Error("chunk missing"); }
+ return fakeGame as RetroGame<unknown>;
+ };
+ render(<RetroArcadeOverlay gameId="neon-snake" onClose={vi.fn()} loadGame={flaky} />);
+ await vi.waitFor(() => expect(phase()).toBe("error"));
+ fireEvent.click(screen.getByRole("button", { name: /retry|try again/i }));
+ await vi.waitFor(() => expect(phase()).toBe("ready"));
+ });
+
+ test("keeps a new best score when closed mid-run", async () => {
+ await mount();
+ frame();
+ key("keyDown", "Enter", "Enter");
+ frame();
+ key("keyDown", "Space", " ");
+ frame();
+ expect(lastState?.score).toBe(10);
+ cleanup();
+ expect(window.localStorage.getItem(bestKey("neon-snake"))).toBe("10");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsx b/jarvis/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsx
new file mode 100644
index 0000000000..c10e18f958
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsx
@@ -0,0 +1,483 @@
+/**
+ * Standing at a cabinet on the arcade floor: the full-screen player for every
+ * 2D retro game.
+ *
+ * The game itself is pure (retroGame.ts); this overlay owns everything around
+ * it: loading the game's code, the cabinet look, the keyboard / gamepad /
+ * touch controls, the fixed-step loop, the title / pause / game-over screens,
+ * the HUD and the best score. It is a modal dialog, so the office character
+ * stands still while you play, and it takes every key it uses in the capture
+ * phase so the office never sees them.
+ *
+ * Phase changes are React state (rare); the loop itself runs on refs and
+ * never sets state per frame. The HUD polls the game ten times a second.
+ */
+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from "react";
+import { useReducedMotion } from "framer-motion";
+import { useT } from "@/i18n";
+import { arcadeGame, loadRetroGame, type CabinetLook, type RetroGameId } from "./arcadeGames";
+import { RETRO_STEP, type RetroGame } from "./retroGame";
+import {
+ clearEdges, createInputTracker, dpadDirections, firstGamepad, hasStartGesture, leavePointer, pressKey, readGamepad, releaseAll,
+ releaseKey, screenScale, setPointer, setTouch, takeInput, toLogical, type GamepadLike, type InputTracker, type RetroButton,
+} from "./retroInput";
+import { createRetroClock, resetClock, stepsDue } from "./retroLoop";
+import { readBest, saveBest } from "./retroScores";
+import "./retroArcade.css";
+
+type Phase = "loading" | "error" | "ready" | "playing" | "paused" | "over";
+
+/** After a run ends, Space / Enter wait this long, so a held fire key does not skip the result. */
+const RESTART_GUARD_MS = 600;
+const HUD_POLL_MS = 100;
+/** The screen size shown while a game's code is still loading. */
+const PLACEHOLDER = { width: 320, height: 240 };
+const FALLBACK_LOOK: CabinetLook = { body: "#1d1a3a", trim: "#0e0c1f", marquee: "#120f2a", marqueeText: "#facc15", accent: "#2dff5a" };
+
+interface Hud { score: number; lives?: number; level?: number }
+interface RunResult { score: number; best: number; newBest: boolean; won: boolean }
+interface Run { game: RetroGame<unknown>; state: unknown }
+
+type GameLoader = (id: RetroGameId) => Promise<RetroGame<unknown>>;
+
+function sameHud(a: Hud, b: Hud): boolean {
+ return a.score === b.score && a.lives === b.lives && a.level === b.level;
+}
+
+function readPads(): readonly (GamepadLike | null)[] | null {
+ if (typeof navigator === "undefined" || typeof navigator.getGamepads !== "function") return null;
+ try {
+ return navigator.getGamepads();
+ } catch {
+ // A permissions policy can forbid the Gamepad API; the keyboard still works.
+ return null;
+ }
+}
+
+function useCoarsePointer(): boolean {
+ const query = "(pointer: coarse)";
+ const [coarse, setCoarse] = useState(() => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(query).matches);
+ useEffect(() => {
+ if (typeof window.matchMedia !== "function") return;
+ const media = window.matchMedia(query);
+ const change = () => setCoarse(media.matches);
+ media.addEventListener?.("change", change);
+ return () => media.removeEventListener?.("change", change);
+ }, []);
+ return coarse;
+}
+
+export function RetroArcadeOverlay({ gameId, onClose, loadGame = loadRetroGame }: {
+ gameId: RetroGameId;
+ onClose: () => void;
+ loadGame?: GameLoader;
+}) {
+ const t = useT();
+ const info = arcadeGame(gameId);
+ const title = info?.title ?? gameId;
+ const look = info?.look ?? FALLBACK_LOOK;
+ const reduced = useReducedMotion() ?? false;
+ const coarse = useCoarsePointer();
+
+ const dialog = useRef<HTMLDivElement>(null);
+ const stage = useRef<HTMLDivElement>(null);
+ const canvas = useRef<HTMLCanvasElement>(null);
+ const run = useRef<Run | null>(null);
+ const tracker = useRef<InputTracker>(createInputTracker());
+ const startRequest = useRef(false);
+ const reducedRef = useRef(reduced);
+ reducedRef.current = reduced;
+ // Callers often pass fresh arrow functions; refs keep the listeners and the load from churning on every render.
+ const closeRef = useRef(onClose);
+ closeRef.current = onClose;
+ const loaderRef = useRef(loadGame);
+ loaderRef.current = loadGame;
+
+ const [game, setGame] = useState<RetroGame<unknown> | null>(null);
+ const [attempt, setAttempt] = useState(0);
+ const [phase, setPhaseState] = useState<Phase>("loading");
+ const phaseRef = useRef<Phase>("loading");
+ const [hud, setHud] = useState<Hud>({ score: 0 });
+ const [best, setBest] = useState(() => readBest(gameId));
+ const [result, setResult] = useState<RunResult | null>(null);
+ const [scale, setScale] = useState(1);
+
+ const setPhase = useCallback((next: Phase) => {
+ phaseRef.current = next;
+ setPhaseState(next);
+ }, []);
+
+ // Load (or reload after an error) the game's code.
+ useEffect(() => {
+ let alive = true;
+ setPhase("loading");
+ loaderRef.current(gameId).then(
+ (loaded) => {
+ if (!alive) return;
+ run.current = { game: loaded, state: loaded.create(Math.random) };
+ setGame(loaded);
+ setResult(null);
+ setPhase("ready");
+ },
+ (error: unknown) => {
+ if (!alive) return;
+ console.warn("[arcade] game failed to load", gameId, error);
+ setPhase("error");
+ },
+ );
+ return () => { alive = false; };
+ }, [gameId, attempt, setPhase]);
+
+ const pause = useCallback(() => {
+ releaseAll(tracker.current);
+ if (phaseRef.current === "playing") setPhase("paused");
+ }, [setPhase]);
+
+ // The fixed-step loop. It runs for as long as the overlay is open (the
+ // browser throttles animation frames of a truly hidden page by itself; the
+ // desktop shell's visibility signal is not trusted to stop it).
+ useEffect(() => {
+ const clock = createRetroClock();
+ let raf = 0;
+ let last = -1;
+ let opened = -1;
+ let overAt = 0;
+
+ const finish = (score: number, won: boolean, now: number) => {
+ const previous = readBest(gameId);
+ const newBest = saveBest(gameId, score);
+ const kept = Math.max(previous, score);
+ setBest(kept);
+ setResult({ score, best: kept, newBest, won });
+ overAt = now;
+ clearEdges(tracker.current);
+ setPhase("over");
+ };
+
+ const begin = (now: number) => {
+ const current = run.current;
+ if (!current) return;
+ if (phaseRef.current === "over") {
+ if (now - overAt < RESTART_GUARD_MS) return;
+ current.state = current.game.create(Math.random);
+ setResult(null);
+ }
+ resetClock(clock);
+ clearEdges(tracker.current);
+ setPhase("playing");
+ };
+
+ const frame = (now: number) => {
+ raf = requestAnimationFrame(frame);
+ if (opened < 0) opened = now;
+ const elapsed = last < 0 ? 0 : (now - last) / 1000;
+ last = now;
+ const current = run.current;
+ const phase = phaseRef.current;
+ if (!current || phase === "loading" || phase === "error") return;
+ const input = tracker.current;
+ const pads = readPads();
+ const startPressed = pads ? readGamepad(input, firstGamepad(pads)) : false;
+ try {
+ if (phase === "playing") {
+ if (startPressed) {
+ pause();
+ } else {
+ const steps = stepsDue(clock, elapsed);
+ for (let i = 0; i < steps; i++) {
+ current.game.step(current.state, takeInput(input, !!current.game.pointer), RETRO_STEP, Math.random);
+ const status = current.game.status(current.state);
+ if (status.over) {
+ finish(Math.max(0, Math.floor(status.score)), !!status.won, now);
+ break;
+ }
+ }
+ }
+ } else {
+ const wants = startRequest.current || startPressed || hasStartGesture(input);
+ startRequest.current = false;
+ clearEdges(input);
+ if (wants) begin(now);
+ }
+ const ctx = canvas.current?.getContext("2d") ?? null;
+ if (ctx) {
+ ctx.imageSmoothingEnabled = false;
+ const shown = phaseRef.current;
+ current.game.draw(ctx, current.state, {
+ time: (now - opened) / 1000,
+ reduced: reducedRef.current,
+ idle: shown === "ready" || shown === "paused",
+ });
+ }
+ } catch (error) {
+ // A game that throws stops here with a retry, instead of throwing every frame.
+ console.warn("[arcade] game crashed", gameId, error);
+ run.current = null;
+ setPhase("error");
+ }
+ };
+ raf = requestAnimationFrame(frame);
+ return () => cancelAnimationFrame(raf);
+ }, [gameId, pause, setPhase]);
+
+ const togglePause = useCallback(() => {
+ if (phaseRef.current === "playing") pause();
+ else if (phaseRef.current === "paused") startRequest.current = true;
+ }, [pause]);
+
+ // Keyboard: every key the cabinet uses is taken in the capture phase, so
+ // neither the office's Escape nor its walking keys ever see it.
+ useEffect(() => {
+ const swallow = (event: KeyboardEvent) => { event.preventDefault(); event.stopPropagation(); };
+ const down = (event: KeyboardEvent) => {
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
+ const code = event.code;
+ if (event.key === "Escape" || code === "KeyE") {
+ swallow(event);
+ if (!event.repeat) closeRef.current();
+ } else if (code === "KeyP") {
+ swallow(event);
+ if (!event.repeat) togglePause();
+ } else if (code === "Enter" || code === "NumpadEnter") {
+ swallow(event);
+ if (!event.repeat) startRequest.current = true;
+ } else if (pressKey(tracker.current, code, event.repeat)) {
+ swallow(event);
+ }
+ };
+ const up = (event: KeyboardEvent) => {
+ const code = event.code;
+ // Released keys always count, even with a modifier down, or they would stick.
+ if (releaseKey(tracker.current, code) || code === "Enter" || code === "NumpadEnter" || code === "KeyP") swallow(event);
+ };
+ // Leaving the window (or hiding it) pauses and forgets held keys: their keyup never arrives.
+ const visibility = () => { if (document.hidden) pause(); };
+ window.addEventListener("keydown", down, true);
+ window.addEventListener("keyup", up, true);
+ window.addEventListener("blur", pause);
+ document.addEventListener("visibilitychange", visibility);
+ return () => {
+ window.removeEventListener("keydown", down, true);
+ window.removeEventListener("keyup", up, true);
+ window.removeEventListener("blur", pause);
+ document.removeEventListener("visibilitychange", visibility);
+ };
+ }, [pause, togglePause]);
+
+ // The HUD follows the game at a relaxed pace, and only re-renders on change.
+ useEffect(() => {
+ const id = window.setInterval(() => {
+ const current = run.current;
+ if (!current || phaseRef.current === "loading" || phaseRef.current === "error") return;
+ try {
+ const status = current.game.status(current.state);
+ const next: Hud = { score: Math.max(0, Math.floor(status.score)), lives: status.lives, level: status.level };
+ setHud((h) => (sameHud(h, next) ? h : next));
+ } catch {
+ // The loop reports a crashing game; the HUD just keeps its last numbers.
+ }
+ }, HUD_POLL_MS);
+ return () => window.clearInterval(id);
+ }, []);
+
+ // Closing mid-run still keeps a new best score.
+ useEffect(() => () => {
+ const current = run.current;
+ if (!current) return;
+ try { saveBest(gameId, current.game.status(current.state).score); } catch { /* a crashed game has no score worth keeping */ }
+ }, [gameId]);
+
+ // Focus moves into the dialog and back to where it was on close.
+ useLayoutEffect(() => {
+ const previous = document.activeElement;
+ dialog.current?.focus({ preventScroll: true });
+ return () => {
+ if (previous instanceof HTMLElement && previous.isConnected) previous.focus({ preventScroll: true });
+ };
+ }, []);
+
+ const width = game?.width ?? PLACEHOLDER.width;
+ const height = game?.height ?? PLACEHOLDER.height;
+
+ // The screen is scaled to the largest crisp factor that fits the stage.
+ useEffect(() => {
+ const el = stage.current;
+ if (!el) return;
+ const measure = () => {
+ const next = screenScale(el.clientWidth, el.clientHeight, width, height, window.devicePixelRatio || 1);
+ setScale((s) => (Math.abs(s - next) < 1e-6 ? s : next));
+ };
+ measure();
+ if (typeof ResizeObserver !== "undefined") {
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }
+ window.addEventListener("resize", measure);
+ return () => window.removeEventListener("resize", measure);
+ }, [width, height]);
+
+ const pointerAt = (event: ReactPointerEvent<HTMLCanvasElement>, down: boolean) => {
+ const el = canvas.current;
+ if (!el || !game?.pointer) return;
+ const at = toLogical(event.clientX, event.clientY, el.getBoundingClientRect(), width, height);
+ if (at) setPointer(tracker.current, at.x, at.y, down);
+ else leavePointer(tracker.current);
+ };
+
+ const style = {
+ "--cab-body": look.body, "--cab-trim": look.trim, "--cab-marquee": look.marquee,
+ "--cab-marquee-text": look.marqueeText, "--cab-accent": look.accent,
+ } as CSSProperties;
+ const screenStyle = { width: `${width * scale}px`, height: `${height * scale}px`, "--retro-px": `${scale}px` } as CSSProperties;
+ const key = info?.key ?? "";
+ const shownBest = Math.max(best, hud.score);
+ const requestStart = () => { startRequest.current = true; };
+
+ return (
+ <div className="retro-cab-backdrop" data-office-ui onPointerDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>
+ <div ref={dialog} className="retro-cab" style={style} role="dialog" data-state="open" aria-modal="true" aria-label={title}
+ data-phase={phase} data-reduced={reduced ? "true" : "false"} tabIndex={-1}>
+ <header className="retro-cab-marquee">
+ <h2>{title}</h2>
+ <button type="button" className="retro-cab-close" onClick={onClose} aria-label={t("society.office.close")}>×</button>
+ </header>
+ <div className="retro-cab-bezel">
+ <div className="retro-cab-hud">
+ <span>{t("society.arcade.score")} <b>{hud.score}</b></span>
+ <span>{t("society.arcade.best")} <b>{shownBest}</b></span>
+ {hud.lives !== undefined && <span>{t("society.arcade.lives")} <b>{hud.lives}</b></span>}
+ {hud.level !== undefined && <span>{t("society.arcade.level")} <b>{hud.level}</b></span>}
+ </div>
+ <div ref={stage} className="retro-cab-stage">
+ <div className="retro-cab-screen" style={screenStyle} data-scan={scale >= 2 ? "on" : "off"}>
+ <canvas ref={canvas} width={width} height={height} data-pointer={game?.pointer ? "true" : "false"}
+ onPointerDown={(event) => {
+ if (!game?.pointer) return;
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ pointerAt(event, true);
+ }}
+ onPointerMove={(event) => pointerAt(event, event.buttons !== 0)}
+ onPointerUp={(event) => pointerAt(event, false)}
+ onPointerCancel={() => leavePointer(tracker.current)}
+ onPointerLeave={() => leavePointer(tracker.current)} />
+ <div className="retro-cab-crt" aria-hidden />
+ {phase === "loading" && (
+ <div className="retro-cab-card" role="status"><span>{t("society.arcade.loading")}</span></div>
+ )}
+ {phase === "error" && (
+ <div className="retro-cab-card" role="alert">
+ <span>{t("society.arcade.load_failed")}</span>
+ <button type="button" className="retro-cab-retry" onClick={() => setAttempt((n) => n + 1)}>{t("society.arcade.retry")}</button>
+ </div>
+ )}
+ {phase === "ready" && (
+ <button type="button" className="retro-cab-card" onClick={requestStart}>
+ <strong>{title}</strong>
+ {key && <span className="retro-cab-tagline">{t(`society.arcade.games.${key}.tagline`)}</span>}
+ {key && <span className="retro-cab-how">{t(`society.arcade.games.${key}.how`)}</span>}
+ <span className="retro-cab-blink">{t(coarse ? "society.arcade.tap_start" : "society.arcade.press_start")}</span>
+ </button>
+ )}
+ {phase === "paused" && (
+ <button type="button" className="retro-cab-card" onClick={requestStart}>
+ <strong>{t("society.arcade.paused")}</strong>
+ <span>{t(coarse ? "society.arcade.tap_resume" : "society.arcade.resume_hint")}</span>
+ </button>
+ )}
+ {phase === "over" && result && (
+ <button type="button" className="retro-cab-card" onClick={requestStart}>
+ <strong>{t(result.won ? "society.arcade.you_win" : "society.arcade.game_over")}</strong>
+ <span>{t("society.arcade.score")} <b>{result.score}</b> · {t("society.arcade.best")} <b>{result.best}</b></span>
+ {result.newBest && <span className="retro-cab-newbest">{t("society.arcade.new_best")}</span>}
+ <span className="retro-cab-blink">{t(coarse ? "society.arcade.tap_again" : "society.arcade.play_again")}</span>
+ </button>
+ )}
+ </div>
+ </div>
+ {coarse ? (
+ <TouchPad tracker={tracker.current} onPause={togglePause} pauseLabel={t("society.arcade.pause")}
+ labels={{ up: t("society.arcade.pad_up"), down: t("society.arcade.pad_down"), left: t("society.arcade.pad_left"), right: t("society.arcade.pad_right") }} />
+ ) : (
+ <p className="retro-cab-keys">{t("society.arcade.keys_hint")}</p>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+const DIRECTIONS = ["up", "down", "left", "right"] as const;
+
+/**
+ * The on-screen control panel for touch screens: an 8-way d-pad you can roll
+ * your thumb across, A and B, and pause. Each control tracks its own pointer
+ * ids, so two thumbs (move + fire) work at once.
+ */
+function TouchPad({ tracker, onPause, pauseLabel, labels }: {
+ tracker: InputTracker;
+ onPause: () => void;
+ pauseLabel: string;
+ labels: Record<(typeof DIRECTIONS)[number], string>;
+}) {
+ const dpadPointer = useRef<number | null>(null);
+
+ const steer = (event: ReactPointerEvent<HTMLDivElement>) => {
+ const rect = event.currentTarget.getBoundingClientRect();
+ const dirs = dpadDirections(event.clientX - (rect.left + rect.width / 2), event.clientY - (rect.top + rect.height / 2), rect.width / 2);
+ for (const d of DIRECTIONS) setTouch(tracker, d, dirs[d]);
+ };
+ const releaseDpad = (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (event.pointerId !== dpadPointer.current) return;
+ dpadPointer.current = null;
+ for (const d of DIRECTIONS) setTouch(tracker, d, false);
+ };
+
+ return (
+ <div className="retro-cab-touch">
+ <div className="retro-cab-dpad" role="group"
+ onPointerDown={(event) => {
+ if (dpadPointer.current !== null) return;
+ event.preventDefault();
+ dpadPointer.current = event.pointerId;
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ steer(event);
+ }}
+ onPointerMove={(event) => { if (event.pointerId === dpadPointer.current) steer(event); }}
+ onPointerUp={releaseDpad}
+ onPointerCancel={releaseDpad}
+ onLostPointerCapture={releaseDpad}>
+ {DIRECTIONS.map((d) => <span key={d} className="retro-cab-dpad-arm" data-dir={d} role="img" aria-label={labels[d]} />)}
+ </div>
+ <button type="button" className="retro-cab-pause" aria-label={pauseLabel} onClick={onPause}>❚❚</button>
+ <div className="retro-cab-buttons">
+ <TouchButton tracker={tracker} button="b" />
+ <TouchButton tracker={tracker} button="a" />
+ </div>
+ </div>
+ );
+}
+
+function TouchButton({ tracker, button }: { tracker: InputTracker; button: RetroButton }) {
+ const held = useRef(new Set<number>());
+ const release = (event: ReactPointerEvent<HTMLButtonElement>) => {
+ if (!held.current.delete(event.pointerId)) return;
+ if (held.current.size === 0) setTouch(tracker, button, false);
+ };
+ // Labelled with its letter: A and B are the cabinet's own button names in every language.
+ return (
+ <button type="button" className="retro-cab-btn" data-button={button} aria-label={button.toUpperCase()}
+ onPointerDown={(event) => {
+ event.preventDefault();
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ held.current.add(event.pointerId);
+ setTouch(tracker, button, true);
+ }}
+ onPointerUp={release}
+ onPointerCancel={release}
+ onLostPointerCapture={release}
+ onContextMenu={(event) => event.preventDefault()}>
+ {button.toUpperCase()}
+ </button>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.test.ts
new file mode 100644
index 0000000000..839fc425cc
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.test.ts
@@ -0,0 +1,139 @@
+import { describe, expect, it } from "vitest";
+import { ARCADE_GAMES, cabinetId, gameForCabinet } from "./arcadeGames";
+import { arcadeDecor, buildArcadeLayout, cabinetPlaySpot, SNACK_TABLE_HALF } from "./arcadeFloorLayout";
+import { archPosts, ARCH, FURNITURE_SIZE, footprint, roomAt, wallRect, type Rect } from "../office/officeLayout";
+import { buildNavGrid, findPath, isWalkable } from "../office/officeNav";
+import { arrivalPose } from "../office/officeFloors";
+
+const overlaps = (a: Rect, b: Rect) => a.minX < b.maxX - 1e-9 && b.minX < a.maxX - 1e-9 && a.minZ < b.maxZ - 1e-9 && b.minZ < a.maxZ - 1e-9;
+const inside = (r: Rect, outer: Rect) => r.minX >= outer.minX && r.maxX <= outer.maxX && r.minZ >= outer.minZ && r.maxZ <= outer.maxZ;
+
+describe("arcade floor layout", () => {
+ const layout = buildArcadeLayout();
+ const grid = buildNavGrid(layout);
+ const cabinets = layout.furniture.filter((f) => f.kind === "retroCabinet");
+
+ it("is the arcade variant with no agents' places on it", () => {
+ expect(layout.variant).toBe("arcade");
+ expect(layout.departments).toEqual([]);
+ expect(layout.lead.desks).toEqual([]);
+ expect(layout.spots).toEqual([]);
+ expect(layout.command).toBeUndefined();
+ expect(layout.checkpoints.map((c) => c.id)).toEqual(["elevator"]);
+ });
+
+ it("is deterministic", () => {
+ expect(buildArcadeLayout()).toEqual(layout);
+ });
+
+ it("has a compact slab of the size the other floors float at", () => {
+ const { minX, maxX, minZ, maxZ } = layout.bounds;
+ expect(maxX - minX).toBeGreaterThanOrEqual(22);
+ expect(maxX - minX).toBeLessThanOrEqual(28);
+ expect(maxZ - minZ).toBeGreaterThanOrEqual(16);
+ expect(maxZ - minZ).toBeLessThanOrEqual(20);
+ expect(inside(layout.floor, layout.bounds)).toBe(true);
+ });
+
+ it("has the hall, the prize corner and the snack bar, side by side", () => {
+ expect(layout.rooms.map((r) => r.kind).sort()).toEqual(["arcade", "prizes", "snack"]);
+ for (const a of layout.rooms) {
+ expect(inside(a, layout.bounds)).toBe(true);
+ for (const b of layout.rooms) if (a !== b) expect(overlaps(a, b)).toBe(false);
+ }
+ const kinds = (room: string) => layout.furniture.filter((f) => f.room === room).map((f) => f.kind);
+ expect(kinds("prizes")).toEqual(expect.arrayContaining(["prizeCounter", "tokenMachine", "clawMachine"]));
+ expect(kinds("snack")).toEqual(expect.arrayContaining(["snackCounter", "elevator"]));
+ expect(kinds("arcade")).toEqual(expect.arrayContaining(["retroCabinet", "pinball", "airHockey"]));
+ });
+
+ it("puts every furniture piece in the room it names", () => {
+ for (const item of layout.furniture) expect(roomAt(layout, item)?.kind, item.id).toBe(item.room);
+ });
+
+ it("has exactly one cabinet per game, turned by quarter turns", () => {
+ expect(cabinets).toHaveLength(ARCADE_GAMES.length);
+ for (const game of ARCADE_GAMES) {
+ expect(cabinets.filter((c) => c.id === cabinetId(game.id))).toHaveLength(1);
+ }
+ for (const cabinet of cabinets) {
+ expect(gameForCabinet(cabinet.id)).not.toBeNull();
+ const quarters = cabinet.rotationY / (Math.PI / 2);
+ expect(Math.abs(quarters - Math.round(quarters))).toBeLessThan(1e-9);
+ }
+ expect(new Set(layout.furniture.map((f) => f.id)).size).toBe(layout.furniture.length);
+ });
+
+ it("turns every cabinet's screen towards the camera (south or east)", () => {
+ for (const cabinet of cabinets) {
+ const facing = { x: Math.round(Math.sin(cabinet.rotationY)), z: Math.round(Math.cos(cabinet.rotationY)) };
+ expect(facing.x >= 0 && facing.z >= 0, cabinet.id).toBe(true);
+ }
+ });
+
+ it("keeps solid furniture, decor and arch posts apart and inside the slab", () => {
+ const solids = layout.furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map((f) => ({ id: f.id, rect: footprint(f) }));
+ const tables = arcadeDecor(layout.rooms).tables.map((t, i) => ({
+ id: `table-${i}`, rect: { minX: t.x - SNACK_TABLE_HALF, maxX: t.x + SNACK_TABLE_HALF, minZ: t.z - SNACK_TABLE_HALF, maxZ: t.z + SNACK_TABLE_HALF },
+ }));
+ const posts = layout.rooms.flatMap(archPosts).map((p, i) => ({
+ id: `post-${i}`, rect: { minX: p.x - ARCH.post / 2, maxX: p.x + ARCH.post / 2, minZ: p.z - ARCH.post / 2, maxZ: p.z + ARCH.post / 2 },
+ }));
+ const walls = layout.walls.map((w, i) => ({ id: `wall-${i}`, rect: wallRect(w) }));
+ const all = [...solids, ...tables, ...posts, ...walls];
+ expect(tables).toHaveLength(3);
+ for (let i = 0; i < all.length; i += 1) {
+ expect(inside(all[i].rect, layout.bounds), all[i].id).toBe(true);
+ for (let j = i + 1; j < all.length; j += 1) {
+ expect(overlaps(all[i].rect, all[j].rect), `${all[i].id} × ${all[j].id}`).toBe(false);
+ }
+ }
+ // Navigation walks round every one of them.
+ for (const { rect } of all) expect(layout.obstacles).toContainEqual(rect);
+ });
+
+ it("can reach every cabinet's play spot from the elevator", () => {
+ const pose = arrivalPose(layout, "elevator");
+ expect(isWalkable(grid, pose)).toBe(true);
+ expect(isWalkable(grid, layout.spawn)).toBe(true);
+ expect(isWalkable(grid, layout.arrival)).toBe(true);
+ for (const cabinet of cabinets) {
+ const spot = cabinetPlaySpot(cabinet);
+ expect(isWalkable(grid, spot), cabinet.id).toBe(true);
+ const path = findPath(grid, pose, spot);
+ expect(path, cabinet.id).not.toBeNull();
+ expect(path?.at(-1)).toEqual(spot);
+ }
+ });
+
+ it("keeps the play spots of different cabinets at least a metre apart", () => {
+ const spots = cabinets.map(cabinetPlaySpot);
+ for (let i = 0; i < spots.length; i += 1) {
+ for (let j = i + 1; j < spots.length; j += 1) {
+ expect(Math.hypot(spots[i].x - spots[j].x, spots[i].z - spots[j].z)).toBeGreaterThanOrEqual(1.0);
+ }
+ }
+ });
+
+ it("keeps the elevator stop clear of the cabinets", () => {
+ const stop = layout.checkpoints[0];
+ expect(stop.room).toBe("snack");
+ for (const cabinet of cabinets) {
+ const spot = cabinetPlaySpot(cabinet);
+ expect(Math.hypot(spot.x - stop.x, spot.z - stop.z)).toBeGreaterThan(stop.radius + 1);
+ }
+ });
+
+ it("reaches the counters, the claw machines and the snack tables on foot", () => {
+ const pose = arrivalPose(layout, "elevator");
+ const front = (id: string) => {
+ const item = layout.furniture.find((f) => f.id === id)!;
+ const reach = FURNITURE_SIZE[item.kind].d / 2 + 0.5;
+ return { x: item.x + Math.sin(item.rotationY) * reach, z: item.z + Math.cos(item.rotationY) * reach };
+ };
+ for (const id of ["prize-counter", "token-machine", "claw-a", "claw-b", "snack-counter", "air-hockey", "pinball-1"]) {
+ expect(isWalkable(grid, front(id)), id).toBe(true);
+ expect(findPath(grid, pose, front(id)), id).not.toBeNull();
+ }
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.ts b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.ts
new file mode 100644
index 0000000000..74781a91d0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.ts
@@ -0,0 +1,178 @@
+/**
+ * The arcade floor as data: the top floor of the building, one elevator ride
+ * above the coding floor. A dark, neon-lit 80s/90s arcade hall with every
+ * playable cabinet of the registry, a pinball row, an air-hockey table, a
+ * prize counter with claw machines and a token changer, and a snack bar by
+ * the elevator.
+ *
+ * Pure and deterministic, like officeLayout: the plan never depends on who is
+ * online (nobody works up here, so it has no departments, desks or hangout
+ * spots). Units are metres, +x east, +z south, origin at the floor centre.
+ * The camera looks from the south-east, so the floor is a diorama with two
+ * back walls (north and west, drawn by ArcadeHall) and glass railings on the
+ * south and east; tall pieces stand along the back walls, every cabinet's
+ * screen faces south or east, towards the camera.
+ *
+ * ┌───────── north wall ─────────────────────────────────────────────┐
+ * │ PRIZES: counter · tokens │ pinballs · cabinet row A · dance pad │
+ * │ claw machines (west wall) │ row B (faces east) · island C │
+ * │ SNACK: counter · tables │ │
+ * │ elevator (west wall) │ air hockey │
+ * └──────────────────────────────────────────────────────── railing ─┘
+ *
+ * Open rooms only: each one's name arch stands on its north edge, right
+ * behind the counter (prizes, snack) or the cabinet row (hall), so the sign
+ * reads as the counter's own gantry.
+ */
+import { ARCADE_GAMES, cabinetId } from "./arcadeGames";
+import {
+ archPosts, ARCH, FURNITURE_SIZE, footprint, wallRect, wallsOf,
+ type Checkpoint, type Furniture, type FurnitureKind, type OfficeLayout, type Point, type Rect, type Room, type RoomKind,
+} from "../office/officeLayout";
+
+/** Half the slab's size (bounds = ±HALF_W × ±HALF_D). */
+const HALF_W = 11.5;
+const HALF_D = 8.5;
+/** The back walls and the railings stand this far in from the slab's edge. */
+export const ARCADE_WALL_INSET = 0.2;
+/** How far a figure's centre stays from the slab edge (see officeLayout's RAIL_CLEARANCE). */
+const RAIL_CLEARANCE = 0.65;
+/** Width of the west column holding the prize corner (north) and the snack bar (south). */
+const WEST_COLUMN = 5.8;
+/** Where the prize corner ends and the snack bar begins. */
+const PRIZES_DEPTH = 5.8;
+/** Centre-to-centre pitch of cabinets standing side by side (a 0.8 m cabinet and a 0.3 m gap). */
+const CABINET_PITCH = 1.1;
+/** The arch posts stand right behind a counter or a cabinet row; this keeps them clear of it. */
+const BEHIND_ARCH = ARCH.post / 2 + 0.06;
+
+/** A cabinet is played standing this far in front of it, along its local +z (OfficePlayer). */
+export const CABINET_PLAY_DISTANCE = 0.85;
+
+/** The bistro tables of the snack bar: table and stools fit inside a square of this half size. */
+export const SNACK_TABLE_HALF = 0.62;
+
+/** Floor decor that is drawn by ArcadeHall but placed here, so navigation knows the solid parts. */
+export interface ArcadeDecor {
+ /** Bistro tables (with their stools) in the snack bar; solid. */
+ tables: Point[];
+ /** The light-up dance pad in the hall's north-east corner; flat, walkable. */
+ pad: Rect;
+ /** A neon star medallion inlaid in the carpet in the open south of the hall; flat, walkable. */
+ medallion: Point & { r: number };
+}
+
+/** The snack bar's three bistro tables, south of its counter, clear of the elevator stop. */
+function snackTables(room: Rect): Point[] {
+ const cx = (room.minX + room.maxX) / 2;
+ return [
+ { x: cx - 1.2, z: room.minZ + 3.4 },
+ { x: cx + 1.2, z: room.minZ + 3.4 },
+ { x: cx, z: room.minZ + 5.6 },
+ ];
+}
+
+/** Where the floor decor lies, from the rooms of an arcade layout (empty when a room is missing). */
+export function arcadeDecor(rooms: readonly Room[]): ArcadeDecor {
+ const snack = rooms.find((r) => r.kind === "snack");
+ const hall = rooms.find((r) => r.kind === "arcade");
+ return {
+ tables: snack ? snackTables(snack) : [],
+ pad: hall
+ ? { minX: hall.maxX - 3.9, maxX: hall.maxX - 1.5, minZ: hall.minZ + 0.9, maxZ: hall.minZ + 3.3 }
+ : { minX: 0, maxX: 0, minZ: 0, maxZ: 0 },
+ medallion: hall ? { x: hall.minX + 6.6, z: hall.maxZ - 3.6, r: 1.5 } : { x: 0, z: 0, r: 0 },
+ };
+}
+
+/** The spot in front of a cabinet where the person stands to play it. */
+export function cabinetPlaySpot(item: Pick<Furniture, "x" | "z" | "rotationY">): Point {
+ return { x: item.x + Math.sin(item.rotationY) * CABINET_PLAY_DISTANCE, z: item.z + Math.cos(item.rotationY) * CABINET_PLAY_DISTANCE };
+}
+
+/** Build the arcade floor. Takes no input: the hall is the same for everyone. */
+export function buildArcadeLayout(): OfficeLayout {
+ // The lines of the back walls (north, west) and the railings (south, east).
+ const west = -HALF_W + ARCADE_WALL_INSET, east = HALF_W - ARCADE_WALL_INSET;
+ const north = -HALF_D + ARCADE_WALL_INSET, south = HALF_D - ARCADE_WALL_INSET;
+ const split = west + WEST_COLUMN;
+
+ const prizes: Room = { id: "prizes", kind: "prizes", walled: false, doors: [], minX: west, maxX: split, minZ: north, maxZ: north + PRIZES_DEPTH };
+ const snack: Room = { id: "snack", kind: "snack", walled: false, doors: [], minX: west, maxX: split, minZ: prizes.maxZ, maxZ: south };
+ const hall: Room = { id: "arcade", kind: "arcade", walled: false, doors: [], minX: split, maxX: east, minZ: north, maxZ: south };
+ const rooms = [hall, prizes, snack];
+
+ const piece = (id: string, kind: FurnitureKind, room: RoomKind, x: number, z: number, rotationY = 0): Furniture =>
+ ({ id, kind, x, z, rotationY, room });
+ /** z of a piece facing south whose back stands just in front of its room's name arch. */
+ const underArch = (room: Room, kind: FurnitureKind) => archPosts(room)[0].z + BEHIND_ARCH + FURNITURE_SIZE[kind].d / 2;
+ /** z of a piece facing south with its back against the north wall. */
+ const againstNorth = (kind: FurnitureKind) => north + 0.08 + FURNITURE_SIZE[kind].d / 2;
+ /** x of a piece turned to face east with its back against the west wall. */
+ const againstWest = (kind: FurnitureKind) => west + 0.08 + FURNITURE_SIZE[kind].d / 2;
+ const pcx = (prizes.minX + prizes.maxX) / 2, scx = (snack.minX + snack.maxX) / 2, hcx = (hall.minX + hall.maxX) / 2;
+
+ // The cabinets, in registry order: row A along the north wall under the hall's
+ // arch, row B down the hall's west side facing east, island C in the middle.
+ const slots: { x: number; z: number; rotationY: number }[] = [
+ ...[0, 1, 2, 3].map((i) => ({ x: hcx + (i - 1.5) * CABINET_PITCH, z: underArch(hall, "retroCabinet"), rotationY: 0 })),
+ ...[0, 1, 2].map((i) => ({ x: split + 1.2, z: north + 4.9 + i * CABINET_PITCH, rotationY: Math.PI / 2 })),
+ ...[0, 1, 2].map((i) => ({ x: hcx + (i - 1) * CABINET_PITCH - 1.1, z: north + 5.9, rotationY: 0 })),
+ ];
+ const cabinets: Furniture[] = ARCADE_GAMES.map((game, i) => {
+ const slot = slots[i % slots.length];
+ return piece(cabinetId(game.id), "retroCabinet", "arcade", slot.x, slot.z, slot.rotationY);
+ });
+
+ const elevatorZ = south - 2.7;
+ const elevator = piece("elevator", "elevator", "snack", againstWest("elevator"), elevatorZ, Math.PI / 2);
+ const furniture: Furniture[] = [
+ ...cabinets,
+ // Prize corner: the counter under its arch, the token changer beside it, two claw machines on the west wall.
+ piece("prize-counter", "prizeCounter", "prizes", pcx, underArch(prizes, "prizeCounter")),
+ piece("token-machine", "tokenMachine", "prizes", prizes.maxX - 0.55, againstNorth("tokenMachine") + 0.2),
+ piece("claw-a", "clawMachine", "prizes", againstWest("clawMachine"), prizes.minZ + 2.6, Math.PI / 2),
+ piece("claw-b", "clawMachine", "prizes", againstWest("clawMachine"), prizes.minZ + 3.8, Math.PI / 2),
+ // Snack bar: the counter under its arch; the elevator on the west wall.
+ piece("snack-counter", "snackCounter", "snack", scx, underArch(snack, "snackCounter")),
+ elevator,
+ // Hall: a pinball row on the north wall west of row A, the air-hockey table in the open south-east.
+ ...[0, 1, 2].map((i) => piece(`pinball-${i}`, "pinball", "arcade", split + 1.9 + i * 0.85, againstNorth("pinball"))),
+ piece("air-hockey", "airHockey", "arcade", east - 3.7, south - 4.7),
+ ];
+
+ // The elevator's doors face east into the snack bar; its stop is the floor in front of them.
+ const elevatorStop: Checkpoint = { id: "elevator", room: "snack", x: elevator.x + 0.95, z: elevator.z, radius: 1.0 };
+ const decor = arcadeDecor(rooms);
+ const walls = rooms.flatMap(wallsOf);
+ const obstacles: Rect[] = [
+ ...walls.map(wallRect),
+ ...furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint),
+ ...decor.tables.map((t) => ({ minX: t.x - SNACK_TABLE_HALF, maxX: t.x + SNACK_TABLE_HALF, minZ: t.z - SNACK_TABLE_HALF, maxZ: t.z + SNACK_TABLE_HALF })),
+ // The posts of the open rooms' name arches.
+ ...rooms.filter((r) => !r.walled).flatMap(archPosts).map((p) => ({
+ minX: p.x - ARCH.post / 2, maxX: p.x + ARCH.post / 2, minZ: p.z - ARCH.post / 2, maxZ: p.z + ARCH.post / 2,
+ })),
+ ];
+
+ const bounds: Rect = { minX: -HALF_W, maxX: HALF_W, minZ: -HALF_D, maxZ: HALF_D };
+ return {
+ variant: "arcade",
+ departments: [],
+ // Nobody leads up here; the rect is the prize corner so it stays a real place on the floor.
+ lead: { minX: prizes.minX, maxX: prizes.maxX, minZ: prizes.minZ, maxZ: prizes.maxZ, desks: [] },
+ rooms,
+ walls,
+ furniture,
+ spots: [],
+ checkpoints: [elevatorStop],
+ obstacles,
+ spawn: { x: elevator.x + 1.15, z: elevator.z },
+ arrival: { x: elevator.x + 1.6, z: elevator.z },
+ floor: {
+ minX: bounds.minX + RAIL_CLEARANCE, maxX: bounds.maxX - RAIL_CLEARANCE,
+ minZ: bounds.minZ + RAIL_CLEARANCE, maxZ: bounds.maxZ - RAIL_CLEARANCE,
+ },
+ bounds,
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/arcadeGames.ts b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeGames.ts
new file mode 100644
index 0000000000..7018c2bf3e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeGames.ts
@@ -0,0 +1,117 @@
+/**
+ * Every cabinet on the arcade floor, in the order they stand in the hall.
+ *
+ * The metadata (title, cabinet colours, which strings describe it) is cheap
+ * and loaded with the floor; a game's code loads only when someone plays it
+ * or walks up to its screen (`loadRetroGame`). Titles are the games' own
+ * names and stay untranslated; the tagline and the controls line are i18n
+ * keys under `society.arcade.games.<key>`.
+ *
+ * Asteroid Run is the 3D game from the break room; its cabinet opens the
+ * existing ArcadeCabinet overlay instead of the retro overlay.
+ */
+import type { RetroGame } from "./retroGame";
+
+export type RetroGameId =
+ | "neon-snake" | "brick-breaker" | "paddle-duel"
+ | "block-drop" | "maze-muncher" | "desert-dash"
+ | "pixel-raiders" | "road-hopper" | "city-defense";
+
+export type ArcadeGameId = RetroGameId | "asteroid-run";
+
+export interface CabinetLook {
+ /** Cabinet side panels. */
+ body: string;
+ /** Trim, bezel and control panel. */
+ trim: string;
+ /** The lit marquee's background and its title colour. */
+ marquee: string;
+ marqueeText: string;
+ /** The neon accent: side stripes, the glow on the floor, the joystick ball. */
+ accent: string;
+}
+
+export interface ArcadeGameInfo {
+ id: ArcadeGameId;
+ /** The game's own name, shown on the marquee and the overlay. Never translated. */
+ title: string;
+ /** i18n key segment: `society.arcade.games.<key>.tagline` and `.how`. */
+ key: string;
+ /** "retro" opens RetroArcadeOverlay; "asteroid3d" the break room's 3D ArcadeCabinet. */
+ kind: "retro" | "asteroid3d";
+ look: CabinetLook;
+}
+
+export const ARCADE_GAMES: readonly ArcadeGameInfo[] = [
+ { id: "asteroid-run", title: "Asteroid Run", key: "asteroid_run", kind: "asteroid3d",
+ look: { body: "#1d1a3a", trim: "#0e0c1f", marquee: "#120f2a", marqueeText: "#facc15", accent: "#2dff5a" } },
+ { id: "neon-snake", title: "Neon Snake", key: "neon_snake", kind: "retro",
+ look: { body: "#0f2a1e", trim: "#08140e", marquee: "#06180f", marqueeText: "#5dff9c", accent: "#22e07a" } },
+ { id: "brick-breaker", title: "Brick Breaker", key: "brick_breaker", kind: "retro",
+ look: { body: "#3a1420", trim: "#1c0910", marquee: "#22070f", marqueeText: "#ff7aa8", accent: "#ff3d7f" } },
+ { id: "paddle-duel", title: "Paddle Duel", key: "paddle_duel", kind: "retro",
+ look: { body: "#e8e4d8", trim: "#2a2a2e", marquee: "#151518", marqueeText: "#f5f5f0", accent: "#9aa3ff" } },
+ { id: "block-drop", title: "Block Drop", key: "block_drop", kind: "retro",
+ look: { body: "#14224a", trim: "#0a1126", marquee: "#0b1433", marqueeText: "#7cc4ff", accent: "#3fa2ff" } },
+ { id: "maze-muncher", title: "Maze Muncher", key: "maze_muncher", kind: "retro",
+ look: { body: "#2b1f05", trim: "#120d02", marquee: "#100c02", marqueeText: "#ffd23f", accent: "#ffb800" } },
+ { id: "desert-dash", title: "Desert Dash", key: "desert_dash", kind: "retro",
+ look: { body: "#5a3416", trim: "#2a180a", marquee: "#2b1607", marqueeText: "#ffb36b", accent: "#ff8a3d" } },
+ { id: "pixel-raiders", title: "Pixel Raiders", key: "pixel_raiders", kind: "retro",
+ look: { body: "#1a1035", trim: "#0c0719", marquee: "#0d0820", marqueeText: "#c58bff", accent: "#a855f7" } },
+ { id: "road-hopper", title: "Road Hopper", key: "road_hopper", kind: "retro",
+ look: { body: "#123a2e", trim: "#081a14", marquee: "#071b14", marqueeText: "#b6f36b", accent: "#7ed957" } },
+ { id: "city-defense", title: "City Defense", key: "city_defense", kind: "retro",
+ look: { body: "#3b0d0d", trim: "#1a0505", marquee: "#1c0404", marqueeText: "#ffcf5a", accent: "#ff4b2b" } },
+];
+
+const BY_ID = new Map<string, ArcadeGameInfo>(ARCADE_GAMES.map((g) => [g.id, g]));
+
+/** The game behind a cabinet furniture id (`cabinet-<gameId>`), or null for anything else. */
+export function gameForCabinet(furnitureId: string): ArcadeGameInfo | null {
+ return furnitureId.startsWith(CABINET_PREFIX) ? BY_ID.get(furnitureId.slice(CABINET_PREFIX.length)) ?? null : null;
+}
+
+export function arcadeGame(id: string): ArcadeGameInfo | null {
+ return BY_ID.get(id) ?? null;
+}
+
+/** Cabinets on the arcade floor are furniture of kind "retroCabinet" with the id `cabinet-<gameId>`. */
+export const CABINET_PREFIX = "cabinet-";
+
+export function cabinetId(game: ArcadeGameId): string {
+ return CABINET_PREFIX + game;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type AnyRetroGame = RetroGame<any>;
+
+/** Code-split loaders: a game's module is fetched the first time it is needed. */
+const LOADERS: Record<RetroGameId, () => Promise<{ default: AnyRetroGame }>> = {
+ "neon-snake": () => import("./games/neonSnake"),
+ "brick-breaker": () => import("./games/brickBreaker"),
+ "paddle-duel": () => import("./games/paddleDuel"),
+ "block-drop": () => import("./games/blockDrop"),
+ "maze-muncher": () => import("./games/mazeMuncher"),
+ "desert-dash": () => import("./games/desertDash"),
+ "pixel-raiders": () => import("./games/pixelRaiders"),
+ "road-hopper": () => import("./games/roadHopper"),
+ "city-defense": () => import("./games/cityDefense"),
+};
+
+const loaded = new Map<RetroGameId, Promise<AnyRetroGame>>();
+
+/** Load a retro game's definition (cached; a failed load is retried next time). */
+export function loadRetroGame(id: RetroGameId): Promise<AnyRetroGame> {
+ let pending = loaded.get(id);
+ if (!pending) {
+ pending = LOADERS[id]().then((m) => m.default);
+ pending.catch(() => loaded.delete(id));
+ loaded.set(id, pending);
+ }
+ return pending;
+}
+
+export function isRetroGame(id: ArcadeGameId): id is RetroGameId {
+ return id !== "asteroid-run";
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/arcadeHallLook.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeHallLook.test.ts
new file mode 100644
index 0000000000..8f47c8e3a7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeHallLook.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, it } from "vitest";
+import { Color } from "three";
+import { ARCADE_GAMES } from "./arcadeGames";
+import { drawCarpet, drawGlowSpot, drawPrizeCarpet, drawSnackFloor, drawWallPanels, PartKit } from "./arcadeHallLook";
+import { createLiveScreen, drawScreenFrame, FACE_DRAWINGS, NEON_DRAW, PREVIEW_FPS, type NeonSymbol } from "./arcadeScreens";
+import type { RetroGame } from "./retroGame";
+
+/**
+ * A stand-in 2D context (jsdom has no canvas): every method is recorded, the
+ * gradient and text-metric factories return plain objects.
+ */
+function fakeContext(): { ctx: CanvasRenderingContext2D; calls: string[]; texts: string[] } {
+ const calls: string[] = [];
+ const texts: string[] = [];
+ const state: Record<string, unknown> = {};
+ const gradient = { addColorStop: () => undefined };
+ const ctx = new Proxy(state, {
+ get(target, key) {
+ if (typeof key !== "string") return undefined;
+ if (key in target) return target[key];
+ if (key === "createLinearGradient" || key === "createRadialGradient") return () => gradient;
+ if (key === "measureText") return (text: string) => ({ width: text.length * 10 });
+ return (...args: unknown[]) => {
+ if (key === "fillText" || key === "strokeText") texts.push(String(args[0]));
+ calls.push(`${key}(${args.map((a) => (typeof a === "number" ? a.toFixed(2) : String(a))).join(",")})`);
+ };
+ },
+ set(target, key, value) {
+ if (typeof key === "string") {
+ target[key] = value;
+ calls.push(`${key}=${String(value)}`);
+ }
+ return true;
+ },
+ });
+ return { ctx: ctx as unknown as CanvasRenderingContext2D, calls, texts };
+}
+
+/** Only digits and spaces may be drawn as text, besides a game's own title: everything else is i18n. */
+const NUMERIC = /^[\d\s]*$/;
+
+describe("PartKit", () => {
+ it("merges placed, painted parts into one vertex-coloured geometry", () => {
+ const geometry = new PartKit()
+ .box([1, 2, 3], [1, 0, 0], "#ff0000")
+ .sphere(0.5, [0, 1, 0], "#00ff00")
+ .cylinder(0.2, 0.4, [0, 0, -2], "#0000ff", { rotation: [Math.PI / 2, 0, 0] })
+ .build();
+ const position = geometry.getAttribute("position");
+ const colour = geometry.getAttribute("color");
+ expect(colour.count).toBe(position.count);
+ const red = new Color("#ff0000");
+ expect([colour.getX(0), colour.getY(0), colour.getZ(0)]).toEqual([red.r, red.g, red.b]);
+ const box = geometry.boundingBox!;
+ // The sphere is a polygon: its extent is within a few centimetres of its radius.
+ expect(box.min.x).toBeCloseTo(-0.5, 1);
+ expect(box.max.x).toBeCloseTo(1.5);
+ expect(box.max.y).toBeCloseTo(1.5);
+ expect(box.min.z).toBeCloseTo(-2.2);
+ geometry.dispose();
+ });
+
+ it("builds an empty geometry from no parts", () => {
+ const kit = new PartKit();
+ expect(kit.size).toBe(0);
+ const geometry = kit.build();
+ expect(geometry.getAttribute("position")).toBeUndefined();
+ });
+});
+
+describe("hall surfaces", () => {
+ it.each([
+ ["carpet", drawCarpet], ["prize carpet", drawPrizeCarpet], ["snack floor", drawSnackFloor],
+ ["wall panels", drawWallPanels], ["glow spot", drawGlowSpot],
+ ] as const)("draws the %s the same way every time", (_name, draw) => {
+ const a = fakeContext(), b = fakeContext();
+ draw(a.ctx, 256, 256);
+ draw(b.ctx, 256, 256);
+ expect(a.calls.length).toBeGreaterThan(0);
+ expect(a.calls).toEqual(b.calls);
+ expect(a.texts).toEqual([]);
+ });
+});
+
+describe("attract screens", () => {
+ it.each(ARCADE_GAMES.map((g) => [g.id, g] as const))("%s has two different frames with its title and no words", (_id, game) => {
+ const frames = ([0, 1] as const).map((frame) => {
+ const fake = fakeContext();
+ drawScreenFrame(fake.ctx, 0, game, frame);
+ return fake;
+ });
+ expect(frames[0].calls).not.toEqual(frames[1].calls);
+ for (const { texts } of frames) {
+ expect(texts).toContain(game.title);
+ for (const text of texts) if (text !== game.title) expect(text).toMatch(NUMERIC);
+ }
+ });
+
+ it("draws a blank screen for a cabinet without a game", () => {
+ const fake = fakeContext();
+ drawScreenFrame(fake.ctx, 0, null, 0);
+ expect(fake.texts.every((t) => NUMERIC.test(t))).toBe(true);
+ });
+});
+
+describe("machine faces and neon signs", () => {
+ it.each(Object.entries(FACE_DRAWINGS))("%s writes nothing but digits", (_name, draw) => {
+ const fake = fakeContext();
+ draw(fake.ctx, 256, 128);
+ expect(fake.calls.length).toBeGreaterThan(0);
+ for (const text of fake.texts) expect(text).toMatch(NUMERIC);
+ });
+
+ it.each(Object.keys(NEON_DRAW) as NeonSymbol[])("the %s sign is tubes only", (symbol) => {
+ const fake = fakeContext();
+ NEON_DRAW[symbol](fake.ctx, 256);
+ expect(fake.calls.some((c) => c.startsWith("stroke("))).toBe(true);
+ expect(fake.texts).toEqual([]);
+ });
+});
+
+describe("live preview", () => {
+ interface Counter { draws: number }
+ const fakeCanvas = () => {
+ const { ctx } = fakeContext();
+ return { width: 0, height: 0, getContext: () => ctx } as unknown as HTMLCanvasElement;
+ };
+ const game = (draw: (state: Counter, idle: boolean, time: number) => void): RetroGame<Counter> => ({
+ id: "fake", width: 160, height: 120,
+ create: () => ({ draws: 0 }),
+ step: () => undefined,
+ draw: (_ctx, state, info) => draw(state, info.idle, info.time),
+ status: () => ({ score: 0, over: false }),
+ });
+
+ it("is unavailable without a 2D canvas", () => {
+ expect(createLiveScreen(game(() => undefined) as RetroGame<unknown>, { canvas: () => null })).toBeNull();
+ });
+
+ it("repaints the game's idle title screen a dozen times a second", () => {
+ const seen: { idle: boolean; time: number }[] = [];
+ let state: Counter | null = null;
+ const screen = createLiveScreen(game((s, idle, time) => { state = s; s.draws += 1; seen.push({ idle, time }); }) as RetroGame<unknown>,
+ { canvas: fakeCanvas });
+ expect(screen).not.toBeNull();
+ screen!.tick(0.01);
+ screen!.tick(0.5 / PREVIEW_FPS);
+ expect(state!.draws).toBe(1);
+ screen!.tick(0.6 / PREVIEW_FPS);
+ expect(state!.draws).toBe(2);
+ expect(seen.every((s) => s.idle)).toBe(true);
+ expect(seen[1].time).toBeGreaterThan(seen[0].time);
+ screen!.dispose();
+ });
+
+ it("freezes on a game that throws while drawing", () => {
+ let calls = 0;
+ const screen = createLiveScreen(game(() => { calls += 1; throw new Error("broken"); }) as RetroGame<unknown>, { canvas: fakeCanvas });
+ screen!.tick(1);
+ screen!.tick(1);
+ expect(calls).toBe(1);
+ });
+
+ it("gives up on a game that cannot start", () => {
+ const broken: RetroGame<unknown> = { ...game(() => undefined), create: () => { throw new Error("no start"); } } as RetroGame<unknown>;
+ expect(createLiveScreen(broken, { canvas: fakeCanvas })).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/arcadeHallLook.ts b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeHallLook.ts
new file mode 100644
index 0000000000..4e7f26b247
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeHallLook.ts
@@ -0,0 +1,282 @@
+/**
+ * The arcade floor's look: its palette, the blacklight carpet and the room
+ * floors, and a small kit that bakes many coloured primitives into ONE
+ * geometry with vertex colours.
+ *
+ * The kit is why ten cabinets, a pinball row and shelves full of plush cost
+ * a handful of draw calls: every matte part of a prop shares one material
+ * (`HALL_MAT.paint`), every glowing part another (`HALL_MAT.glow`), and the
+ * colour of each part lives in the geometry. Kits are built once per prop
+ * kind (or per game for cabinets) and shared by every copy.
+ */
+import {
+ BoxGeometry, BufferGeometry, Color, CylinderGeometry, DoubleSide, Euler, Float32BufferAttribute, Matrix4, MeshBasicMaterial,
+ MeshStandardMaterial, Quaternion, SphereGeometry, Vector3,
+} from "three";
+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";
+
+export type Vec3 = [number, number, number];
+
+/** The arcade floor's colours. Neon on midnight: magenta, cyan, yellow, violet and green. */
+export const HALL = {
+ /** The night round the floating floor, and its fog. */
+ space: "#0b0718",
+ /** Hemisphere light: a violet sky and a dark plum bounce off the carpet. */
+ sky: "#c9b8ff",
+ ground: "#2a1638",
+ sun: "#ece6ff",
+ slabEdge: "#130d22",
+ /** The glowing rim under the slab's edge. */
+ rim: "#ff3fa4",
+ /** The back walls: midnight panels with a faint pinstripe. */
+ wall: { base: "#160f2c", panel: "#1c1438", groove: "#0d0920" },
+ neon: { magenta: "#ff3fa4", cyan: "#2de2e6", yellow: "#ffd23f", violet: "#8b5cff", green: "#39ff88", orange: "#ff8a3d" },
+ /** The blacklight carpet: near-black ground and its neon squiggles. */
+ carpet: { base: "#0d0a1c", shapes: ["#ff3fa4", "#2de2e6", "#ffd23f", "#8b5cff", "#39ff88"] },
+ /** The prize corner's plum carpet with gold stars, and the snack bar's diner checker. */
+ prizes: { base: "#3a1838", star: "#f5c84a", dot: "#5a2656" },
+ snack: { red: "#7a1f26", cream: "#e9e2d6" },
+ /** Plush prizes on the shelves and in the claw machines. */
+ plush: ["#ff8fc7", "#7fe3ff", "#ffe066", "#b99cff", "#ff9f5a", "#8ff0a4", "#f4f1ea", "#ff6b6b"],
+ chrome: "#cfd3dc",
+ steel: "#2a2a33",
+ black: "#0a0a10",
+} as const;
+
+/** Every vertex-coloured matte part of the hall's props. */
+export const HALL_MAT = {
+ paint: new MeshStandardMaterial({ vertexColors: true, roughness: 0.62, metalness: 0.05 }),
+ /** Chrome, steel and lacquer: the same colours, a shinier finish (barely metallic: the scene has no environment map to reflect). */
+ gloss: new MeshStandardMaterial({ vertexColors: true, roughness: 0.3, metalness: 0.15 }),
+ /** Neon tubes, bulbs and buttons: self-lit, never dimmed by the tone mapper. */
+ glow: new MeshBasicMaterial({ vertexColors: true, toneMapped: false }),
+ glass: new MeshStandardMaterial({
+ color: "#d8ecff", transparent: true, opacity: 0.16, roughness: 0.05, metalness: 0.1, side: DoubleSide, depthWrite: false,
+ }),
+};
+
+/**
+ * Collects primitives, each placed, turned and painted, and merges them into
+ * one geometry with a `color` attribute. Call `build()` once; it frees the parts.
+ */
+export class PartKit {
+ private readonly parts: BufferGeometry[] = [];
+
+ box(size: Vec3, at: Vec3, colour: string, rotation?: Vec3): this {
+ return this.add(new BoxGeometry(size[0], size[1], size[2]), at, colour, rotation);
+ }
+
+ /** An upright cylinder (or cone when `radiusTop` differs) of `height`, centred on `at`. */
+ cylinder(radius: number, height: number, at: Vec3, colour: string, { rotation, radiusTop = radius, segments = 12 }: {
+ rotation?: Vec3; radiusTop?: number; segments?: number;
+ } = {}): this {
+ return this.add(new CylinderGeometry(radiusTop, radius, height, segments), at, colour, rotation);
+ }
+
+ /** A sphere of `radius`, optionally squashed by `scale`. */
+ sphere(radius: number, at: Vec3, colour: string, scale?: Vec3, segments = 10): this {
+ return this.add(new SphereGeometry(radius, segments, Math.max(4, Math.round(segments * 0.7))), at, colour, undefined, scale);
+ }
+
+ add(geometry: BufferGeometry, at: Vec3, colour: string, rotation?: Vec3, scale?: Vec3): this {
+ const turn = new Quaternion().setFromEuler(new Euler(rotation?.[0] ?? 0, rotation?.[1] ?? 0, rotation?.[2] ?? 0));
+ geometry.applyMatrix4(new Matrix4().compose(new Vector3(...at), turn, new Vector3(...(scale ?? [1, 1, 1]))));
+ const c = new Color(colour);
+ const count = geometry.getAttribute("position").count;
+ const colours = new Float32Array(count * 3);
+ for (let i = 0; i < count; i += 1) {
+ colours[i * 3] = c.r;
+ colours[i * 3 + 1] = c.g;
+ colours[i * 3 + 2] = c.b;
+ }
+ geometry.setAttribute("color", new Float32BufferAttribute(colours, 3));
+ this.parts.push(geometry);
+ return this;
+ }
+
+ get size(): number {
+ return this.parts.length;
+ }
+
+ build(): BufferGeometry {
+ const merged = this.parts.length > 0 ? mergeGeometries(this.parts, false) : null;
+ for (const part of this.parts) part.dispose();
+ this.parts.length = 0;
+ const out = merged ?? new BufferGeometry();
+ out.computeBoundingBox();
+ out.computeBoundingSphere();
+ return out;
+ }
+}
+
+/** Deterministic pseudo-random numbers, so the carpet and the prize shelves never change between loads. */
+export function lcg(seed: number): () => number {
+ let state = seed >>> 0;
+ return () => {
+ state = (state * 1664525 + 1013904223) >>> 0;
+ return state / 0x1_0000_0000;
+ };
+}
+
+type Ctx = CanvasRenderingContext2D;
+
+/** Metres covered by one repeat of the carpet tile and of the room floors. */
+export const CARPET_METRES = 2.6;
+export const ROOM_FLOOR_METRES = 1.6;
+
+/** Draw `paint` at every wrapped copy of the tile, so a shape crossing an edge continues on the other side. */
+function wrapped(w: number, h: number, paint: (dx: number, dy: number) => void): void {
+ for (const dx of [-w, 0, w]) for (const dy of [-h, 0, h]) paint(dx, dy);
+}
+
+/**
+ * The blacklight arcade carpet: a near-black ground scattered with neon
+ * squiggles, rings, triangles, zigzags and specks. Seamless on both axes.
+ */
+export function drawCarpet(ctx: Ctx, w: number, h: number): void {
+ const { base, shapes } = HALL.carpet;
+ const rand = lcg(0xa2cade);
+ ctx.fillStyle = base;
+ ctx.fillRect(0, 0, w, h);
+ // A faint woven speckle first, so the ground is not a flat black.
+ for (let i = 0; i < 2600; i += 1) {
+ ctx.fillStyle = rand() > 0.5 ? "rgba(70,60,120,0.35)" : "rgba(0,0,0,0.4)";
+ ctx.fillRect(Math.floor(rand() * w), Math.floor(rand() * h), 2, 2);
+ }
+ ctx.lineCap = "round";
+ ctx.lineJoin = "round";
+ const pick = () => shapes[Math.floor(rand() * shapes.length)];
+ for (let i = 0; i < 64; i += 1) {
+ const x = rand() * w, y = rand() * h, colour = pick(), size = 10 + rand() * 18, turn = rand() * Math.PI * 2;
+ const kind = i % 5;
+ ctx.strokeStyle = colour;
+ ctx.fillStyle = colour;
+ ctx.lineWidth = 3 + rand() * 2;
+ wrapped(w, h, (dx, dy) => {
+ ctx.save();
+ ctx.translate(x + dx, y + dy);
+ ctx.rotate(turn);
+ ctx.beginPath();
+ if (kind === 0) {
+ // A squiggle: one wave of a sine.
+ for (let s = 0; s <= 12; s += 1) {
+ const px = -size * 1.4 + (s / 12) * size * 2.8, py = Math.sin((s / 12) * Math.PI * 2) * size * 0.35;
+ if (s === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py);
+ }
+ ctx.stroke();
+ } else if (kind === 1) {
+ ctx.arc(0, 0, size * 0.55, 0, Math.PI * 2);
+ ctx.stroke();
+ } else if (kind === 2) {
+ ctx.moveTo(0, -size * 0.7);
+ ctx.lineTo(size * 0.62, size * 0.45);
+ ctx.lineTo(-size * 0.62, size * 0.45);
+ ctx.closePath();
+ ctx.stroke();
+ } else if (kind === 3) {
+ // A zigzag bolt.
+ ctx.moveTo(-size, 0);
+ for (let s = 1; s <= 4; s += 1) ctx.lineTo(-size + s * size * 0.5, s % 2 === 1 ? -size * 0.35 : size * 0.35);
+ ctx.stroke();
+ } else {
+ // A four-point sparkle.
+ ctx.moveTo(0, -size * 0.6);
+ ctx.quadraticCurveTo(0, 0, size * 0.6, 0);
+ ctx.quadraticCurveTo(0, 0, 0, size * 0.6);
+ ctx.quadraticCurveTo(0, 0, -size * 0.6, 0);
+ ctx.quadraticCurveTo(0, 0, 0, -size * 0.6);
+ ctx.fill();
+ }
+ ctx.restore();
+ });
+ }
+ // Small neon specks between the shapes.
+ for (let i = 0; i < 140; i += 1) {
+ ctx.fillStyle = pick();
+ const x = rand() * w, y = rand() * h, r = 1.5 + rand() * 2;
+ wrapped(w, h, (dx, dy) => {
+ ctx.beginPath();
+ ctx.arc(x + dx, y + dy, r, 0, Math.PI * 2);
+ ctx.fill();
+ });
+ }
+}
+
+/** The prize corner's plum carpet: a fine dot grid with small gold stars. Seamless. */
+export function drawPrizeCarpet(ctx: Ctx, w: number, h: number): void {
+ const { base, star, dot } = HALL.prizes;
+ ctx.fillStyle = base;
+ ctx.fillRect(0, 0, w, h);
+ ctx.fillStyle = dot;
+ for (let y = 8; y < h; y += 16) for (let x = 8; x < w; x += 16) ctx.fillRect(x - 1.5, y - 1.5, 3, 3);
+ ctx.fillStyle = star;
+ const cell = w / 4;
+ for (let row = 0; row < 4; row += 1) {
+ for (let col = 0; col < 4; col += 1) {
+ const cx = col * cell + (row % 2 === 0 ? cell / 2 : 0), cy = row * cell + cell / 2;
+ wrapped(w, h, (dx, dy) => {
+ starPath(ctx, cx + dx, cy + dy, cell * 0.16, cell * 0.07);
+ ctx.fill();
+ });
+ }
+ }
+}
+
+/** The snack bar's diner floor: a red and cream checkerboard. Seamless (an even number of tiles). */
+export function drawSnackFloor(ctx: Ctx, w: number, h: number): void {
+ const tiles = 4, size = w / tiles;
+ for (let row = 0; row < tiles; row += 1) {
+ for (let col = 0; col < tiles; col += 1) {
+ ctx.fillStyle = (row + col) % 2 === 0 ? HALL.snack.red : HALL.snack.cream;
+ ctx.fillRect(col * size, row * size, size, size);
+ }
+ }
+ ctx.fillStyle = "rgba(0,0,0,0.12)";
+ for (let i = 0; i <= tiles; i += 1) {
+ ctx.fillRect(i * size - 1, 0, 2, h);
+ ctx.fillRect(0, i * size - 1, w, 2);
+ }
+}
+
+/** Adds a five-point star to the current path (begins a new path). */
+export function starPath(ctx: Ctx, cx: number, cy: number, outer: number, inner: number): void {
+ ctx.beginPath();
+ for (let i = 0; i < 10; i += 1) {
+ const r = i % 2 === 0 ? outer : inner;
+ const a = -Math.PI / 2 + (i * Math.PI) / 5;
+ if (i === 0) ctx.moveTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r);
+ else ctx.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r);
+ }
+ ctx.closePath();
+}
+
+/** A soft white disc fading to transparent: the glow a cabinet throws on the carpet, tinted per instance. */
+export function drawGlowSpot(ctx: Ctx, w: number, h: number): void {
+ ctx.clearRect(0, 0, w, h);
+ const g = ctx.createRadialGradient(w / 2, h / 2, 0, w / 2, h / 2, w / 2);
+ g.addColorStop(0, "rgba(255,255,255,0.55)");
+ g.addColorStop(0.45, "rgba(255,255,255,0.22)");
+ g.addColorStop(1, "rgba(255,255,255,0)");
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, w, h);
+}
+
+/** The back walls: tall midnight panels with dark grooves and a faint violet sheen. Seamless horizontally. */
+export function drawWallPanels(ctx: Ctx, w: number, h: number): void {
+ const { base, panel, groove } = HALL.wall;
+ ctx.fillStyle = base;
+ ctx.fillRect(0, 0, w, h);
+ const panels = 4, pw = w / panels;
+ for (let i = 0; i < panels; i += 1) {
+ const g = ctx.createLinearGradient(0, 0, 0, h);
+ g.addColorStop(0, panel);
+ g.addColorStop(1, base);
+ ctx.fillStyle = g;
+ ctx.fillRect(i * pw + 3, 0, pw - 6, h);
+ ctx.fillStyle = groove;
+ ctx.fillRect(i * pw - 1.5, 0, 3, h);
+ }
+ // A skirting band at the foot.
+ ctx.fillStyle = groove;
+ ctx.fillRect(0, h - h * 0.04, w, h * 0.04);
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/arcadeScreens.ts b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeScreens.ts
new file mode 100644
index 0000000000..695849449e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/arcadeScreens.ts
@@ -0,0 +1,942 @@
+/**
+ * Everything the arcade floor draws on canvases: each cabinet's attract
+ * screen and lit marquee, the neon signs on the back walls, the faces of the
+ * other machines (prize counter, token changer, claw machine, pinball, air
+ * hockey, snack bar) and the live preview of the cabinet the person stands at.
+ *
+ * No words: only the games' own titles (never translated, see arcadeGames),
+ * digits and symbols. Static faces are drawn once and cached; an attract
+ * screen holds two frames stacked in one texture, and the hall flips between
+ * them by moving the texture's offset, so ten cabinets animate for free.
+ */
+import { CanvasTexture, MeshBasicMaterial, MeshStandardMaterial, SRGBColorSpace, type Texture } from "three";
+import { cachedCanvasTexture, canvasMaterial } from "../office/canvasMaterials";
+import type { ArcadeGameId, ArcadeGameInfo, CabinetLook } from "./arcadeGames";
+import { retroFont, seededRandom, type RetroDrawInfo, type RetroGame } from "./retroGame";
+import { HALL, lcg, starPath } from "./arcadeHallLook";
+
+type Ctx = CanvasRenderingContext2D;
+
+/** One attract-screen frame in canvas pixels (4:3, like the cabinets' tubes). */
+export const SCREEN_PX = { w: 256, h: 192 } as const;
+export const MARQUEE_PX = { w: 512, h: 128 } as const;
+
+/** The look of a cabinet whose id names no game (a test piece, a game removed from the registry). */
+export const BLANK_LOOK: CabinetLook = { body: "#1d1a3a", trim: "#0e0c1f", marquee: "#120f2a", marqueeText: "#facc15", accent: "#8b5cff" };
+
+// ---------------------------------------------------------------------------
+// Fonts
+// ---------------------------------------------------------------------------
+
+const fontWaiters = new Set<string>();
+
+/**
+ * Redraw a cached canvas texture once the pixel face has loaded: a texture
+ * drawn before that would keep the fallback font for the whole session.
+ */
+function redrawWhenFontLoads(key: string, texture: Texture | null, draw: (ctx: Ctx, w: number, h: number) => void): void {
+ if (!texture || fontWaiters.has(key) || typeof document === "undefined" || !("fonts" in document)) return;
+ const font = retroFont(20);
+ if (document.fonts.check(font)) return;
+ fontWaiters.add(key);
+ document.fonts.load(font).then(() => {
+ const canvas = texture.image as HTMLCanvasElement | undefined;
+ const ctx = canvas?.getContext?.("2d");
+ if (!canvas || !ctx) return;
+ draw(ctx, canvas.width, canvas.height);
+ texture.needsUpdate = true;
+ }, () => {
+ // The face failed to load: the fallback monospace already on the texture stays, which is legible.
+ });
+}
+
+/** A cached material showing a canvas that writes in the pixel face. */
+function fontCanvasMaterial(key: string, w: number, h: number, draw: (ctx: Ctx, w: number, h: number) => void,
+ options: Parameters<typeof canvasMaterial>[4]): MeshStandardMaterial {
+ const material = canvasMaterial(key, w, h, draw, options);
+ redrawWhenFontLoads(key, material.map, draw);
+ return material;
+}
+
+// ---------------------------------------------------------------------------
+// Pixel helpers
+// ---------------------------------------------------------------------------
+
+/** Paint a little bitmap: each character of `rows` is one block of `size` pixels; "." is empty. */
+function pixels(ctx: Ctx, rows: readonly string[], x: number, y: number, size: number, colours: Record<string, string>): void {
+ rows.forEach((row, r) => {
+ for (let c = 0; c < row.length; c += 1) {
+ const colour = colours[row[c]];
+ if (!colour) continue;
+ ctx.fillStyle = colour;
+ ctx.fillRect(x + c * size, y + r * size, size, size);
+ }
+ });
+}
+
+/** Fit `text` into `room` pixels by shrinking the pixel face from `px` down to `min`. */
+function fitFont(ctx: Ctx, text: string, room: number, px: number, min: number, weight = 700): void {
+ let size = px;
+ ctx.font = retroFont(size, weight);
+ while (size > min && ctx.measureText(text).width > room) {
+ size -= 2;
+ ctx.font = retroFont(size, weight);
+ }
+}
+
+/** Faint horizontal scanlines over a whole screen frame. */
+function scanlines(ctx: Ctx, y0: number, w: number, h: number): void {
+ ctx.fillStyle = "rgba(0,0,0,0.18)";
+ for (let y = 0; y < h; y += 3) ctx.fillRect(0, y0 + y, w, 1);
+}
+
+// ---------------------------------------------------------------------------
+// Attract screens
+// ---------------------------------------------------------------------------
+
+type ScreenArt = (ctx: Ctx, w: number, h: number, frame: 0 | 1, look: CabinetLook) => void;
+
+const ALIEN: readonly (readonly string[])[] = [
+ ["...XXXXX...", ".XXXXXXXXX.", "XX.XX.XX.XX", "XXXXXXXXXXX", ".X.X...X.X.", "X.........X"],
+ ["...XXXXX...", ".XXXXXXXXX.", "XX.XX.XX.XX", "XXXXXXXXXXX", "..X.X.X.X..", ".X.......X."],
+];
+
+const ART: Record<ArcadeGameId, ScreenArt> = {
+ "neon-snake": (ctx, w, h, frame) => {
+ ctx.strokeStyle = "rgba(34,224,122,0.12)";
+ for (let x = 0; x < w; x += 16) ctx.strokeRect(x, 40, 16, h);
+ const path = [[3, 9], [4, 9], [5, 9], [6, 9], [6, 8], [6, 7], [7, 7], [8, 7], [9, 7], [10, 7], [10, 8], [10, 9], [11, 9], [12, 9]];
+ const body = path.slice(frame, frame + 12);
+ body.forEach(([cx, cy], i) => {
+ ctx.fillStyle = i === body.length - 1 ? "#d9ffe9" : i % 2 === 0 ? "#22e07a" : "#5dff9c";
+ ctx.fillRect(cx * 16 + 1, cy * 16 + 1, 14, 14);
+ });
+ ctx.fillStyle = "#ff4d6d";
+ ctx.fillRect(13 * 16 + 3, 6 * 16 + 3, 10, 10);
+ ctx.fillStyle = "#5dff9c";
+ ctx.fillRect(13 * 16 + 8, 6 * 16 - 1, 3, 5);
+ },
+ "brick-breaker": (ctx, w, _h, frame, look) => {
+ const colours = ["#ff3d7f", "#ff8a3d", "#ffd23f", "#39ff88", "#2de2e6"];
+ for (let row = 0; row < 5; row += 1) {
+ for (let col = 0; col < 10; col += 1) {
+ if (frame === 1 && row === 4 && col === 6) continue;
+ ctx.fillStyle = colours[row];
+ ctx.fillRect(8 + col * 24, 44 + row * 11, 22, 9);
+ }
+ }
+ ctx.fillStyle = look.marqueeText;
+ ctx.fillRect(frame === 0 ? 96 : 120, 172, 44, 7);
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(frame === 0 ? 150 : 158, frame === 0 ? 132 : 112, 7, 7);
+ ctx.fillStyle = "rgba(255,255,255,0.08)";
+ ctx.fillRect(0, 186, w, 6);
+ },
+ "paddle-duel": (ctx, w, h, frame) => {
+ ctx.fillStyle = "#f5f5f0";
+ for (let y = 42; y < h; y += 14) ctx.fillRect(w / 2 - 2, y, 4, 8);
+ ctx.fillRect(16, frame === 0 ? 86 : 100, 7, 38);
+ ctx.fillRect(w - 23, frame === 0 ? 120 : 104, 7, 38);
+ ctx.fillRect(frame === 0 ? 88 : 150, frame === 0 ? 110 : 128, 8, 8);
+ ctx.font = retroFont(34, 700);
+ ctx.textAlign = "center";
+ ctx.fillText("3", w / 2 - 40, 76);
+ ctx.fillText("5", w / 2 + 40, 76);
+ },
+ "block-drop": (ctx, _w, h, frame) => {
+ const cell = 12, x0 = 68, wellW = 10;
+ ctx.fillStyle = "#3fa2ff";
+ ctx.fillRect(x0 - 4, 38, 4, h - 38);
+ ctx.fillRect(x0 + wellW * cell, 38, 4, h - 38);
+ const colours = ["#3fa2ff", "#ffd23f", "#ff3d7f", "#39ff88", "#b18cff", "#ff8a3d"];
+ const stack = ["..........", ".....AA...", "B...AAC..D", "BB.EEECCDD", "BFFFEEECDD", "BBFFAACCDD"];
+ stack.forEach((row, r) => {
+ for (let c = 0; c < row.length; c += 1) {
+ if (row[c] === ".") continue;
+ ctx.fillStyle = colours[(row.charCodeAt(c) - 65) % colours.length];
+ ctx.fillRect(x0 + c * cell + 1, h - (stack.length - r) * cell + 1, cell - 2, cell - 2);
+ }
+ });
+ // The falling piece, one row lower on the second frame.
+ ctx.fillStyle = "#b18cff";
+ const py = 64 + frame * cell;
+ for (const [dx, dy] of [[0, 0], [1, 0], [2, 0], [1, 1]]) ctx.fillRect(x0 + (3 + dx) * cell + 1, py + dy * cell + 1, cell - 2, cell - 2);
+ },
+ "maze-muncher": (ctx, w, h, frame) => {
+ ctx.strokeStyle = "#2f6bff";
+ ctx.lineWidth = 3;
+ ctx.strokeRect(10, 42, w - 20, h - 52);
+ for (const [x, y, ww, hh] of [[40, 70, 50, 20], [166, 70, 50, 20], [40, 130, 50, 20], [166, 130, 50, 20], [108, 98, 40, 26]]) {
+ ctx.strokeRect(x, y, ww, hh);
+ }
+ ctx.fillStyle = "#ffd9a0";
+ for (let x = 26; x < w - 20; x += 14) {
+ ctx.fillRect(x, 56, 3, 3);
+ ctx.fillRect(x, h - 26, 3, 3);
+ }
+ const mx = frame === 0 ? 70 : 84, my = 113;
+ ctx.fillStyle = "#ffd23f";
+ ctx.beginPath();
+ const open = frame === 0 ? 0.6 : 0.12;
+ ctx.moveTo(mx, my);
+ ctx.arc(mx, my, 11, open, Math.PI * 2 - open);
+ ctx.closePath();
+ ctx.fill();
+ // A round three-eyed blob with an antenna gives chase.
+ const bx = frame === 0 ? 176 : 166;
+ ctx.fillStyle = "#ff5ad1";
+ ctx.beginPath();
+ ctx.arc(bx, my, 11, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillRect(bx - 1, my - 18, 2, 7);
+ ctx.fillStyle = "#ffffff";
+ for (const dx of [-5, 0, 5]) ctx.fillRect(bx + dx - 1.5, my - 4, 3, 4);
+ },
+ "desert-dash": (ctx, w, h, frame) => {
+ const sky = ctx.createLinearGradient(0, 40, 0, h);
+ sky.addColorStop(0, "#3a1660");
+ sky.addColorStop(1, "#ff8a3d");
+ ctx.fillStyle = sky;
+ ctx.fillRect(0, 40, w, h - 40);
+ ctx.fillStyle = "#ffd23f";
+ ctx.beginPath();
+ ctx.arc(196, 92, 22, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = "#5a3416";
+ ctx.beginPath();
+ ctx.moveTo(0, 160);
+ for (let x = 0; x <= w; x += 8) ctx.lineTo(x, 156 + Math.sin(x * 0.04) * 6);
+ ctx.lineTo(w, h);
+ ctx.lineTo(0, h);
+ ctx.fill();
+ const cx = frame === 0 ? 170 : 150;
+ ctx.fillStyle = "#2f8f4e";
+ ctx.fillRect(cx, 128, 9, 32);
+ ctx.fillRect(cx - 9, 136, 9, 5);
+ ctx.fillRect(cx - 9, 128, 4, 10);
+ ctx.fillRect(cx + 9, 140, 8, 5);
+ ctx.fillRect(cx + 13, 132, 4, 10);
+ // The runner: head, body and legs that swap between frames.
+ ctx.fillStyle = "#ffe8c2";
+ ctx.fillRect(60, 124, 10, 10);
+ ctx.fillRect(58, 134, 12, 14);
+ ctx.fillRect(frame === 0 ? 56 : 62, 148, 5, 10);
+ ctx.fillRect(frame === 0 ? 66 : 60, 148, 5, 10);
+ },
+ "pixel-raiders": (ctx, w, _h, frame) => {
+ const colours = ["#c58bff", "#2de2e6", "#39ff88"];
+ for (let row = 0; row < 3; row += 1) {
+ for (let col = 0; col < 6; col += 1) {
+ pixels(ctx, ALIEN[frame], 22 + col * 36 + frame * 6, 48 + row * 26, 2.5, { X: colours[row] });
+ }
+ }
+ ctx.fillStyle = "#39ff88";
+ ctx.fillRect(116, 172, 24, 8);
+ ctx.fillRect(124, 166, 8, 6);
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(127, frame === 0 ? 140 : 128, 2, 10);
+ ctx.fillStyle = "#5a7d4a";
+ for (const x of [30, 100, 170]) ctx.fillRect(x + 6, 150, 40, 10);
+ ctx.fillStyle = "rgba(255,255,255,0.1)";
+ ctx.fillRect(0, 186, w, 2);
+ },
+ "road-hopper": (ctx, w, h, frame) => {
+ ctx.fillStyle = "#123a6b";
+ ctx.fillRect(0, 44, w, 46);
+ ctx.fillStyle = "#7a4a22";
+ ctx.fillRect(frame === 0 ? 20 : 34, 50, 70, 12);
+ ctx.fillRect(frame === 0 ? 150 : 136, 72, 80, 12);
+ ctx.fillStyle = "#2a2a33";
+ ctx.fillRect(0, 96, w, 70);
+ ctx.fillStyle = "#e9e2d6";
+ for (let x = 0; x < w; x += 24) ctx.fillRect(x + (frame * 12), 130, 12, 2);
+ ctx.fillStyle = "#ff4b2b";
+ ctx.fillRect(frame === 0 ? 30 : 46, 104, 34, 16);
+ ctx.fillStyle = "#ffd23f";
+ ctx.fillRect(frame === 0 ? 190 : 174, 140, 40, 16);
+ ctx.fillStyle = "#3fa2ff";
+ ctx.fillRect(frame === 0 ? 110 : 126, 140, 30, 16);
+ ctx.fillStyle = "#3b6b2e";
+ ctx.fillRect(0, 166, w, h - 166);
+ pixels(ctx, frame === 0 ? ["X.X", "XXX", "X.X"] : [".X.", "XXX", "X.X"], 118, 170, 6, { X: "#7ed957" });
+ },
+ "city-defense": (ctx, w, h, frame) => {
+ ctx.fillStyle = "#0a0f2a";
+ ctx.fillRect(0, 40, w, h - 40);
+ ctx.fillStyle = "#ffffff";
+ for (let i = 0; i < 26; i += 1) ctx.fillRect((i * 97) % w, 44 + ((i * 53) % 70), 1.5, 1.5);
+ ctx.strokeStyle = "#ff4b2b";
+ ctx.lineWidth = 2;
+ for (const [x0, x1] of [[30, 90], [140, 110], [230, 190]]) {
+ const len = frame === 0 ? 0.55 : 0.75;
+ ctx.beginPath();
+ ctx.moveTo(x0, 42);
+ ctx.lineTo(x0 + (x1 - x0) * len, 42 + 120 * len);
+ ctx.stroke();
+ }
+ ctx.fillStyle = frame === 0 ? "rgba(255,207,90,0.85)" : "rgba(255,207,90,0.45)";
+ ctx.beginPath();
+ ctx.arc(176, 96, frame === 0 ? 12 : 18, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = "#ffcf5a";
+ for (const [x, ww, hh] of [[14, 22, 20], [44, 18, 28], [92, 26, 16], [150, 20, 24], [196, 24, 18], [226, 18, 26]]) ctx.fillRect(x, h - 14 - hh, ww, hh);
+ ctx.fillStyle = "#7a4a22";
+ ctx.fillRect(0, h - 14, w, 14);
+ ctx.fillStyle = "#2de2e6";
+ ctx.beginPath();
+ ctx.arc(128, h - 14, 12, Math.PI, 0);
+ ctx.fill();
+ },
+ "asteroid-run": (ctx, w, h, frame) => {
+ ctx.fillStyle = "#07060f";
+ ctx.fillRect(0, 40, w, h - 40);
+ const rand = lcg(0xa57e);
+ for (let i = 0; i < 46; i += 1) {
+ const x = rand() * w, y = 42 + rand() * (h - 44), len = 2 + rand() * 6 + frame * 4;
+ ctx.fillStyle = `rgba(201,212,255,${0.4 + rand() * 0.5})`;
+ ctx.fillRect(x, y, len, 1.5);
+ }
+ ctx.fillStyle = "#8d93b8";
+ for (const [x, y, r] of [[200, 70, 16], [46, 150, 11], [222, 158, 9]]) {
+ ctx.beginPath();
+ for (let k = 0; k < 7; k += 1) {
+ const a = (k / 7) * Math.PI * 2, rr = r * (0.75 + ((k * 7) % 4) * 0.1);
+ if (k === 0) ctx.moveTo(x + Math.cos(a) * rr, y + Math.sin(a) * rr); else ctx.lineTo(x + Math.cos(a) * rr, y + Math.sin(a) * rr);
+ }
+ ctx.fill();
+ }
+ ctx.save();
+ ctx.translate(112, 120);
+ ctx.rotate(Math.PI / 2);
+ ctx.fillStyle = frame === 0 ? "#ffcc33" : "#ff8a3d";
+ ctx.beginPath(); ctx.moveTo(-6, 14); ctx.lineTo(0, frame === 0 ? 34 : 42); ctx.lineTo(6, 14); ctx.closePath(); ctx.fill();
+ ctx.fillStyle = "#e0443e";
+ ctx.beginPath(); ctx.moveTo(-8, 2); ctx.lineTo(-17, 16); ctx.lineTo(-7, 12); ctx.closePath(); ctx.fill();
+ ctx.beginPath(); ctx.moveTo(8, 2); ctx.lineTo(17, 16); ctx.lineTo(7, 12); ctx.closePath(); ctx.fill();
+ ctx.fillStyle = "#eef2f8";
+ ctx.fillRect(-8, -14, 16, 28);
+ ctx.fillStyle = "#3b82f6";
+ ctx.beginPath(); ctx.moveTo(-8, -14); ctx.lineTo(0, -28); ctx.lineTo(8, -14); ctx.closePath(); ctx.fill();
+ ctx.restore();
+ },
+};
+
+/** One attract frame: the game's art, its title on top, a score of zeros and a blinking coin at the foot. */
+export function drawScreenFrame(ctx: Ctx, y0: number, game: ArcadeGameInfo | null, frame: 0 | 1): void {
+ const { w, h } = SCREEN_PX;
+ const look = game?.look ?? BLANK_LOOK;
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(0, y0, w, h);
+ ctx.clip();
+ ctx.translate(0, y0);
+ ctx.fillStyle = "#05040b";
+ ctx.fillRect(0, 0, w, h);
+ if (game) ART[game.id](ctx, w, h, frame, look);
+ // Title band.
+ ctx.fillStyle = "rgba(5,4,11,0.82)";
+ ctx.fillRect(0, 0, w, 38);
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ ctx.fillStyle = look.marqueeText;
+ if (game) {
+ fitFont(ctx, game.title, w - 24, 24, 12);
+ ctx.fillText(game.title, w / 2, 21);
+ }
+ ctx.font = retroFont(11);
+ ctx.textAlign = "left";
+ ctx.fillStyle = "#ffffff";
+ ctx.fillText("000000", 8, 7);
+ // The blinking coin: shown on the first frame only.
+ if (frame === 0) {
+ ctx.fillStyle = "#ffd23f";
+ ctx.beginPath();
+ ctx.arc(w - 14, 8, 5, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ scanlines(ctx, 0, w, h);
+ ctx.restore();
+}
+
+/** Both attract frames stacked: frame 0 on top, frame 1 below. */
+function drawScreens(game: ArcadeGameInfo | null) {
+ return (ctx: Ctx) => {
+ drawScreenFrame(ctx, 0, game, 0);
+ drawScreenFrame(ctx, SCREEN_PX.h, game, 1);
+ };
+}
+
+const framedScreens = new Set<string>();
+
+/**
+ * The cached, self-lit attract screen of a game (null = a blank screen).
+ * Its texture shows one of two stacked frames; `setScreenFrame` flips them.
+ */
+export function screenMaterial(game: ArcadeGameInfo | null): MeshStandardMaterial {
+ const key = `arcade:screen:${game?.id ?? "blank"}`;
+ const material = fontCanvasMaterial(key, SCREEN_PX.w, SCREEN_PX.h * 2, drawScreens(game), { glow: 0.95, fallback: "#120f2a", roughness: 0.35 });
+ if (material.map && !framedScreens.has(key)) {
+ framedScreens.add(key);
+ material.map.repeat.set(1, 0.5);
+ // The canvas's top half is the upper half of the texture (v from 0.5 to 1).
+ material.map.offset.set(0, 0.5);
+ }
+ return material;
+}
+
+/** Show attract frame 0 or 1 on a game's screen. */
+export function setScreenFrame(game: ArcadeGameInfo, frame: 0 | 1): void {
+ const map = screenMaterial(game).map;
+ if (map) map.offset.y = frame === 0 ? 0.5 : 0;
+}
+
+// ---------------------------------------------------------------------------
+// Marquees
+// ---------------------------------------------------------------------------
+
+function drawMarquee(game: ArcadeGameInfo | null) {
+ return (ctx: Ctx, w: number, h: number) => {
+ const look = game?.look ?? BLANK_LOOK;
+ const g = ctx.createLinearGradient(0, 0, 0, h);
+ g.addColorStop(0, look.marquee);
+ g.addColorStop(0.5, look.body);
+ g.addColorStop(1, look.marquee);
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, w, h);
+ ctx.fillStyle = look.accent;
+ ctx.fillRect(0, 6, w, 5);
+ ctx.fillRect(0, h - 11, w, 5);
+ // A pixel star at each end.
+ for (const x of [26, w - 40]) pixels(ctx, ["..X..", ".XXX.", "XXXXX", ".XXX.", "..X.."], x, h / 2 - 10, 4, { X: look.marqueeText });
+ if (!game) return;
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ fitFont(ctx, game.title, w - 120, 62, 28);
+ ctx.shadowColor = look.accent;
+ ctx.shadowBlur = 14;
+ ctx.fillStyle = look.marqueeText;
+ ctx.fillText(game.title, w / 2, h / 2 + 3);
+ ctx.shadowBlur = 0;
+ };
+}
+
+/** The cached lit marquee of a game, its title drawn in the pixel face. */
+export function marqueeMaterial(game: ArcadeGameInfo | null): MeshStandardMaterial {
+ return fontCanvasMaterial(`arcade:marquee:${game?.id ?? "blank"}`, MARQUEE_PX.w, MARQUEE_PX.h, drawMarquee(game),
+ { glow: 1.1, fallback: game?.look.marquee ?? BLANK_LOOK.marquee, roughness: 0.4 });
+}
+
+// ---------------------------------------------------------------------------
+// Neon signs on the back walls
+// ---------------------------------------------------------------------------
+
+export type NeonSymbol = "joystick" | "alien" | "bolt" | "star" | "ticket" | "soda" | "claw" | "coin";
+
+/** Stroke the current path as a neon tube: a wide soft halo, the coloured tube and a pale hot core. */
+function tube(ctx: Ctx, colour: string, width: number): void {
+ ctx.lineCap = "round";
+ ctx.lineJoin = "round";
+ ctx.shadowColor = colour;
+ ctx.shadowBlur = width * 3;
+ ctx.strokeStyle = colour;
+ ctx.lineWidth = width;
+ ctx.stroke();
+ ctx.shadowBlur = width;
+ ctx.stroke();
+ ctx.shadowBlur = 0;
+ ctx.strokeStyle = "rgba(255,255,255,0.85)";
+ ctx.lineWidth = width * 0.35;
+ ctx.stroke();
+}
+
+/** Each neon symbol drawn into an `s` × `s` square. */
+export const NEON_DRAW: Record<NeonSymbol, (ctx: Ctx, s: number) => void> = {
+ joystick: (ctx, s) => {
+ ctx.beginPath();
+ ctx.ellipse(s * 0.5, s * 0.74, s * 0.3, s * 0.1, 0, 0, Math.PI * 2);
+ tube(ctx, HALL.neon.cyan, s * 0.035);
+ ctx.beginPath();
+ ctx.moveTo(s * 0.5, s * 0.72);
+ ctx.lineTo(s * 0.42, s * 0.36);
+ tube(ctx, HALL.neon.cyan, s * 0.035);
+ ctx.beginPath();
+ ctx.arc(s * 0.41, s * 0.28, s * 0.08, 0, Math.PI * 2);
+ tube(ctx, HALL.neon.magenta, s * 0.035);
+ ctx.beginPath();
+ ctx.arc(s * 0.72, s * 0.68, s * 0.04, 0, Math.PI * 2);
+ tube(ctx, HALL.neon.yellow, s * 0.03);
+ },
+ alien: (ctx, s) => {
+ const rows = ALIEN[0], size = s / 15, x0 = s * 0.5 - (rows[0].length * size) / 2, y0 = s * 0.3;
+ rows.forEach((row, r) => {
+ for (let c = 0; c < row.length; c += 1) {
+ if (row[c] !== "X") continue;
+ ctx.beginPath();
+ ctx.rect(x0 + c * size + size * 0.18, y0 + r * size + size * 0.18, size * 0.64, size * 0.64);
+ tube(ctx, HALL.neon.green, size * 0.22);
+ }
+ });
+ },
+ bolt: (ctx, s) => {
+ ctx.beginPath();
+ ctx.moveTo(s * 0.58, s * 0.1);
+ ctx.lineTo(s * 0.32, s * 0.52);
+ ctx.lineTo(s * 0.5, s * 0.52);
+ ctx.lineTo(s * 0.4, s * 0.9);
+ ctx.lineTo(s * 0.7, s * 0.42);
+ ctx.lineTo(s * 0.52, s * 0.42);
+ ctx.closePath();
+ tube(ctx, HALL.neon.yellow, s * 0.035);
+ },
+ star: (ctx, s) => {
+ starPath(ctx, s * 0.5, s * 0.52, s * 0.36, s * 0.15);
+ tube(ctx, HALL.neon.magenta, s * 0.035);
+ for (let i = 0; i < 8; i += 1) {
+ const a = (i / 8) * Math.PI * 2 + 0.2;
+ ctx.beginPath();
+ ctx.moveTo(s * 0.5 + Math.cos(a) * s * 0.42, s * 0.52 + Math.sin(a) * s * 0.42);
+ ctx.lineTo(s * 0.5 + Math.cos(a) * s * 0.47, s * 0.52 + Math.sin(a) * s * 0.47);
+ tube(ctx, HALL.neon.cyan, s * 0.025);
+ }
+ },
+ ticket: (ctx, s) => {
+ const x0 = s * 0.12, x1 = s * 0.88, y0 = s * 0.3, y1 = s * 0.7, r = s * 0.07;
+ ctx.beginPath();
+ ctx.moveTo(x0, y0);
+ ctx.lineTo(x1, y0);
+ ctx.arc(x1, (y0 + y1) / 2, r, -Math.PI / 2, Math.PI / 2, true);
+ ctx.lineTo(x1, y1);
+ ctx.lineTo(x0, y1);
+ ctx.arc(x0, (y0 + y1) / 2, r, Math.PI / 2, -Math.PI / 2, true);
+ ctx.closePath();
+ tube(ctx, HALL.neon.orange, s * 0.03);
+ starPath(ctx, s * 0.5, s * 0.5, s * 0.12, s * 0.05);
+ tube(ctx, HALL.neon.yellow, s * 0.025);
+ },
+ soda: (ctx, s) => {
+ ctx.beginPath();
+ ctx.moveTo(s * 0.32, s * 0.32);
+ ctx.lineTo(s * 0.68, s * 0.32);
+ ctx.lineTo(s * 0.62, s * 0.86);
+ ctx.lineTo(s * 0.38, s * 0.86);
+ ctx.closePath();
+ tube(ctx, HALL.neon.cyan, s * 0.032);
+ ctx.beginPath();
+ ctx.moveTo(s * 0.54, s * 0.32);
+ ctx.lineTo(s * 0.6, s * 0.12);
+ ctx.lineTo(s * 0.7, s * 0.12);
+ tube(ctx, HALL.neon.magenta, s * 0.028);
+ ctx.beginPath();
+ ctx.moveTo(s * 0.36, s * 0.48);
+ ctx.lineTo(s * 0.64, s * 0.48);
+ tube(ctx, HALL.neon.magenta, s * 0.02);
+ },
+ claw: (ctx, s) => {
+ ctx.beginPath();
+ ctx.moveTo(s * 0.5, s * 0.06);
+ ctx.lineTo(s * 0.5, s * 0.3);
+ tube(ctx, HALL.neon.cyan, s * 0.03);
+ ctx.beginPath();
+ ctx.moveTo(s * 0.5, s * 0.3);
+ ctx.quadraticCurveTo(s * 0.26, s * 0.36, s * 0.3, s * 0.56);
+ ctx.moveTo(s * 0.5, s * 0.3);
+ ctx.quadraticCurveTo(s * 0.74, s * 0.36, s * 0.7, s * 0.56);
+ tube(ctx, HALL.neon.cyan, s * 0.03);
+ // The heart it is about to grab.
+ const cx = s * 0.5, cy = s * 0.7, r = s * 0.12;
+ ctx.beginPath();
+ ctx.moveTo(cx, cy + r * 1.2);
+ ctx.bezierCurveTo(cx - r * 2, cy - r * 0.2, cx - r * 0.8, cy - r * 1.6, cx, cy - r * 0.5);
+ ctx.bezierCurveTo(cx + r * 0.8, cy - r * 1.6, cx + r * 2, cy - r * 0.2, cx, cy + r * 1.2);
+ tube(ctx, HALL.neon.magenta, s * 0.03);
+ },
+ coin: (ctx, s) => {
+ ctx.beginPath();
+ ctx.arc(s * 0.5, s * 0.5, s * 0.34, 0, Math.PI * 2);
+ tube(ctx, HALL.neon.yellow, s * 0.035);
+ ctx.beginPath();
+ ctx.arc(s * 0.5, s * 0.5, s * 0.26, 0, Math.PI * 2);
+ tube(ctx, HALL.neon.orange, s * 0.02);
+ starPath(ctx, s * 0.5, s * 0.5, s * 0.14, s * 0.06);
+ tube(ctx, HALL.neon.yellow, s * 0.025);
+ },
+};
+
+const neonMaterials = new Map<NeonSymbol, MeshBasicMaterial>();
+
+/** A neon sign's tubes on a transparent sheet; it glows on its own and lets the wall show between the tubes. */
+export function neonMaterial(symbol: NeonSymbol): MeshBasicMaterial {
+ let material = neonMaterials.get(symbol);
+ if (!material) {
+ const map = cachedCanvasTexture(`arcade:neon:${symbol}`, 256, 256, (ctx, w) => {
+ ctx.clearRect(0, 0, w, w);
+ NEON_DRAW[symbol](ctx, w);
+ });
+ material = map
+ ? new MeshBasicMaterial({ map, transparent: true, depthWrite: false, toneMapped: false })
+ : new MeshBasicMaterial({ color: HALL.neon.magenta, transparent: true, opacity: 0, depthWrite: false });
+ neonMaterials.set(symbol, material);
+ }
+ return material;
+}
+
+let medallion: MeshBasicMaterial | null = null;
+/** The star medallion inlaid in the carpet: a neon ring round a star, on a transparent sheet. */
+export function medallionMaterial(): MeshBasicMaterial {
+ let material = medallion;
+ if (!material) {
+ const map = cachedCanvasTexture("arcade:medallion", 512, 512, (ctx, w) => {
+ ctx.clearRect(0, 0, w, w);
+ ctx.beginPath();
+ ctx.arc(w / 2, w / 2, w * 0.44, 0, Math.PI * 2);
+ tube(ctx, HALL.neon.cyan, w * 0.018);
+ ctx.beginPath();
+ ctx.arc(w / 2, w / 2, w * 0.38, 0, Math.PI * 2);
+ tube(ctx, HALL.neon.magenta, w * 0.012);
+ starPath(ctx, w / 2, w / 2, w * 0.3, w * 0.12);
+ tube(ctx, HALL.neon.yellow, w * 0.018);
+ });
+ material = map
+ ? new MeshBasicMaterial({ map, transparent: true, depthWrite: false, toneMapped: false, polygonOffset: true, polygonOffsetFactor: -2 })
+ : new MeshBasicMaterial({ color: HALL.neon.cyan, transparent: true, opacity: 0, depthWrite: false });
+ medallion = material;
+ }
+ return material;
+}
+
+// ---------------------------------------------------------------------------
+// Faces of the other machines
+// ---------------------------------------------------------------------------
+
+/** The prize counter's lit front: tickets and stars in a row. */
+function drawPrizeSign(ctx: Ctx, w: number, h: number): void {
+ ctx.fillStyle = "#1b0b24";
+ ctx.fillRect(0, 0, w, h);
+ const step = w / 6;
+ for (let i = 0; i < 6; i += 1) {
+ const cx = step * (i + 0.5), cy = h / 2;
+ if (i % 2 === 0) {
+ ctx.fillStyle = HALL.neon.orange;
+ ctx.fillRect(cx - 26, cy - 14, 52, 28);
+ ctx.fillStyle = "#1b0b24";
+ ctx.beginPath();
+ ctx.arc(cx - 26, cy, 6, 0, Math.PI * 2);
+ ctx.arc(cx + 26, cy, 6, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = HALL.neon.yellow;
+ starPath(ctx, cx, cy, 9, 4);
+ ctx.fill();
+ } else {
+ ctx.fillStyle = HALL.neon.magenta;
+ starPath(ctx, cx, cy, 20, 8);
+ ctx.fill();
+ }
+ }
+}
+
+/** The token changer's panel: a bill turning into a stack of coins. */
+function drawTokenFace(ctx: Ctx, w: number, h: number): void {
+ ctx.fillStyle = "#14141c";
+ ctx.fillRect(0, 0, w, h);
+ ctx.fillStyle = "#39ff88";
+ ctx.fillRect(w * 0.2, h * 0.1, w * 0.6, h * 0.2);
+ ctx.fillStyle = "#14141c";
+ ctx.beginPath();
+ ctx.arc(w / 2, h * 0.2, h * 0.06, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = "#ffffff";
+ ctx.beginPath();
+ ctx.moveTo(w / 2 - 12, h * 0.38);
+ ctx.lineTo(w / 2 + 12, h * 0.38);
+ ctx.lineTo(w / 2, h * 0.48);
+ ctx.closePath();
+ ctx.fill();
+ for (let i = 0; i < 4; i += 1) {
+ ctx.fillStyle = i % 2 === 0 ? HALL.neon.yellow : "#e0a92a";
+ ctx.beginPath();
+ ctx.ellipse(w / 2, h * 0.82 - i * h * 0.07, w * 0.22, h * 0.05, 0, 0, Math.PI * 2);
+ ctx.fill();
+ }
+}
+
+/** The claw machine's lit header: a heart between two stars. */
+function drawClawHeader(ctx: Ctx, w: number, h: number): void {
+ const g = ctx.createLinearGradient(0, 0, w, 0);
+ g.addColorStop(0, "#2a0d3a");
+ g.addColorStop(0.5, "#4a1660");
+ g.addColorStop(1, "#2a0d3a");
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, w, h);
+ const cx = w / 2, cy = h / 2, r = h * 0.2;
+ ctx.fillStyle = HALL.neon.magenta;
+ ctx.beginPath();
+ ctx.moveTo(cx, cy + r * 1.3);
+ ctx.bezierCurveTo(cx - r * 2.2, cy - r * 0.2, cx - r * 0.8, cy - r * 1.8, cx, cy - r * 0.5);
+ ctx.bezierCurveTo(cx + r * 0.8, cy - r * 1.8, cx + r * 2.2, cy - r * 0.2, cx, cy + r * 1.3);
+ ctx.fill();
+ ctx.fillStyle = HALL.neon.yellow;
+ for (const x of [w * 0.2, w * 0.8]) {
+ starPath(ctx, x, cy, h * 0.28, h * 0.12);
+ ctx.fill();
+ }
+}
+
+/** A pinball backglass: a ringed planet over a starfield, and the score reels. */
+function drawBackglass(ctx: Ctx, w: number, h: number): void {
+ const g = ctx.createLinearGradient(0, 0, 0, h);
+ g.addColorStop(0, "#1a0b3a");
+ g.addColorStop(1, "#3a1050");
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, w, h);
+ const rand = lcg(0xb411);
+ for (let i = 0; i < 70; i += 1) {
+ ctx.fillStyle = `rgba(255,255,255,${0.3 + rand() * 0.7})`;
+ ctx.fillRect(rand() * w, rand() * h * 0.7, 2, 2);
+ }
+ ctx.fillStyle = HALL.neon.orange;
+ ctx.beginPath();
+ ctx.arc(w * 0.5, h * 0.4, w * 0.2, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.strokeStyle = HALL.neon.cyan;
+ ctx.lineWidth = 6;
+ ctx.beginPath();
+ ctx.ellipse(w * 0.5, h * 0.4, w * 0.36, w * 0.08, -0.25, 0, Math.PI * 2);
+ ctx.stroke();
+ ctx.fillStyle = HALL.neon.magenta;
+ starPath(ctx, w * 0.18, h * 0.18, 16, 7);
+ ctx.fill();
+ ctx.fillStyle = "#05040b";
+ ctx.fillRect(w * 0.12, h * 0.76, w * 0.76, h * 0.16);
+ ctx.fillStyle = HALL.neon.yellow;
+ ctx.font = retroFont(30, 700);
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ ctx.fillText("000000", w / 2, h * 0.84 + 2);
+}
+
+/** A pinball playfield seen from above: lanes, lit inserts, bumper rings and the two flippers. */
+function drawPlayfield(ctx: Ctx, w: number, h: number): void {
+ ctx.fillStyle = "#101a4a";
+ ctx.fillRect(0, 0, w, h);
+ ctx.strokeStyle = "#e9e2d6";
+ ctx.lineWidth = 3;
+ ctx.beginPath();
+ ctx.moveTo(w * 0.85, h);
+ ctx.lineTo(w * 0.85, h * 0.12);
+ ctx.quadraticCurveTo(w * 0.85, 4, w * 0.5, 4);
+ ctx.quadraticCurveTo(w * 0.1, 4, w * 0.1, h * 0.15);
+ ctx.stroke();
+ const inserts = [HALL.neon.magenta, HALL.neon.yellow, HALL.neon.cyan, HALL.neon.green, HALL.neon.orange];
+ for (let i = 0; i < 5; i += 1) {
+ ctx.fillStyle = inserts[i];
+ ctx.beginPath();
+ ctx.moveTo(w * 0.47, h * (0.5 + i * 0.05));
+ ctx.lineTo(w * 0.53, h * (0.5 + i * 0.05));
+ ctx.lineTo(w * 0.5, h * (0.535 + i * 0.05));
+ ctx.closePath();
+ ctx.fill();
+ }
+ ctx.strokeStyle = HALL.neon.cyan;
+ ctx.lineWidth = 4;
+ for (const [x, y] of [[0.32, 0.28], [0.62, 0.24], [0.48, 0.4]]) {
+ ctx.beginPath();
+ ctx.arc(w * x, h * y, w * 0.09, 0, Math.PI * 2);
+ ctx.stroke();
+ }
+ ctx.fillStyle = "#e9e2d6";
+ ctx.save();
+ ctx.translate(w * 0.36, h * 0.9);
+ ctx.rotate(0.45);
+ ctx.fillRect(0, -3, w * 0.16, 6);
+ ctx.restore();
+ ctx.save();
+ ctx.translate(w * 0.64, h * 0.9);
+ ctx.rotate(Math.PI - 0.45);
+ ctx.fillRect(0, -3, w * 0.16, 6);
+ ctx.restore();
+}
+
+/** The air-hockey surface: ice white, a red centre line, blue face-off circles, goal creases and air holes. */
+function drawAirHockey(ctx: Ctx, w: number, h: number): void {
+ ctx.fillStyle = "#e8f4ff";
+ ctx.fillRect(0, 0, w, h);
+ ctx.fillStyle = "rgba(60,90,140,0.25)";
+ for (let y = 10; y < h; y += 16) for (let x = 10; x < w; x += 16) ctx.fillRect(x, y, 2, 2);
+ ctx.fillStyle = "#e0443e";
+ ctx.fillRect(w / 2 - 3, 0, 6, h);
+ ctx.strokeStyle = "#3b82f6";
+ ctx.lineWidth = 5;
+ ctx.beginPath();
+ ctx.arc(w / 2, h / 2, h * 0.22, 0, Math.PI * 2);
+ ctx.stroke();
+ for (const x of [0, w]) {
+ ctx.beginPath();
+ ctx.arc(x, h / 2, h * 0.26, 0, Math.PI * 2);
+ ctx.stroke();
+ }
+ ctx.fillStyle = "#1c2440";
+ ctx.fillRect(0, h / 2 - h * 0.14, 8, h * 0.28);
+ ctx.fillRect(w - 8, h / 2 - h * 0.14, 8, h * 0.28);
+}
+
+/** The snack bar's lit menu strip: burger, fries, soda, popcorn and ice cream, each with a price in coins. */
+function drawSnackMenu(ctx: Ctx, w: number, h: number): void {
+ ctx.fillStyle = "#1a0a0c";
+ ctx.fillRect(0, 0, w, h);
+ const step = w / 5, cy = h * 0.42;
+ const items: ((x: number) => void)[] = [
+ (x) => {
+ ctx.fillStyle = "#e0a24a"; ctx.beginPath(); ctx.arc(x, cy, 18, Math.PI, 0); ctx.fill();
+ ctx.fillStyle = "#6b3a1e"; ctx.fillRect(x - 18, cy + 2, 36, 7);
+ ctx.fillStyle = "#39ff88"; ctx.fillRect(x - 19, cy, 38, 3);
+ ctx.fillStyle = "#e0a24a"; ctx.fillRect(x - 17, cy + 10, 34, 7);
+ },
+ (x) => {
+ ctx.fillStyle = HALL.neon.yellow;
+ for (let i = -3; i <= 3; i += 1) ctx.fillRect(x + i * 4 - 1, cy - 22 + Math.abs(i) * 2, 3, 20);
+ ctx.fillStyle = "#e0443e"; ctx.fillRect(x - 14, cy - 6, 28, 22);
+ },
+ (x) => {
+ ctx.fillStyle = HALL.neon.cyan;
+ ctx.beginPath(); ctx.moveTo(x - 13, cy - 16); ctx.lineTo(x + 13, cy - 16); ctx.lineTo(x + 9, cy + 18); ctx.lineTo(x - 9, cy + 18); ctx.fill();
+ ctx.fillStyle = "#ffffff"; ctx.fillRect(x + 2, cy - 28, 3, 14);
+ },
+ (x) => {
+ ctx.fillStyle = "#fff4d6";
+ for (const [dx, dy] of [[-8, -14], [0, -18], [8, -14], [-4, -8], [5, -9]]) { ctx.beginPath(); ctx.arc(x + dx, cy + dy, 6, 0, Math.PI * 2); ctx.fill(); }
+ ctx.fillStyle = "#e0443e"; ctx.fillRect(x - 13, cy - 8, 26, 26);
+ ctx.fillStyle = "#ffffff"; ctx.fillRect(x - 4, cy - 8, 8, 26);
+ },
+ (x) => {
+ ctx.fillStyle = "#e0a24a";
+ ctx.beginPath(); ctx.moveTo(x - 11, cy - 4); ctx.lineTo(x + 11, cy - 4); ctx.lineTo(x, cy + 20); ctx.fill();
+ ctx.fillStyle = "#ff8fc7"; ctx.beginPath(); ctx.arc(x, cy - 10, 12, 0, Math.PI * 2); ctx.fill();
+ },
+ ];
+ ctx.font = retroFont(16, 700);
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ items.forEach((paint, i) => {
+ const x = step * (i + 0.5);
+ paint(x);
+ // The price: a number of tokens.
+ const price = String([3, 2, 1, 2, 1][i]);
+ ctx.fillStyle = HALL.neon.yellow;
+ ctx.beginPath();
+ ctx.arc(x + 9, h * 0.86, 6, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = "#ffffff";
+ ctx.fillText(price, x - 5, h * 0.86 + 1);
+ });
+}
+
+/** The faces' drawings, by face. */
+export const FACE_DRAWINGS = {
+ prizeSign: drawPrizeSign, token: drawTokenFace, clawHeader: drawClawHeader, backglass: drawBackglass,
+ playfield: drawPlayfield, airHockey: drawAirHockey, snackMenu: drawSnackMenu,
+} as const;
+
+/** The machines' faces, each a cached self-lit material. */
+export const FACES = {
+ prizeSign: () => canvasMaterial("arcade:face:prize", 512, 96, drawPrizeSign, { glow: 0.85, fallback: "#1b0b24" }),
+ token: () => canvasMaterial("arcade:face:token", 128, 160, drawTokenFace, { glow: 0.7, fallback: "#14141c" }),
+ clawHeader: () => canvasMaterial("arcade:face:claw", 256, 64, drawClawHeader, { glow: 0.9, fallback: "#4a1660" }),
+ backglass: () => fontCanvasMaterial("arcade:face:backglass", 256, 256, drawBackglass, { glow: 0.85, fallback: "#2a0d45" }),
+ playfield: () => canvasMaterial("arcade:face:playfield", 128, 256, drawPlayfield, { glow: 0.45, fallback: "#101a4a", roughness: 0.3 }),
+ airHockey: () => canvasMaterial("arcade:face:hockey", 512, 288, drawAirHockey, { glow: 0.3, fallback: "#e8f4ff", roughness: 0.25 }),
+ snackMenu: () => fontCanvasMaterial("arcade:face:menu", 512, 96, drawSnackMenu, { glow: 0.75, fallback: "#1a0a0c" }),
+};
+
+// ---------------------------------------------------------------------------
+// Live preview
+// ---------------------------------------------------------------------------
+
+/** How often the live preview repaints, per second. */
+export const PREVIEW_FPS = 12;
+
+export interface LiveScreen {
+ material: MeshBasicMaterial;
+ /** Advance the preview's clock by `dt` seconds; repaints at PREVIEW_FPS. */
+ tick(dt: number): void;
+ dispose(): void;
+}
+
+function defaultCanvas(): HTMLCanvasElement | null {
+ return typeof document === "undefined" ? null : document.createElement("canvas");
+}
+
+/**
+ * A game's own title screen, repainted a dozen times a second into a canvas
+ * texture of the attract screen's size (the game's frame letterboxed into it).
+ * Null where there is no 2D canvas. A game that throws while drawing freezes
+ * on its last good frame: the preview is decoration, the overlay is the game.
+ */
+export function createLiveScreen(
+ game: RetroGame<unknown>,
+ { seed = 7, canvas = defaultCanvas }: { seed?: number; canvas?: () => HTMLCanvasElement | null } = {},
+): LiveScreen | null {
+ const source = canvas();
+ const output = canvas();
+ if (!source || !output) return null;
+ let sourceCtx: Ctx | null = null, outputCtx: Ctx | null = null;
+ try {
+ sourceCtx = source.getContext("2d");
+ outputCtx = output.getContext("2d");
+ } catch {
+ // jsdom without the canvas package throws "not implemented": no live preview, the static screen stays.
+ return null;
+ }
+ if (!sourceCtx || !outputCtx) return null;
+ let state: unknown;
+ try {
+ state = game.create(seededRandom(seed));
+ } catch {
+ // A game that cannot even start leaves its static attract screen; the overlay reports it when played.
+ return null;
+ }
+ source.width = Math.max(1, game.width);
+ source.height = Math.max(1, game.height);
+ output.width = SCREEN_PX.w;
+ output.height = SCREEN_PX.h;
+ const texture = new CanvasTexture(output);
+ texture.colorSpace = SRGBColorSpace;
+ const material = new MeshBasicMaterial({ map: texture, toneMapped: false });
+ const info: RetroDrawInfo = { time: 0, reduced: false, idle: true };
+ // Letterbox: the largest copy of the game's frame that fits the screen.
+ const scale = Math.min(SCREEN_PX.w / source.width, SCREEN_PX.h / source.height);
+ const dw = source.width * scale, dh = source.height * scale;
+ const dx = (SCREEN_PX.w - dw) / 2, dy = (SCREEN_PX.h - dh) / 2;
+ const src = sourceCtx, out = outputCtx;
+ out.imageSmoothingEnabled = false;
+ let since = Infinity;
+ let broken = false;
+ const paint = () => {
+ try {
+ game.draw(src, state, info);
+ } catch {
+ // See above: a broken draw keeps the last good frame; the game's own overlay reports real errors.
+ broken = true;
+ return;
+ }
+ out.fillStyle = "#05040b";
+ out.fillRect(0, 0, SCREEN_PX.w, SCREEN_PX.h);
+ out.drawImage(source, dx, dy, dw, dh);
+ scanlines(out, 0, SCREEN_PX.w, SCREEN_PX.h);
+ texture.needsUpdate = true;
+ };
+ return {
+ material,
+ tick(dt: number) {
+ if (broken) return;
+ info.time += dt;
+ since += dt;
+ if (since < 1 / PREVIEW_FPS) return;
+ since = 0;
+ paint();
+ },
+ dispose() {
+ texture.dispose();
+ material.dispose();
+ },
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/blockDrop.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/blockDrop.test.ts
new file mode 100644
index 0000000000..9390f0f2a4
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/blockDrop.test.ts
@@ -0,0 +1,249 @@
+import { describe, expect, it } from "vitest";
+import { RETRO_STEP, idleInput, seededRandom, type RetroInput } from "../retroGame";
+import blockDrop, {
+ ARR, CLEAR_TIME, COLS, DAS, HIDDEN, LINE_SCORES, LOCK_DELAY, MAX_LOCK_RESETS, PIECE_COUNT, PIECE_I, PIECE_O, PIECE_T, ROWS, SHAPES,
+ createBlockDrop, fits, gravityInterval, spawnPiece, tryRotate, type BlockDropState,
+} from "./blockDrop";
+
+/** A 2D context stand-in: every call is a no-op, texts are recorded, non-finite numbers are flagged. */
+function fakeContext(texts: string[], bad: string[]): CanvasRenderingContext2D {
+ const target: Record<string, unknown> = {
+ fillText: (s: unknown) => { texts.push(String(s)); },
+ createLinearGradient: () => ({ addColorStop: () => undefined }),
+ createRadialGradient: () => ({ addColorStop: () => undefined }),
+ measureText: (s: string) => ({ width: s.length * 6 }),
+ };
+ return new Proxy(target, {
+ get: (t, key) => {
+ if (typeof key === "string" && key in t) return t[key];
+ return (...args: unknown[]) => {
+ if (args.some((a) => typeof a === "number" && !Number.isFinite(a))) bad.push(String(key));
+ };
+ },
+ set: (t, key, value) => { t[String(key)] = value; return true; },
+ }) as unknown as CanvasRenderingContext2D;
+}
+
+const run = (s: BlockDropState, input: RetroInput, steps: number, random: () => number) => {
+ for (let i = 0; i < steps; i += 1) blockDrop.step(s, input, RETRO_STEP, random);
+};
+const press = (button: "left" | "right" | "up" | "down" | "a" | "b"): RetroInput => {
+ const input = idleInput();
+ input[button] = true;
+ input.pressed[button] = true;
+ return input;
+};
+const hold = (button: "left" | "right" | "down"): RetroInput => {
+ const input = idleInput();
+ input[button] = true;
+ return input;
+};
+/** A fresh run with a given piece falling at a given spot. */
+const withPiece = (kind: number, x = 3, y = 5): BlockDropState => {
+ const s = createBlockDrop(seededRandom(1));
+ s.piece = kind; s.rot = 0; s.px = x; s.py = y; s.active = true; s.lowestRow = y;
+ return s;
+};
+const cellsOf = (s: BlockDropState): Array<[number, number]> => {
+ const shape = SHAPES[s.piece][s.rot];
+ const out: Array<[number, number]> = [];
+ for (let i = 0; i < 4; i += 1) out.push([s.px + shape[i * 2], s.py + shape[i * 2 + 1]]);
+ return out;
+};
+
+describe("block drop", () => {
+ it("starts with a falling piece, an empty well and a full preview queue", () => {
+ const s = blockDrop.create(seededRandom(7));
+ expect(s.active).toBe(true);
+ expect(s.cells.every((c) => c === 0)).toBe(true);
+ expect(s.queue.length).toBeGreaterThanOrEqual(PIECE_COUNT);
+ expect(blockDrop.status(s)).toEqual({ score: 0, level: 1, over: false });
+ expect(blockDrop.width).toBeGreaterThan(0);
+ });
+
+ it("deals every one of the seven pieces once per bag", () => {
+ const random = seededRandom(42);
+ const s = createBlockDrop(random);
+ const dealt: number[] = [s.piece];
+ for (let i = 0; i < 20; i += 1) { spawnPiece(s, random); dealt.push(s.piece); }
+ for (let bag = 0; bag < 3; bag += 1) {
+ expect([...dealt.slice(bag * 7, bag * 7 + 7)].sort()).toEqual([0, 1, 2, 3, 4, 5, 6]);
+ }
+ });
+
+ it("has four distinct rotations that come back round, each a solid four-cell piece", () => {
+ for (let kind = 0; kind < PIECE_COUNT; kind += 1) {
+ const s = withPiece(kind);
+ const start = JSON.stringify(cellsOf(s));
+ for (let r = 0; r < 4; r += 1) expect(tryRotate(s)).toBe(true);
+ expect(s.rot).toBe(0);
+ expect(JSON.stringify(cellsOf(s))).toBe(start);
+ }
+ const t = withPiece(PIECE_T);
+ tryRotate(t);
+ expect(t.rot).toBe(1);
+ // The T pointing right: a vertical bar of three with a nub on its right.
+ expect(cellsOf(t).sort()).toEqual([[4, 5], [4, 6], [4, 7], [5, 6]].sort());
+ });
+
+ it("rotates with up or a, and kicks off a wall instead of refusing", () => {
+ const s = withPiece(PIECE_T);
+ run(s, press("up"), 1, seededRandom(1));
+ expect(s.rot).toBe(1);
+ run(s, idleInput(), 1, seededRandom(1));
+ run(s, press("a"), 1, seededRandom(1));
+ expect(s.rot).toBe(2);
+
+ // A vertical I flush against the right wall would stick out when turned flat: it kicks left.
+ const i = withPiece(PIECE_I, 0, 5);
+ tryRotate(i);
+ i.px = COLS - 3; // vertical I occupies column px + 2 = the last column
+ expect(cellsOf(i).every(([x]) => x === COLS - 1)).toBe(true);
+ expect(tryRotate(i)).toBe(true);
+ expect(cellsOf(i).every(([x]) => x >= 0 && x < COLS)).toBe(true);
+ expect(i.rot).toBe(2);
+ });
+
+ it("refuses a rotation when no kick fits", () => {
+ const s = withPiece(PIECE_I, 3, 10);
+ // Bury the flat I in a one-row slot: no room to stand up anywhere nearby.
+ for (let y = 0; y < ROWS; y += 1) for (let x = 0; x < COLS; x += 1) if (y !== 11) s.cells[y * COLS + x] = 1;
+ for (let x = 0; x < COLS; x += 1) if (x < 3 || x > 6) s.cells[11 * COLS + x] = 1;
+ expect(fits(s, PIECE_I, 0, 3, 10)).toBe(true);
+ expect(tryRotate(s)).toBe(false);
+ expect(s.rot).toBe(0);
+ });
+
+ it("shifts once on press, then auto-repeats after the delay", () => {
+ const s = withPiece(PIECE_O, 4, 5);
+ s.lockTimer = 0;
+ const random = seededRandom(1);
+ run(s, press("left"), 1, random);
+ expect(s.px).toBe(3);
+ const steps = Math.floor(DAS / RETRO_STEP) - 2;
+ run(s, hold("left"), steps, random);
+ expect(s.px).toBe(3);
+ run(s, hold("left"), Math.ceil(ARR / RETRO_STEP) * 2 + 3, random);
+ expect(s.px).toBeLessThan(3);
+ run(s, hold("left"), 60, random);
+ expect(s.px).toBe(0);
+ });
+
+ it("clears a full line, scores it times the level and drops the rows above", () => {
+ const random = seededRandom(3);
+ const s = withPiece(PIECE_I, 3, 5);
+ const bottom = ROWS - 1;
+ for (let x = 0; x < COLS; x += 1) if (x < 3 || x > 6) s.cells[bottom * COLS + x] = 2;
+ s.cells[(bottom - 1) * COLS] = 3; // a lone cell above that should fall one row
+ s.level = 2;
+ run(s, press("b"), 1, random);
+ expect(s.clearing).toBeGreaterThan(0);
+ expect(s.lines).toBe(1);
+ const dropBonus = (bottom - 1 - 5) * 2;
+ expect(s.score).toBe(LINE_SCORES[1] * 2 + dropBonus);
+ run(s, idleInput(), Math.ceil(CLEAR_TIME / RETRO_STEP) + 1, random);
+ expect(s.clearing).toBe(0);
+ expect(s.cells[bottom * COLS]).toBe(3);
+ for (let x = 1; x < COLS; x += 1) expect(s.cells[bottom * COLS + x]).toBe(0);
+ expect(s.active).toBe(true);
+ });
+
+ it("pays more for four lines at once and levels up every ten lines", () => {
+ const random = seededRandom(5);
+ const s = withPiece(PIECE_I, 0, 5);
+ tryRotate(s); // vertical, in column px + 2
+ s.px = -2;
+ expect(fits(s, PIECE_I, 1, -2, 5)).toBe(true);
+ for (let y = ROWS - 4; y < ROWS; y += 1) for (let x = 1; x < COLS; x += 1) s.cells[y * COLS + x] = 5;
+ s.lines = 8;
+ run(s, press("b"), 1, random);
+ expect(s.lines).toBe(12);
+ expect(s.level).toBe(2);
+ expect(s.score).toBe(LINE_SCORES[4] * 1 + (ROWS - 4 - 5) * 2);
+ expect(gravityInterval(2)).toBeLessThan(gravityInterval(1));
+ });
+
+ it("locks a grounded piece after the lock delay, and limits how often moves restart it", () => {
+ const random = seededRandom(9);
+ const s = withPiece(PIECE_O, 4, ROWS - 2);
+ run(s, idleInput(), Math.floor(LOCK_DELAY / RETRO_STEP) - 3, random);
+ expect(s.cells.some((c) => c !== 0)).toBe(false);
+ run(s, idleInput(), 6, random);
+ expect(s.cells[(ROWS - 1) * COLS + 4]).toBe(PIECE_O + 1);
+
+ const t = withPiece(PIECE_T, 4, ROWS - 2);
+ let steps = 0;
+ // Wiggle left and right forever: the piece must still lock eventually.
+ while (t.cells.every((c) => c === 0) && steps < 2000) {
+ run(t, press(steps % 2 === 0 ? "left" : "right"), 1, random);
+ run(t, idleInput(), 5, random);
+ steps += 1;
+ }
+ expect(t.cells.some((c) => c !== 0)).toBe(true);
+ expect(steps).toBeLessThanOrEqual(MAX_LOCK_RESETS + 10);
+ });
+
+ it("soft drop falls faster and scores a point per row", () => {
+ const random = seededRandom(2);
+ const s = withPiece(PIECE_O, 4, 2);
+ run(s, hold("down"), 30, random);
+ expect(s.py).toBeGreaterThan(10);
+ expect(s.score).toBe(s.py - 2);
+ });
+
+ it("tops out when a new piece has no room", () => {
+ const random = seededRandom(4);
+ const s = createBlockDrop(random);
+ for (let y = HIDDEN; y < ROWS; y += 1) for (let x = 0; x < COLS; x += 1) if (x !== 0) s.cells[y * COLS + x] = 1;
+ s.cells[1 * COLS + 4] = 1;
+ s.cells[1 * COLS + 5] = 1;
+ spawnPiece(s, random);
+ expect(s.over).toBe(true);
+ expect(blockDrop.status(s).over).toBe(true);
+ // A finished run ignores input.
+ const score = s.score;
+ run(s, press("b"), 5, random);
+ expect(s.score).toBe(score);
+ });
+
+ it("tops out by stacking pieces in the middle", () => {
+ const random = seededRandom(11);
+ const s = blockDrop.create(random);
+ let steps = 0;
+ while (!s.over && steps < 400) { run(s, press("b"), 1, random); run(s, idleInput(), 30, random); steps += 1; }
+ expect(s.over).toBe(true);
+ });
+
+ it("draws every state without throwing, without words and without bad numbers", () => {
+ const texts: string[] = [];
+ const bad: string[] = [];
+ const ctx = fakeContext(texts, bad);
+ const random = seededRandom(8);
+ const s = blockDrop.create(random);
+ blockDrop.draw(ctx, s, { time: 0, reduced: false, idle: true });
+ blockDrop.draw(ctx, s, { time: 1.3, reduced: true, idle: true });
+ run(s, press("b"), 1, random);
+ blockDrop.draw(ctx, s, { time: 2, reduced: false, idle: false });
+ const line = withPiece(PIECE_I, 3, 5);
+ for (let x = 0; x < COLS; x += 1) if (x < 3 || x > 6) line.cells[(ROWS - 1) * COLS + x] = 2;
+ run(line, press("b"), 1, random);
+ run(line, idleInput(), 5, random);
+ blockDrop.draw(ctx, line, { time: 3, reduced: false, idle: false });
+ blockDrop.draw(ctx, line, { time: 3, reduced: true, idle: true });
+ line.over = true;
+ blockDrop.draw(ctx, line, { time: 4, reduced: false, idle: false });
+ expect(bad).toEqual([]);
+ expect(texts.length).toBeGreaterThan(0);
+ for (const text of texts) expect(text).not.toMatch(/[A-Za-z]/);
+ });
+
+ it("is deterministic for a given seed", () => {
+ const play = () => {
+ const random = seededRandom(123);
+ const s = blockDrop.create(random);
+ for (let i = 0; i < 600; i += 1) blockDrop.step(s, i % 40 === 0 ? press("b") : i % 7 === 0 ? press("left") : idleInput(), RETRO_STEP, random);
+ return [s.score, s.lines, s.piece, Array.from(s.cells).join("")].join("|");
+ };
+ expect(play()).toBe(play());
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/blockDrop.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/blockDrop.ts
new file mode 100644
index 0000000000..e78f0926a0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/blockDrop.ts
@@ -0,0 +1,553 @@
+/**
+ * "Block Drop": the falling-block puzzle cabinet.
+ *
+ * Seven four-cell pieces fall into a 10 × 20 well (plus two hidden rows on
+ * top where pieces appear). Pieces come from a 7-bag, so every seven in a row
+ * hold each shape once and droughts cannot happen. Left / right shift once on
+ * press and then auto-repeat after a short delay (DAS / ARR), `up` or `a`
+ * rotates clockwise with a few simple wall kicks, `down` soft-drops and `b`
+ * hard-drops. A grounded piece locks after half a second; moving or rotating
+ * it buys time, but only a limited number of times, so it cannot stall
+ * forever. Full rows clear after a short animation and score by how many went
+ * at once, times the level; every ten lines the level and the gravity rise.
+ */
+import { type RetroDrawInfo, type RetroGame, type RetroInput, type RetroStatus } from "../retroGame";
+import { drawDigits, drawSparks, emitSpark, sparkPool, stepSparks, type Spark } from "./games2Kit";
+
+export const COLS = 10;
+/** 20 visible rows plus 2 hidden ones on top where pieces spawn. */
+export const ROWS = 22;
+export const HIDDEN = 2;
+
+/** Delayed auto shift: hold this long before a held direction starts repeating... */
+export const DAS = 0.17;
+/** ...then move one column this often. */
+export const ARR = 0.05;
+export const LOCK_DELAY = 0.5;
+/** How often moving or rotating a grounded piece may restart its lock timer. */
+export const MAX_LOCK_RESETS = 15;
+export const CLEAR_TIME = 0.3;
+const SOFT_DROP_INTERVAL = 0.035;
+/** Points for 1, 2, 3 or 4 lines at once, times the level. */
+export const LINE_SCORES: readonly number[] = [0, 100, 300, 500, 800];
+
+/** Piece kinds, in this order: I O T S Z J L. Cells store kind + 1 (0 is empty). */
+export const PIECE_I = 0, PIECE_O = 1, PIECE_T = 2, PIECE_S = 3, PIECE_Z = 4, PIECE_J = 5, PIECE_L = 6;
+export const PIECE_COUNT = 7;
+
+/** Spawn-orientation cells per kind as x, y pairs inside its bounding box (y down). */
+const BASE_CELLS: readonly (readonly number[])[] = [
+ [0, 1, 1, 1, 2, 1, 3, 1], // I
+ [0, 0, 1, 0, 0, 1, 1, 1], // O
+ [1, 0, 0, 1, 1, 1, 2, 1], // T
+ [1, 0, 2, 0, 0, 1, 1, 1], // S
+ [0, 0, 1, 0, 1, 1, 2, 1], // Z
+ [0, 0, 0, 1, 1, 1, 2, 1], // J
+ [2, 0, 0, 1, 1, 1, 2, 1], // L
+];
+const BOX = [4, 2, 3, 3, 3, 3, 3];
+
+/** SHAPES[kind][rotation] = 8 numbers (four x, y pairs), rotated clockwise inside the box. */
+export const SHAPES: readonly (readonly Int8Array[])[] = BASE_CELLS.map((base, kind) => {
+ const n = BOX[kind];
+ const states: Int8Array[] = [Int8Array.from(base)];
+ for (let r = 1; r < 4; r += 1) {
+ const prev = states[r - 1];
+ const next = new Int8Array(8);
+ for (let i = 0; i < 4; i += 1) {
+ // Clockwise in a y-down box: (x, y) -> (n - 1 - y, x).
+ next[i * 2] = kind === PIECE_O ? prev[i * 2] : n - 1 - prev[i * 2 + 1];
+ next[i * 2 + 1] = kind === PIECE_O ? prev[i * 2 + 1] : prev[i * 2];
+ }
+ states.push(next);
+ }
+ return states;
+});
+
+/** Offsets tried in order when a rotation does not fit in place (y < 0 lifts the piece). */
+const KICKS: readonly number[] = [0, 0, -1, 0, 1, 0, 0, -1, -1, -1, 1, -1];
+const KICKS_I: readonly number[] = [0, 0, -1, 0, 1, 0, -2, 0, 2, 0, 0, -1, 0, -2];
+
+export interface BlockDropState {
+ /** COLS × ROWS, row-major from the top; 0 empty, otherwise piece kind + 1. */
+ cells: Uint8Array;
+ /** A piece is falling (false while rows clear or after topping out). */
+ active: boolean;
+ piece: number;
+ rot: number;
+ px: number;
+ py: number;
+ /** Upcoming kinds; refilled a whole shuffled bag at a time, never shorter than 7. */
+ queue: number[];
+ /** Scratch for shuffling the next bag. */
+ bag: number[];
+ gravityTimer: number;
+ lockTimer: number;
+ lockResets: number;
+ /** The lowest row this piece has reached; reaching a new one restores its lock resets. */
+ lowestRow: number;
+ shiftDir: number;
+ shiftTimer: number;
+ /** Seconds left of the line-clear animation; the rows in `clearRows` vanish when it ends. */
+ clearing: number;
+ clearRows: number[];
+ score: number;
+ lines: number;
+ level: number;
+ over: boolean;
+ /** Steps run, so the attract screen knows a run is still untouched. */
+ ticks: number;
+ sparks: Spark[];
+ /** Draw-only juice: the hard-drop kick, the "+points" popup, the level-up glow. */
+ kick: number;
+ popupValue: number;
+ popupRow: number;
+ popupTime: number;
+ levelGlow: number;
+}
+
+export const WIDTH = 200;
+export const HEIGHT = 236;
+const CELL = 11;
+const WELL_X = 8;
+const WELL_Y = 8;
+const PANEL_X = 128;
+const PANEL_W = 64;
+
+const COLORS = ["#4fd8ff", "#ffd84a", "#b06bff", "#5dea6a", "#ff5a6e", "#4a7dff", "#ff9a3d"];
+const STACK_GREY = "#5b6177";
+
+export function gravityInterval(level: number): number {
+ const l = Math.min(20, Math.max(1, level));
+ return Math.pow(0.8 - (l - 1) * 0.007, l - 1);
+}
+
+export function fits(s: BlockDropState, kind: number, rot: number, x: number, y: number): boolean {
+ const shape = SHAPES[kind][rot];
+ for (let i = 0; i < 4; i += 1) {
+ const cx = x + shape[i * 2];
+ const cy = y + shape[i * 2 + 1];
+ if (cx < 0 || cx >= COLS || cy < 0 || cy >= ROWS) return false;
+ if (s.cells[cy * COLS + cx] !== 0) return false;
+ }
+ return true;
+}
+
+function refill(s: BlockDropState, random: () => number): void {
+ while (s.queue.length < PIECE_COUNT) {
+ const bag = s.bag;
+ for (let i = 0; i < PIECE_COUNT; i += 1) bag[i] = i;
+ for (let i = PIECE_COUNT - 1; i > 0; i -= 1) {
+ const j = Math.floor(random() * (i + 1));
+ const t = bag[i]; bag[i] = bag[j]; bag[j] = t;
+ }
+ for (let i = 0; i < PIECE_COUNT; i += 1) s.queue.push(bag[i]);
+ }
+}
+
+/** Take the next piece from the queue; topping out (no room to appear) ends the run. */
+export function spawnPiece(s: BlockDropState, random: () => number): void {
+ const kind = s.queue.shift() ?? PIECE_T;
+ refill(s, random);
+ s.piece = kind;
+ s.rot = 0;
+ s.px = kind === PIECE_O ? 4 : 3;
+ s.py = 1;
+ s.gravityTimer = 0;
+ s.lockTimer = 0;
+ s.lockResets = 0;
+ s.lowestRow = s.py;
+ if (!fits(s, kind, 0, s.px, s.py)) {
+ s.active = false;
+ s.over = true;
+ return;
+ }
+ s.active = true;
+}
+
+export function createBlockDrop(random: () => number): BlockDropState {
+ const s: BlockDropState = {
+ cells: new Uint8Array(COLS * ROWS), active: false, piece: 0, rot: 0, px: 0, py: 0,
+ queue: [], bag: [0, 0, 0, 0, 0, 0, 0],
+ gravityTimer: 0, lockTimer: 0, lockResets: 0, lowestRow: 0, shiftDir: 0, shiftTimer: 0,
+ clearing: 0, clearRows: [], score: 0, lines: 0, level: 1, over: false, ticks: 0,
+ sparks: sparkPool(90), kick: 0, popupValue: 0, popupRow: 0, popupTime: 0, levelGlow: 0,
+ };
+ refill(s, random);
+ spawnPiece(s, random);
+ return s;
+}
+
+function grounded(s: BlockDropState): boolean {
+ return !fits(s, s.piece, s.rot, s.px, s.py + 1);
+}
+
+/** A successful move or turn of a grounded piece restarts its lock timer, a limited number of times. */
+function touchLock(s: BlockDropState, wasGrounded: boolean): void {
+ if ((wasGrounded || grounded(s)) && s.lockResets < MAX_LOCK_RESETS) {
+ s.lockTimer = 0;
+ s.lockResets += 1;
+ }
+}
+
+export function tryShift(s: BlockDropState, dx: number): boolean {
+ if (!fits(s, s.piece, s.rot, s.px + dx, s.py)) return false;
+ const was = grounded(s);
+ s.px += dx;
+ touchLock(s, was);
+ return true;
+}
+
+/** Rotate clockwise, trying the kick offsets in order. */
+export function tryRotate(s: BlockDropState): boolean {
+ if (s.piece === PIECE_O) return true;
+ const next = (s.rot + 1) % 4;
+ const kicks = s.piece === PIECE_I ? KICKS_I : KICKS;
+ const was = grounded(s);
+ for (let i = 0; i < kicks.length; i += 2) {
+ const x = s.px + kicks[i];
+ const y = s.py + kicks[i + 1];
+ if (fits(s, s.piece, next, x, y)) {
+ s.rot = next; s.px = x; s.py = y;
+ touchLock(s, was);
+ return true;
+ }
+ }
+ return false;
+}
+
+/** How many rows the current piece can still fall (also places the ghost). */
+export function dropDistance(s: BlockDropState): number {
+ let d = 0;
+ while (fits(s, s.piece, s.rot, s.px, s.py + d + 1)) d += 1;
+ return d;
+}
+
+function lockPiece(s: BlockDropState, random: () => number): void {
+ const shape = SHAPES[s.piece][s.rot];
+ let allHidden = true;
+ for (let i = 0; i < 4; i += 1) {
+ const cy = s.py + shape[i * 2 + 1];
+ s.cells[cy * COLS + s.px + shape[i * 2]] = s.piece + 1;
+ if (cy >= HIDDEN) allHidden = false;
+ }
+ s.active = false;
+ // Locking entirely above the visible well is a top-out too.
+ if (allHidden) { s.over = true; return; }
+ s.clearRows.length = 0;
+ for (let y = 0; y < ROWS; y += 1) {
+ let full = true;
+ for (let x = 0; x < COLS; x += 1) if (s.cells[y * COLS + x] === 0) { full = false; break; }
+ if (full) s.clearRows.push(y);
+ }
+ const n = s.clearRows.length;
+ if (n === 0) { spawnPiece(s, random); return; }
+ const points = LINE_SCORES[n] * s.level;
+ s.score += points;
+ s.lines += n;
+ const level = Math.max(s.level, 1 + Math.floor(s.lines / 10));
+ if (level > s.level) s.levelGlow = 1;
+ s.level = level;
+ s.clearing = CLEAR_TIME;
+ s.popupValue = points;
+ s.popupRow = s.clearRows[0];
+ s.popupTime = 1.1;
+ for (let r = 0; r < n; r += 1) {
+ const py = WELL_Y + (s.clearRows[r] - HIDDEN) * CELL + CELL / 2;
+ for (let i = 0; i < 12; i += 1) {
+ const px = WELL_X + random() * COLS * CELL;
+ emitSpark(s.sparks, px, py, (random() - 0.5) * 90, -30 - random() * 90, 0.4 + random() * 0.4, n === 4 ? 3 : 2,
+ n === 4 ? COLORS[Math.floor(random() * PIECE_COUNT)] : "#ffffff");
+ }
+ }
+}
+
+/** Remove the cleared rows and let everything above fall into place. */
+function collapseRows(s: BlockDropState): void {
+ let write = ROWS - 1;
+ for (let read = ROWS - 1; read >= 0; read -= 1) {
+ if (s.clearRows.includes(read)) continue;
+ if (write !== read) s.cells.copyWithin(write * COLS, read * COLS, read * COLS + COLS);
+ write -= 1;
+ }
+ for (; write >= 0; write -= 1) s.cells.fill(0, write * COLS, write * COLS + COLS);
+ s.clearRows.length = 0;
+}
+
+function handleShift(s: BlockDropState, input: RetroInput, dt: number): void {
+ if (input.pressed.left) {
+ s.shiftDir = -1; s.shiftTimer = 0; tryShift(s, -1);
+ } else if (input.pressed.right) {
+ s.shiftDir = 1; s.shiftTimer = 0; tryShift(s, 1);
+ } else if ((s.shiftDir === -1 && !input.left) || (s.shiftDir === 1 && !input.right)) {
+ // Let go: fall back to the other direction if it is still held, without an instant move.
+ s.shiftDir = s.shiftDir === -1 ? (input.right ? 1 : 0) : (input.left ? -1 : 0);
+ s.shiftTimer = 0;
+ } else if (s.shiftDir !== 0) {
+ s.shiftTimer += dt;
+ while (s.shiftTimer >= DAS) {
+ if (!tryShift(s, s.shiftDir)) { s.shiftTimer = DAS; break; }
+ s.shiftTimer -= ARR;
+ }
+ }
+}
+
+export function stepBlockDrop(s: BlockDropState, input: RetroInput, dt: number, random: () => number): void {
+ s.ticks += 1;
+ stepSparks(s.sparks, dt, 160);
+ s.kick = Math.max(0, s.kick - dt);
+ s.popupTime = Math.max(0, s.popupTime - dt);
+ s.levelGlow = Math.max(0, s.levelGlow - dt * 0.8);
+ if (s.over) return;
+ if (s.clearing > 0) {
+ s.clearing -= dt;
+ if (s.clearing <= 0) {
+ s.clearing = 0;
+ collapseRows(s);
+ spawnPiece(s, random);
+ }
+ return;
+ }
+ if (!s.active) { spawnPiece(s, random); if (!s.active) return; }
+
+ if (input.pressed.up || input.pressed.a) tryRotate(s);
+ handleShift(s, input, dt);
+
+ if (input.pressed.b) {
+ const d = dropDistance(s);
+ s.py += d;
+ s.score += d * 2;
+ s.kick = 0.12;
+ lockPiece(s, random);
+ return;
+ }
+
+ const soft = input.down;
+ const interval = soft ? Math.min(gravityInterval(s.level), SOFT_DROP_INTERVAL) : gravityInterval(s.level);
+ s.gravityTimer += dt;
+ while (s.gravityTimer >= interval) {
+ if (!fits(s, s.piece, s.rot, s.px, s.py + 1)) { s.gravityTimer = 0; break; }
+ s.gravityTimer -= interval;
+ s.py += 1;
+ if (soft) s.score += 1;
+ if (s.py > s.lowestRow) { s.lowestRow = s.py; s.lockResets = 0; s.lockTimer = 0; }
+ }
+
+ if (grounded(s)) {
+ s.lockTimer += dt;
+ if (s.lockTimer >= LOCK_DELAY - 1e-9) lockPiece(s, random);
+ }
+}
+
+// ---------------------------------------------------------------- drawing
+
+function drawCell(ctx: CanvasRenderingContext2D, x: number, y: number, size: number, color: string): void {
+ ctx.fillStyle = color;
+ ctx.fillRect(x, y, size, size);
+ ctx.fillStyle = "rgba(255,255,255,0.38)";
+ ctx.fillRect(x, y, size, 1);
+ ctx.fillRect(x, y, 1, size);
+ ctx.fillStyle = "rgba(0,0,0,0.35)";
+ ctx.fillRect(x, y + size - 1, size, 1);
+ ctx.fillRect(x + size - 1, y, 1, size);
+ if (size >= 8) {
+ ctx.fillStyle = "rgba(255,255,255,0.55)";
+ ctx.fillRect(x + 2, y + 2, 2, 2);
+ }
+}
+
+/** A piece centred in a box, for the preview panel. */
+function drawPreview(ctx: CanvasRenderingContext2D, kind: number, cx: number, cy: number, size: number): void {
+ const shape = SHAPES[kind][0];
+ let minX = 9, maxX = -9, minY = 9, maxY = -9;
+ for (let i = 0; i < 4; i += 1) {
+ minX = Math.min(minX, shape[i * 2]); maxX = Math.max(maxX, shape[i * 2]);
+ minY = Math.min(minY, shape[i * 2 + 1]); maxY = Math.max(maxY, shape[i * 2 + 1]);
+ }
+ const ox = Math.round(cx - ((maxX - minX + 1) * size) / 2);
+ const oy = Math.round(cy - ((maxY - minY + 1) * size) / 2);
+ for (let i = 0; i < 4; i += 1) {
+ drawCell(ctx, ox + (shape[i * 2] - minX) * size, oy + (shape[i * 2 + 1] - minY) * size, size - 1, COLORS[kind]);
+ }
+}
+
+function panelBox(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number): void {
+ ctx.fillStyle = "#0b1433";
+ ctx.fillRect(x, y, w, h);
+ ctx.strokeStyle = "#2a4a8f";
+ ctx.lineWidth = 1;
+ ctx.strokeRect(x + 0.5, y + 0.5, w - 1, h - 1);
+}
+
+/** A decorative half-built stack for the title screen (letters are piece kinds). */
+const ATTRACT_ROWS = [
+ "J.........",
+ "JJJ....LOO",
+ "ZZTT.LLLOO",
+ "SZZT.ITTTS",
+ "SSZT.IJTSS",
+ "OOTT.IJJJS",
+];
+const KIND_OF: Record<string, number> = { I: 0, O: 1, T: 2, S: 3, Z: 4, J: 5, L: 6 };
+
+function drawWell(ctx: CanvasRenderingContext2D, s: BlockDropState, info: RetroDrawInfo): void {
+ const wellW = COLS * CELL, wellH = (ROWS - HIDDEN) * CELL;
+ ctx.fillStyle = "#070c1f";
+ ctx.fillRect(WELL_X, WELL_Y, wellW, wellH);
+ ctx.fillStyle = "rgba(124,196,255,0.06)";
+ for (let x = 1; x < COLS; x += 1) ctx.fillRect(WELL_X + x * CELL, WELL_Y, 1, wellH);
+ for (let y = 1; y < ROWS - HIDDEN; y += 1) ctx.fillRect(WELL_X, WELL_Y + y * CELL, wellW, 1);
+ // The frame glows up for a moment on a level-up, fading smoothly (no blinking).
+ ctx.strokeStyle = s.levelGlow > 0 ? `rgba(124,196,255,${0.45 + s.levelGlow * 0.55})` : "rgba(63,162,255,0.45)";
+ ctx.lineWidth = s.levelGlow > 0 ? 2 : 1;
+ ctx.strokeRect(WELL_X - 1.5, WELL_Y - 1.5, wellW + 3, wellH + 3);
+
+ const attract = info.idle && s.ticks === 0;
+ if (attract) {
+ const top = ROWS - ATTRACT_ROWS.length;
+ for (let r = 0; r < ATTRACT_ROWS.length; r += 1) {
+ for (let x = 0; x < COLS; x += 1) {
+ const ch = ATTRACT_ROWS[r][x];
+ if (ch === ".") continue;
+ drawCell(ctx, WELL_X + x * CELL, WELL_Y + (top + r - HIDDEN) * CELL, CELL - 1, COLORS[KIND_OF[ch]]);
+ }
+ }
+ // An upright I hovering over the gap it is about to fill.
+ const bob = info.reduced ? 0 : Math.round(Math.sin(info.time * 2) * 3);
+ for (let i = 0; i < 4; i += 1) drawCell(ctx, WELL_X + 4 * CELL, WELL_Y + (7 + i) * CELL + bob, CELL - 1, COLORS[PIECE_I]);
+ ctx.strokeStyle = "rgba(79,216,255,0.35)";
+ for (let i = 0; i < 4; i += 1) ctx.strokeRect(WELL_X + 4 * CELL + 0.5, WELL_Y + (top + 2 + i - HIDDEN) * CELL + 0.5, CELL - 2, CELL - 2);
+ return;
+ }
+
+ const p = s.clearing > 0 ? 1 - s.clearing / CLEAR_TIME : 0;
+ for (let y = HIDDEN; y < ROWS; y += 1) {
+ const clearingRow = s.clearing > 0 && s.clearRows.includes(y);
+ for (let x = 0; x < COLS; x += 1) {
+ const v = s.cells[y * COLS + x];
+ if (v === 0) continue;
+ const px = WELL_X + x * CELL, py = WELL_Y + (y - HIDDEN) * CELL;
+ if (clearingRow) {
+ if (info.reduced) {
+ // Reduced motion: the row simply fades away.
+ ctx.globalAlpha = 1 - p;
+ drawCell(ctx, px, py, CELL - 1, COLORS[v - 1]);
+ ctx.globalAlpha = 1;
+ } else {
+ // Squeeze into a white line that wipes out from the middle.
+ const h = Math.max(1, Math.round((CELL - 1) * (1 - p)));
+ const reach = p * (COLS / 2 + 1);
+ ctx.fillStyle = Math.abs(x + 0.5 - COLS / 2) < reach ? "#ffffff" : COLORS[v - 1];
+ ctx.fillRect(px, py + Math.round((CELL - 1 - h) / 2), CELL - 1, h);
+ }
+ continue;
+ }
+ drawCell(ctx, px, py, CELL - 1, s.over ? STACK_GREY : COLORS[v - 1]);
+ }
+ }
+
+ if (s.active && !s.over) {
+ const shape = SHAPES[s.piece][s.rot];
+ const ghost = s.py + dropDistance(s);
+ ctx.strokeStyle = COLORS[s.piece];
+ ctx.globalAlpha = 0.45;
+ ctx.lineWidth = 1;
+ for (let i = 0; i < 4; i += 1) {
+ const gy = ghost + shape[i * 2 + 1];
+ if (gy < HIDDEN) continue;
+ ctx.strokeRect(WELL_X + (s.px + shape[i * 2]) * CELL + 0.5, WELL_Y + (gy - HIDDEN) * CELL + 0.5, CELL - 2, CELL - 2);
+ }
+ ctx.globalAlpha = 1;
+ // A piece about to lock dims a little, so the lock delay can be read.
+ const settle = grounded(s) ? Math.min(1, s.lockTimer / LOCK_DELAY) : 0;
+ for (let i = 0; i < 4; i += 1) {
+ const cy = s.py + shape[i * 2 + 1];
+ if (cy < HIDDEN) continue;
+ drawCell(ctx, WELL_X + (s.px + shape[i * 2]) * CELL, WELL_Y + (cy - HIDDEN) * CELL, CELL - 1, COLORS[s.piece]);
+ if (settle > 0) {
+ ctx.fillStyle = `rgba(7,12,31,${settle * 0.35})`;
+ ctx.fillRect(WELL_X + (s.px + shape[i * 2]) * CELL, WELL_Y + (cy - HIDDEN) * CELL, CELL - 1, CELL - 1);
+ }
+ }
+ }
+
+ if (s.over) {
+ ctx.fillStyle = "rgba(7,12,31,0.45)";
+ ctx.fillRect(WELL_X, WELL_Y, wellW, wellH);
+ }
+}
+
+function drawPanel(ctx: CanvasRenderingContext2D, s: BlockDropState, info: RetroDrawInfo): void {
+ const attract = info.idle && s.ticks === 0;
+ panelBox(ctx, PANEL_X, WELL_Y, PANEL_W, 46);
+ // A small down-arrow marks the "next" box without words.
+ ctx.fillStyle = "#7cc4ff";
+ ctx.beginPath();
+ ctx.moveTo(PANEL_X + 4, WELL_Y + 4); ctx.lineTo(PANEL_X + 10, WELL_Y + 4); ctx.lineTo(PANEL_X + 7, WELL_Y + 8);
+ ctx.closePath();
+ ctx.fill();
+ drawPreview(ctx, attract ? PIECE_T : s.queue[0], PANEL_X + PANEL_W / 2, WELL_Y + 25, 10);
+ panelBox(ctx, PANEL_X, WELL_Y + 50, 31, 30);
+ panelBox(ctx, PANEL_X + 33, WELL_Y + 50, 31, 30);
+ drawPreview(ctx, attract ? PIECE_L : s.queue[1], PANEL_X + 15.5, WELL_Y + 65, 6);
+ drawPreview(ctx, attract ? PIECE_S : s.queue[2], PANEL_X + 48.5, WELL_Y + 65, 6);
+
+ panelBox(ctx, PANEL_X, WELL_Y + 88, PANEL_W, 26);
+ drawDigits(ctx, s.score, PANEL_X + PANEL_W - 5, WELL_Y + 94, 14, "#ffffff", "right", 600);
+
+ // Level: a double chevron; lines: three stacked bars.
+ panelBox(ctx, PANEL_X, WELL_Y + 120, PANEL_W, 20);
+ ctx.strokeStyle = "#ffd84a";
+ ctx.lineWidth = 2;
+ ctx.beginPath();
+ ctx.moveTo(PANEL_X + 5, WELL_Y + 131); ctx.lineTo(PANEL_X + 9, WELL_Y + 127); ctx.lineTo(PANEL_X + 13, WELL_Y + 131);
+ ctx.moveTo(PANEL_X + 5, WELL_Y + 135); ctx.lineTo(PANEL_X + 9, WELL_Y + 131); ctx.lineTo(PANEL_X + 13, WELL_Y + 135);
+ ctx.stroke();
+ drawDigits(ctx, s.level, PANEL_X + PANEL_W - 5, WELL_Y + 124, 12, "#ffd84a", "right");
+
+ panelBox(ctx, PANEL_X, WELL_Y + 144, PANEL_W, 20);
+ ctx.fillStyle = "#5dea6a";
+ for (let i = 0; i < 3; i += 1) ctx.fillRect(PANEL_X + 5, WELL_Y + 149 + i * 4, 9, 2);
+ drawDigits(ctx, s.lines, PANEL_X + PANEL_W - 5, WELL_Y + 148, 12, "#5dea6a", "right");
+
+ // Progress to the next level as a thin bar.
+ panelBox(ctx, PANEL_X, WELL_Y + 170, PANEL_W, 8);
+ ctx.fillStyle = "#3fa2ff";
+ ctx.fillRect(PANEL_X + 2, WELL_Y + 172, Math.round((PANEL_W - 4) * ((s.lines % 10) / 10)), 4);
+
+ // A little decorative tower of cells at the bottom of the panel.
+ for (let i = 0; i < 4; i += 1) {
+ drawCell(ctx, PANEL_X + 8 + i * 13, WELL_Y + 200, 11, COLORS[(i + 2) % PIECE_COUNT]);
+ if (i % 2 === 0) drawCell(ctx, PANEL_X + 8 + i * 13, WELL_Y + 188, 11, COLORS[(i + 5) % PIECE_COUNT]);
+ }
+}
+
+export function drawBlockDrop(ctx: CanvasRenderingContext2D, s: BlockDropState, info: RetroDrawInfo): void {
+ ctx.fillStyle = "#050916";
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
+ ctx.save();
+ if (!info.reduced && s.kick > 0) ctx.translate(0, Math.round((s.kick / 0.12) * 2));
+ drawWell(ctx, s, info);
+ drawSparks(ctx, s.sparks);
+ if (s.popupTime > 0 && s.popupValue > 0 && !s.over) {
+ const rise = info.reduced ? 0 : (1.1 - s.popupTime) * 14;
+ ctx.globalAlpha = Math.min(1, s.popupTime * 2);
+ drawDigits(ctx, `+${s.popupValue}`, WELL_X + (COLS * CELL) / 2, WELL_Y + (s.popupRow - HIDDEN) * CELL - 10 - rise, 12, "#ffffff", "center", 600);
+ ctx.globalAlpha = 1;
+ }
+ ctx.restore();
+ drawPanel(ctx, s, info);
+}
+
+const blockDrop: RetroGame<BlockDropState> = {
+ id: "block-drop",
+ width: WIDTH,
+ height: HEIGHT,
+ create: (random) => createBlockDrop(random),
+ step: (state, input, dt, random) => stepBlockDrop(state, input, dt, random),
+ draw: (ctx, state, info) => drawBlockDrop(ctx, state, info),
+ status: (state): RetroStatus => ({ score: state.score, level: state.level, over: state.over }),
+};
+
+export default blockDrop;
+
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/brickBreaker.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/brickBreaker.test.ts
new file mode 100644
index 0000000000..c66220e72e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/brickBreaker.test.ts
@@ -0,0 +1,282 @@
+import { describe, expect, it } from "vitest";
+import { RETRO_STEP, idleInput, seededRandom, type RetroInput } from "../retroGame";
+import { recordingContext } from "./games1Kit";
+import brickBreaker, {
+ BALL_R, BRICK_H, BRICK_W, COLS, HEIGHT, LAYOUTS, MAX_LIVES, MAX_SPEED, PADDLE_W, PADDLE_Y, ROWS, SLOW_FACTOR, START_LIVES, WIDE_W, WIDTH,
+ brickIndex, brickX, brickY, currentSpeed, levelSpeed, liveBalls, moveBall, type BrickState, type PowerKind,
+} from "./brickBreaker";
+
+const random = seededRandom(5);
+const fresh = (): BrickState => brickBreaker.create(seededRandom(5));
+const run = (s: BrickState, input: RetroInput, seconds: number): void => {
+ for (let t = 0; t < seconds; t += RETRO_STEP) brickBreaker.step(s, input, RETRO_STEP, random);
+};
+const launchInput = (): RetroInput => {
+ const input = idleInput();
+ input.a = true;
+ input.pressed.a = true;
+ return input;
+};
+const clearBoard = (s: BrickState): void => {
+ s.bricks.fill(0);
+ s.left = 0;
+};
+const placeBrick = (s: BrickState, col: number, row: number, hp: number): void => {
+ s.bricks[brickIndex(col, row)] = hp;
+ s.left += 1;
+};
+/** A free-flying ball at (x, y) with velocity (vx, vy). */
+const flyBall = (s: BrickState, x: number, y: number, vx: number, vy: number) => {
+ const b = s.balls[0];
+ Object.assign(b, { alive: true, stuck: false, x, y, vx, vy });
+ return b;
+};
+
+describe("brick breaker", () => {
+ it("starts with three lives, a full board and the ball on the paddle", () => {
+ const s = fresh();
+ expect(brickBreaker.status(s)).toEqual({ score: 0, lives: START_LIVES, level: 1, over: false });
+ expect(brickBreaker.pointer).toBe(true);
+ const expected = LAYOUTS[0].join("").replace(/\./g, "").length;
+ expect(s.left).toBe(expected);
+ expect(liveBalls(s)).toBe(1);
+ expect(s.balls[0].stuck).toBe(true);
+ expect(s.balls[0].y).toBe(PADDLE_Y - BALL_R);
+ });
+
+ it("has at least five well-formed layouts", () => {
+ expect(LAYOUTS.length).toBeGreaterThanOrEqual(5);
+ for (const layout of LAYOUTS) {
+ expect(layout).toHaveLength(ROWS);
+ for (const row of layout) expect(row).toMatch(new RegExp(`^[.123]{${COLS}}$`));
+ expect(layout.join("").replace(/\./g, "").length).toBeGreaterThan(20);
+ }
+ // The board fits the screen with room above the paddle.
+ expect(brickX(COLS - 1) + BRICK_W).toBeLessThanOrEqual(WIDTH);
+ expect(brickY(ROWS - 1) + BRICK_H).toBeLessThan(PADDLE_Y - 60);
+ });
+
+ it("moves the paddle with the keys and keeps it on screen, carrying the stuck ball", () => {
+ const s = fresh();
+ const x0 = s.paddleX;
+ run(s, { ...idleInput(), right: true }, 0.2);
+ expect(s.paddleX).toBeGreaterThan(x0);
+ expect(s.balls[0].x).toBe(s.paddleX);
+ run(s, { ...idleInput(), right: true }, 3);
+ expect(s.paddleX).toBe(WIDTH - PADDLE_W / 2);
+ run(s, { ...idleInput(), left: true }, 3);
+ expect(s.paddleX).toBe(PADDLE_W / 2);
+ });
+
+ it("follows the pointer when it moves but not while it rests", () => {
+ const s = fresh();
+ const pointed = idleInput();
+ pointed.pointer = { x: 80, y: 100, down: false, clicked: false };
+ brickBreaker.step(s, pointed, RETRO_STEP, random);
+ expect(s.paddleX).toBe(80);
+ const keys = { ...pointed, right: true };
+ run(s, keys, 0.3);
+ expect(s.paddleX).toBeGreaterThan(100);
+ });
+
+ it("launches with A and climbs", () => {
+ const s = fresh();
+ run(s, idleInput(), 0.5);
+ expect(s.balls[0].stuck).toBe(true);
+ brickBreaker.step(s, launchInput(), RETRO_STEP, random);
+ const b = s.balls[0];
+ expect(b.stuck).toBe(false);
+ expect(b.vy).toBeLessThan(0);
+ const y0 = b.y;
+ run(s, idleInput(), 0.1);
+ expect(b.y).toBeLessThan(y0);
+ });
+
+ it("bounces off the paddle at an angle set by where the ball lands", () => {
+ const s = fresh();
+ clearBoard(s);
+ placeBrick(s, 0, 0, 3);
+ const centre = flyBall(s, s.paddleX, PADDLE_Y - 10, 0, 150);
+ moveBall(s, centre, 0.1, random);
+ expect(centre.vy).toBeLessThan(0);
+ expect(Math.abs(centre.vx)).toBeLessThan(5);
+ const edge = flyBall(s, s.paddleX + PADDLE_W / 2 - 1, PADDLE_Y - 10, 0, 150);
+ moveBall(s, edge, 0.1, random);
+ expect(edge.vy).toBeLessThan(0);
+ expect(edge.vx).toBeGreaterThan(100);
+ });
+
+ it("breaks a one-hit brick and wears down a three-hit brick", () => {
+ const s = fresh();
+ clearBoard(s);
+ placeBrick(s, 5, 4, 1);
+ placeBrick(s, 0, 0, 3);
+ const bx = brickX(5) + BRICK_W / 2;
+ const b = flyBall(s, bx, brickY(4) + BRICK_H + 20, 0, -200);
+ moveBall(s, b, 0.2, random);
+ expect(s.bricks[brickIndex(5, 4)]).toBe(0);
+ expect(s.left).toBe(1);
+ expect(s.score).toBeGreaterThan(0);
+ expect(b.vy).toBeGreaterThan(0);
+
+ const tough = brickIndex(0, 0);
+ for (let hit = 3; hit > 0; hit -= 1) {
+ expect(s.bricks[tough]).toBe(hit);
+ const ball = flyBall(s, brickX(0) + BRICK_W / 2, brickY(0) + BRICK_H + 10, 0, -200);
+ moveBall(s, ball, 0.1, random);
+ }
+ expect(s.bricks[tough]).toBe(0);
+ });
+
+ it("never tunnels through a brick, however fast the ball", () => {
+ for (const speed of [2000, 8000, 30000]) {
+ const s = fresh();
+ clearBoard(s);
+ placeBrick(s, 6, 5, 1);
+ placeBrick(s, 0, 0, 3);
+ s.paddleX = WIDTH - PADDLE_W; // out of the way, so the rebound is not returned
+ const x = brickX(6) + BRICK_W / 2;
+ const b = flyBall(s, x, brickY(5) + BRICK_H + 4, 0, -speed);
+ moveBall(s, b, RETRO_STEP, random);
+ expect(s.bricks[brickIndex(6, 5)]).toBe(0);
+ expect(b.vy).toBeGreaterThan(0);
+ // Diagonally, too.
+ placeBrick(s, 3, 3, 1);
+ const d = flyBall(s, brickX(3) - 20, brickY(3) + BRICK_H + 20, speed, -speed);
+ moveBall(s, d, RETRO_STEP, random);
+ expect(s.bricks[brickIndex(3, 3)]).toBe(0);
+ }
+ });
+
+ it("loses a life when the last ball drops and ends the run after three", () => {
+ const s = fresh();
+ for (let life = START_LIVES; life > 0; life -= 1) {
+ expect(s.lives).toBe(life);
+ flyBall(s, 10, HEIGHT - 2, 0, 200);
+ s.paddleX = WIDTH - PADDLE_W;
+ run(s, idleInput(), 0.2);
+ }
+ expect(brickBreaker.status(s)).toMatchObject({ lives: 0, over: true });
+ });
+
+ it("clears the board into the next layout with a bonus", () => {
+ const s = fresh();
+ clearBoard(s);
+ placeBrick(s, 4, 2, 1);
+ flyBall(s, brickX(4) + BRICK_W / 2, brickY(2) + BRICK_H + 6, 0, -150);
+ run(s, idleInput(), 0.1);
+ expect(s.level).toBe(2);
+ expect(s.score).toBeGreaterThanOrEqual(500);
+ expect(s.left).toBe(LAYOUTS[1].join("").replace(/\./g, "").length);
+ expect(s.balls[0].stuck).toBe(true);
+ expect(s.speed).toBe(levelSpeed(2));
+ });
+
+ it("repeats the layouts faster, but never past the cap", () => {
+ expect(levelSpeed(LAYOUTS.length + 1)).toBeGreaterThan(levelSpeed(LAYOUTS.length));
+ expect(levelSpeed(LAYOUTS.length + 1)).toBeGreaterThan(levelSpeed(1));
+ expect(levelSpeed(500)).toBe(MAX_SPEED);
+ const s = fresh();
+ s.speed = 99999;
+ expect(currentSpeed(s)).toBe(MAX_SPEED);
+ brickBreaker.step(s, launchInput(), RETRO_STEP, random);
+ run(s, idleInput(), 0.2);
+ for (const b of s.balls) if (b.alive && !b.stuck) expect(Math.hypot(b.vx, b.vy)).toBeLessThanOrEqual(MAX_SPEED + 1e-6);
+ });
+
+ const catchDrop = (s: BrickState, kind: PowerKind): void => {
+ Object.assign(s.drops[0], { alive: true, kind, x: s.paddleX, y: PADDLE_Y - 6 });
+ run(s, idleInput(), 0.3);
+ };
+
+ it("power-ups: wide paddle, multi-ball, slow ball and an extra life", () => {
+ const wide = fresh();
+ catchDrop(wide, "wide");
+ expect(wide.drops[0].alive).toBe(false);
+ run(wide, idleInput(), 1);
+ expect(wide.paddleW).toBe(WIDE_W);
+
+ const multi = fresh();
+ catchDrop(multi, "multi");
+ expect(liveBalls(multi)).toBe(3);
+
+ const slow = fresh();
+ const before = currentSpeed(slow);
+ catchDrop(slow, "slow");
+ expect(currentSpeed(slow)).toBeCloseTo(before * SLOW_FACTOR);
+
+ const life = fresh();
+ catchDrop(life, "life");
+ expect(life.lives).toBe(START_LIVES + 1);
+ life.lives = MAX_LIVES;
+ catchDrop(life, "life");
+ expect(life.lives).toBe(MAX_LIVES);
+ });
+
+ it("lets a missed capsule fall away", () => {
+ const s = fresh();
+ s.paddleX = 30;
+ Object.assign(s.drops[0], { alive: true, kind: "life", x: 250, y: PADDLE_Y - 6 });
+ run(s, idleInput(), 1);
+ expect(s.drops[0].alive).toBe(false);
+ expect(s.lives).toBe(START_LIVES);
+ });
+
+ it("plays a long automated game without escaping the screen", () => {
+ const rnd = seededRandom(9);
+ const s = brickBreaker.create(rnd);
+ let maxLevel = 1;
+ for (let i = 0; i < 60 * 240 && !s.over; i += 1) {
+ // A decent player: follow the lowest falling ball, slightly off-centre to aim.
+ let target = s.paddleX;
+ let lowest = -1;
+ for (const b of s.balls) if (b.alive && b.y > lowest) { lowest = b.y; target = b.x + (b.vx > 0 ? -8 : 8); }
+ const input = idleInput();
+ input.left = target < s.paddleX - 3;
+ input.right = target > s.paddleX + 3;
+ input.pressed.a = i % 30 === 0;
+ brickBreaker.step(s, input, RETRO_STEP, rnd);
+ maxLevel = Math.max(maxLevel, s.level);
+ for (const b of s.balls) {
+ if (!b.alive) continue;
+ expect(Number.isFinite(b.x) && Number.isFinite(b.y)).toBe(true);
+ expect(b.x).toBeGreaterThanOrEqual(BALL_R - 1e-9);
+ expect(b.x).toBeLessThanOrEqual(WIDTH - BALL_R + 1e-9);
+ expect(b.y).toBeGreaterThanOrEqual(BALL_R - 1e-9);
+ }
+ }
+ expect(s.score).toBeGreaterThan(1000);
+ expect(maxLevel).toBeGreaterThanOrEqual(2);
+ });
+
+ it("draws every state without throwing, words or broken numbers", () => {
+ const s = fresh();
+ s.bricks[brickIndex(1, 1)] = 2;
+ s.hitFlash[brickIndex(1, 1)] = 0.05;
+ const kinds: PowerKind[] = ["wide", "multi", "slow", "life"];
+ kinds.forEach((kind, i) => Object.assign(s.drops[i], { alive: true, kind, x: 40 + i * 50, y: 150 }));
+ for (const info of [
+ { time: 0, reduced: false, idle: true },
+ { time: 1, reduced: false, idle: false },
+ { time: 2, reduced: true, idle: false },
+ ]) {
+ const rec = recordingContext();
+ brickBreaker.draw(rec.ctx, s, info);
+ expect(rec.calls.length).toBeGreaterThan(100);
+ expect(rec.nonFinite).toBe(0);
+ expect(rec.depth).toBe(0);
+ expect(rec.ctx.globalAlpha).toBe(1);
+ for (const text of rec.texts) expect(text).not.toMatch(/[a-z]/i);
+ }
+ s.over = true;
+ s.shake = 0.3;
+ s.flash = 0.5;
+ s.wideTime = 2;
+ s.slowTime = 2;
+ flyBall(s, 100, 100, 50, -50);
+ const rec = recordingContext();
+ brickBreaker.draw(rec.ctx, s, { time: 3, reduced: false, idle: false });
+ expect(rec.nonFinite).toBe(0);
+ expect(rec.depth).toBe(0);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/brickBreaker.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/brickBreaker.ts
new file mode 100644
index 0000000000..ed782edaf2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/brickBreaker.ts
@@ -0,0 +1,603 @@
+/**
+ * "Brick Breaker": keep the ball in play with a paddle and knock out every
+ * brick on the board.
+ *
+ * Where the ball meets the paddle sets its bounce angle (centre = straight
+ * up, the ends = steep), so aiming is a skill. Bricks take one to three hits
+ * and show their damage. The ball moves in substeps no longer than half its
+ * radius, so even a very fast ball cannot pass through a brick between two
+ * frames. Broken bricks sometimes drop a capsule: wide paddle, multi-ball,
+ * slow ball or an extra life — catch it with the paddle. Six board layouts,
+ * then they repeat with a faster ball.
+ */
+import type { RetroGame, RetroInput } from "../retroGame";
+import { clamp, drawScanlines, drawSparks, emitSparks, sparkPool, stepSparks, type SparkPool } from "./games1Kit";
+
+export const WIDTH = 320;
+export const HEIGHT = 240;
+export const COLS = 12;
+export const ROWS = 8;
+export const BRICK_W = 24;
+export const BRICK_H = 10;
+const GAP = 2;
+export const FIELD_X = (WIDTH - (COLS * (BRICK_W + GAP) - GAP)) / 2;
+export const FIELD_Y = 26;
+export const PADDLE_Y = 222;
+export const PADDLE_H = 6;
+export const PADDLE_W = 44;
+export const WIDE_W = 68;
+const PADDLE_SPEED = 260;
+export const BALL_R = 3;
+/** Longest move per collision substep: half the ball's radius, well under a brick's height. */
+const SUBSTEP = BALL_R / 2;
+export const MAX_BALLS = 6;
+const MAX_DROPS = 6;
+/** The ball never goes faster than this (px/s), however long the rally. */
+export const MAX_SPEED = 330;
+/** Steepest bounce off the paddle's ends, from straight up. */
+const MAX_BOUNCE = 1.05;
+/** The ball always keeps at least this much of its speed vertical, so it cannot creep sideways forever. */
+const MIN_VERTICAL = 0.3;
+export const START_LIVES = 3;
+export const MAX_LIVES = 5;
+export const DROP_CHANCE = 0.16;
+export const DROP_SPEED = 55;
+export const WIDE_S = 14;
+export const SLOW_S = 10;
+export const SLOW_FACTOR = 0.65;
+
+export type PowerKind = "wide" | "multi" | "slow" | "life";
+
+/** The boards, top row first; digits are hit points, dots are gaps. */
+export const LAYOUTS: readonly (readonly string[])[] = [
+ [
+ "............",
+ "333333333333",
+ "222222222222",
+ "222222222222",
+ "111111111111",
+ "111111111111",
+ "111111111111",
+ "............",
+ ],
+ [
+ ".....33.....",
+ "....2222....",
+ "...222222...",
+ "..11111111..",
+ ".1111111111.",
+ "111111111111",
+ "............",
+ "............",
+ ],
+ [
+ "3.3.3.3.3.3.",
+ ".2.2.2.2.2.2",
+ "1.1.1.1.1.1.",
+ ".1.1.1.1.1.1",
+ "2.2.2.2.2.2.",
+ ".1.1.1.1.1.1",
+ "............",
+ "............",
+ ],
+ [
+ ".....22.....",
+ "....1331....",
+ "...123321...",
+ "..12333321..",
+ "...123321...",
+ "....1331....",
+ ".....22.....",
+ "............",
+ ],
+ [
+ "333333333333",
+ "3..........3",
+ "3.22222222.3",
+ "3.21111112.3",
+ "3.21111112.3",
+ "3.22222222.3",
+ "3..........3",
+ "3333....3333",
+ ],
+ [
+ "1111........",
+ "..2222......",
+ "....3333....",
+ "......2222..",
+ "........1111",
+ "......2222..",
+ "....3333....",
+ "..2222......",
+ ],
+];
+
+export interface Ball {
+ alive: boolean;
+ /** Riding on the paddle, waiting for launch. */
+ stuck: boolean;
+ x: number; y: number; vx: number; vy: number;
+}
+
+export interface Drop {
+ alive: boolean;
+ kind: PowerKind;
+ x: number; y: number;
+}
+
+export interface BrickState {
+ /** Hit points per brick, row-major; 0 = gone. */
+ bricks: Int8Array;
+ /** Seconds of white flash per brick after a hit. */
+ hitFlash: Float32Array;
+ /** Bricks still standing. */
+ left: number;
+ /** Paddle centre and its current (easing) width. */
+ paddleX: number;
+ paddleW: number;
+ wideTime: number;
+ slowTime: number;
+ /** Fixed pools; `alive` marks the ones in play. */
+ balls: Ball[];
+ drops: Drop[];
+ /** The ball's speed before slow-down (px/s); grows a little with every paddle hit. */
+ speed: number;
+ /** Bricks broken since the ball last touched the paddle. */
+ combo: number;
+ lives: number;
+ level: number;
+ score: number;
+ over: boolean;
+ /** Last pointer x seen; the paddle follows the pointer only when it moves. */
+ pointerX: number | null;
+ time: number;
+ shake: number;
+ flash: number;
+ flashColor: string;
+ sparks: SparkPool;
+}
+
+/** The base ball speed of a level: a little faster per board, much faster each time the boards repeat. */
+export function levelSpeed(level: number): number {
+ const board = (level - 1) % LAYOUTS.length;
+ const loop = Math.floor((level - 1) / LAYOUTS.length);
+ return Math.min(MAX_SPEED, 140 + board * 8 + loop * 45);
+}
+
+export function brickIndex(col: number, row: number): number {
+ return row * COLS + col;
+}
+
+export function brickX(col: number): number {
+ return FIELD_X + col * (BRICK_W + GAP);
+}
+
+export function brickY(row: number): number {
+ return FIELD_Y + row * (BRICK_H + GAP);
+}
+
+export function liveBalls(s: BrickState): number {
+ let n = 0;
+ for (const b of s.balls) if (b.alive) n += 1;
+ return n;
+}
+
+function resetBall(s: BrickState): void {
+ for (const b of s.balls) b.alive = false;
+ const b = s.balls[0];
+ b.alive = true;
+ b.stuck = true;
+ b.vx = 0;
+ b.vy = 0;
+ b.x = s.paddleX;
+ b.y = PADDLE_Y - BALL_R;
+ for (const d of s.drops) d.alive = false;
+ s.wideTime = 0;
+ s.slowTime = 0;
+ s.combo = 0;
+}
+
+/** Lay out the board for `s.level` and put a fresh ball on the paddle. */
+export function loadLevel(s: BrickState): void {
+ const layout = LAYOUTS[(s.level - 1) % LAYOUTS.length];
+ s.left = 0;
+ for (let r = 0; r < ROWS; r += 1) {
+ for (let c = 0; c < COLS; c += 1) {
+ const ch = layout[r][c];
+ const hp = ch === "." ? 0 : Number(ch);
+ s.bricks[brickIndex(c, r)] = hp;
+ s.hitFlash[brickIndex(c, r)] = 0;
+ if (hp > 0) s.left += 1;
+ }
+ }
+ s.speed = levelSpeed(s.level);
+ resetBall(s);
+}
+
+function createBricks(): BrickState {
+ const s: BrickState = {
+ bricks: new Int8Array(COLS * ROWS), hitFlash: new Float32Array(COLS * ROWS), left: 0,
+ paddleX: WIDTH / 2, paddleW: PADDLE_W, wideTime: 0, slowTime: 0,
+ balls: [], drops: [], speed: levelSpeed(1), combo: 0,
+ lives: START_LIVES, level: 1, score: 0, over: false, pointerX: null,
+ time: 0, shake: 0, flash: 0, flashColor: "#ffffff", sparks: sparkPool(160),
+ };
+ for (let i = 0; i < MAX_BALLS; i += 1) s.balls.push({ alive: false, stuck: false, x: 0, y: 0, vx: 0, vy: 0 });
+ for (let i = 0; i < MAX_DROPS; i += 1) s.drops.push({ alive: false, kind: "wide", x: 0, y: 0 });
+ loadLevel(s);
+ return s;
+}
+
+/** The speed every moving ball has right now. */
+export function currentSpeed(s: BrickState): number {
+ return Math.min(MAX_SPEED, s.speed) * (s.slowTime > 0 ? SLOW_FACTOR : 1);
+}
+
+/** Point a ball at `angle` from straight up (negative = left) at `speed`. */
+function aim(b: Ball, angle: number, speed: number): void {
+ b.vx = Math.sin(angle) * speed;
+ b.vy = -Math.cos(angle) * speed;
+}
+
+/** Rescale a ball to `speed`, keeping at least MIN_VERTICAL of it vertical. */
+function normalise(b: Ball, speed: number): void {
+ let len = Math.hypot(b.vx, b.vy);
+ if (len < 1e-6) { b.vx = 0; b.vy = -1; len = 1; }
+ let vx = b.vx / len, vy = b.vy / len;
+ if (Math.abs(vy) < MIN_VERTICAL) {
+ vy = vy < 0 ? -MIN_VERTICAL : MIN_VERTICAL;
+ vx = Math.sign(vx || 1) * Math.sqrt(1 - MIN_VERTICAL * MIN_VERTICAL);
+ }
+ b.vx = vx * speed;
+ b.vy = vy * speed;
+}
+
+const ROW_COLOURS = ["#ff3d7f", "#ff7a3d", "#ffc43d", "#9be15d", "#3de0c4", "#3da2ff", "#8a6bff", "#e05dff"];
+const ROW_LIGHT = ["#ff9cc0", "#ffb48c", "#ffe38c", "#cdf5a8", "#9cf2e3", "#9ccfff", "#c2b3ff", "#f2acff"];
+const ROW_DARK = ["#8a1640", "#8a3a14", "#8a6614", "#4a7a24", "#14806c", "#14548a", "#3e2a9a", "#7a1f8a"];
+const DROP_COLOURS: Record<PowerKind, string> = { wide: "#3da2ff", multi: "#ffc43d", slow: "#3de0c4", life: "#ff3d7f" };
+
+function spawnDrop(s: BrickState, x: number, y: number, random: () => number): void {
+ const slot = s.drops.find((d) => !d.alive);
+ if (!slot) return;
+ const r = random();
+ slot.kind = r < 0.32 ? "wide" : r < 0.62 ? "multi" : r < 0.9 ? "slow" : "life";
+ slot.alive = true;
+ slot.x = x;
+ slot.y = y;
+}
+
+/** Damage the brick at `i`; scores, breaks, maybe drops a capsule, may clear the board. */
+function hitBrick(s: BrickState, i: number, random: () => number): void {
+ const hpBefore = s.bricks[i];
+ s.bricks[i] = hpBefore - 1;
+ s.hitFlash[i] = 0.12;
+ const col = i % COLS, row = Math.floor(i / COLS);
+ const cx = brickX(col) + BRICK_W / 2, cy = brickY(row) + BRICK_H / 2;
+ if (s.bricks[i] > 0) {
+ s.score += 10;
+ emitSparks(s.sparks, cx, cy, 3, 50, "#ffffff", random, 0.25, 1);
+ return;
+ }
+ s.score += 30 + 20 * hpBefore + 10 * Math.min(s.combo, 10);
+ s.combo += 1;
+ s.left -= 1;
+ emitSparks(s.sparks, cx, cy, 12, 110, ROW_COLOURS[row], random, 0.55, 2);
+ if (random() < DROP_CHANCE) spawnDrop(s, cx, cy, random);
+}
+
+/**
+ * Circle against the bricks around the ball. On a hit the ball is pushed out
+ * along the shallower overlap and reflected on that axis; one brick per substep.
+ */
+function collideBricks(s: BrickState, b: Ball, random: () => number): boolean {
+ const pitchX = BRICK_W + GAP, pitchY = BRICK_H + GAP;
+ const c0 = Math.max(0, Math.floor((b.x - BALL_R - FIELD_X) / pitchX));
+ const c1 = Math.min(COLS - 1, Math.floor((b.x + BALL_R - FIELD_X) / pitchX));
+ const r0 = Math.max(0, Math.floor((b.y - BALL_R - FIELD_Y) / pitchY));
+ const r1 = Math.min(ROWS - 1, Math.floor((b.y + BALL_R - FIELD_Y) / pitchY));
+ for (let r = r0; r <= r1; r += 1) {
+ for (let c = c0; c <= c1; c += 1) {
+ const i = brickIndex(c, r);
+ if (s.bricks[i] <= 0) continue;
+ const bx = brickX(c), by = brickY(r);
+ const px = clamp(b.x, bx, bx + BRICK_W), py = clamp(b.y, by, by + BRICK_H);
+ const dx = b.x - px, dy = b.y - py;
+ if (dx * dx + dy * dy > BALL_R * BALL_R) continue;
+ const overlapX = Math.min(b.x + BALL_R - bx, bx + BRICK_W - (b.x - BALL_R));
+ const overlapY = Math.min(b.y + BALL_R - by, by + BRICK_H - (b.y - BALL_R));
+ if (overlapX < overlapY) {
+ const fromLeft = b.x < bx + BRICK_W / 2;
+ b.vx = fromLeft ? -Math.abs(b.vx) : Math.abs(b.vx);
+ b.x = fromLeft ? bx - BALL_R : bx + BRICK_W + BALL_R;
+ } else {
+ const fromAbove = b.y < by + BRICK_H / 2;
+ b.vy = fromAbove ? -Math.abs(b.vy) : Math.abs(b.vy);
+ b.y = fromAbove ? by - BALL_R : by + BRICK_H + BALL_R;
+ }
+ hitBrick(s, i, random);
+ return true;
+ }
+ }
+ return false;
+}
+
+/** Move one ball through walls, paddle and bricks in short substeps. */
+export function moveBall(s: BrickState, b: Ball, dt: number, random: () => number): void {
+ const n = Math.max(1, Math.ceil((Math.hypot(b.vx, b.vy) * dt) / SUBSTEP));
+ const h = dt / n;
+ for (let k = 0; k < n; k += 1) {
+ b.x += b.vx * h;
+ b.y += b.vy * h;
+ if (b.x < BALL_R) { b.x = BALL_R; b.vx = Math.abs(b.vx); }
+ else if (b.x > WIDTH - BALL_R) { b.x = WIDTH - BALL_R; b.vx = -Math.abs(b.vx); }
+ if (b.y < BALL_R) { b.y = BALL_R; b.vy = Math.abs(b.vy); }
+ const half = s.paddleW / 2;
+ if (b.vy > 0 && b.y + BALL_R >= PADDLE_Y && b.y + BALL_R <= PADDLE_Y + PADDLE_H
+ && Math.abs(b.x - s.paddleX) <= half + BALL_R) {
+ const offset = clamp((b.x - s.paddleX) / half, -1, 1);
+ aim(b, offset * MAX_BOUNCE, Math.hypot(b.vx, b.vy));
+ b.y = PADDLE_Y - BALL_R;
+ s.combo = 0;
+ s.speed = Math.min(MAX_SPEED, s.speed + 2);
+ emitSparks(s.sparks, b.x, PADDLE_Y, 4, 60, "#ffd1e0", random, 0.25, 1);
+ }
+ if (collideBricks(s, b, random) && s.left === 0) return;
+ if (b.y - BALL_R > HEIGHT) { b.alive = false; return; }
+ }
+}
+
+function launch(b: Ball, s: BrickState, random: () => number): void {
+ b.stuck = false;
+ let angle = (random() - 0.5) * 0.8;
+ if (Math.abs(angle) < 0.12) angle = angle < 0 ? -0.12 : 0.12;
+ aim(b, angle, currentSpeed(s));
+}
+
+function applyPower(s: BrickState, kind: PowerKind, random: () => number): void {
+ s.score += 50;
+ if (kind === "wide") s.wideTime = WIDE_S;
+ else if (kind === "slow") s.slowTime = SLOW_S;
+ else if (kind === "life") s.lives = Math.min(MAX_LIVES, s.lives + 1);
+ else {
+ const source = s.balls.find((b) => b.alive);
+ if (!source) return;
+ if (source.stuck) launch(source, s, random);
+ const speed = Math.hypot(source.vx, source.vy);
+ const base = Math.atan2(source.vx, -source.vy);
+ for (const turn of [-0.4, 0.4]) {
+ const slot = s.balls.find((b) => !b.alive);
+ if (!slot) break;
+ slot.alive = true;
+ slot.stuck = false;
+ slot.x = source.x;
+ slot.y = source.y;
+ aim(slot, base + turn, speed);
+ normalise(slot, speed);
+ }
+ }
+}
+
+function loseLife(s: BrickState): void {
+ s.lives -= 1;
+ s.shake = 0.4;
+ s.flash = 0.8;
+ s.flashColor = "#ff3d5a";
+ if (s.lives <= 0) {
+ s.lives = 0;
+ s.over = true;
+ return;
+ }
+ s.speed = levelSpeed(s.level);
+ resetBall(s);
+}
+
+function stepBricks(s: BrickState, input: RetroInput, dt: number, random: () => number): void {
+ s.time += dt;
+ s.shake = Math.max(0, s.shake - dt);
+ s.flash = Math.max(0, s.flash - dt * 2);
+ for (let i = 0; i < s.hitFlash.length; i += 1) if (s.hitFlash[i] > 0) s.hitFlash[i] -= dt;
+ stepSparks(s.sparks, dt, 160);
+ if (s.over) return;
+ s.wideTime = Math.max(0, s.wideTime - dt);
+ s.slowTime = Math.max(0, s.slowTime - dt);
+
+ // Paddle: keys, or the pointer whenever it moves.
+ const dir = (input.right ? 1 : 0) - (input.left ? 1 : 0);
+ s.paddleX += dir * PADDLE_SPEED * dt;
+ const pointer = input.pointer;
+ if (pointer && pointer.x !== s.pointerX) s.paddleX = pointer.x;
+ s.pointerX = pointer ? pointer.x : null;
+ const targetW = s.wideTime > 0 ? WIDE_W : PADDLE_W;
+ s.paddleW += clamp(targetW - s.paddleW, -120 * dt, 120 * dt);
+ s.paddleX = clamp(s.paddleX, s.paddleW / 2, WIDTH - s.paddleW / 2);
+
+ const fire = input.pressed.a || (pointer?.clicked ?? false);
+ const speed = currentSpeed(s);
+ for (const b of s.balls) {
+ if (!b.alive) continue;
+ if (b.stuck) {
+ b.x = s.paddleX;
+ b.y = PADDLE_Y - BALL_R;
+ if (fire) launch(b, s, random);
+ continue;
+ }
+ normalise(b, speed);
+ moveBall(s, b, dt, random);
+ if (s.left === 0) break;
+ }
+
+ if (s.left === 0) {
+ s.score += 500 * s.level;
+ s.level += 1;
+ s.flash = 1;
+ s.flashColor = "#ffffff";
+ emitSparks(s.sparks, WIDTH / 2, HEIGHT / 2, 40, 160, "#ffc43d", random, 0.9, 2);
+ loadLevel(s);
+ return;
+ }
+
+ for (const d of s.drops) {
+ if (!d.alive) continue;
+ d.y += DROP_SPEED * dt;
+ if (d.y + 4 >= PADDLE_Y && d.y - 4 <= PADDLE_Y + PADDLE_H && Math.abs(d.x - s.paddleX) <= s.paddleW / 2 + 8) {
+ d.alive = false;
+ emitSparks(s.sparks, d.x, PADDLE_Y, 10, 90, DROP_COLOURS[d.kind], random, 0.5, 2);
+ applyPower(s, d.kind, random);
+ } else if (d.y - 4 > HEIGHT) {
+ d.alive = false;
+ }
+ }
+
+ if (liveBalls(s) === 0) loseLife(s);
+}
+
+// ---- drawing -------------------------------------------------------------
+
+function drawBricks(ctx: CanvasRenderingContext2D, s: BrickState): void {
+ for (let r = 0; r < ROWS; r += 1) {
+ for (let c = 0; c < COLS; c += 1) {
+ const i = brickIndex(c, r);
+ const hp = s.bricks[i];
+ if (hp <= 0) continue;
+ const x = brickX(c), y = brickY(r);
+ if (hp >= 3) {
+ // Steel: grey with rivets.
+ ctx.fillStyle = "#5c6378";
+ ctx.fillRect(x, y, BRICK_W, BRICK_H);
+ ctx.fillStyle = "#c9cfdd";
+ ctx.fillRect(x, y, BRICK_W, 2);
+ ctx.fillStyle = "#2c3040";
+ ctx.fillRect(x, y + BRICK_H - 1, BRICK_W, 1);
+ ctx.fillStyle = "#9aa1b5";
+ ctx.fillRect(x + 2, y + 4, 2, 2);
+ ctx.fillRect(x + BRICK_W - 4, y + 4, 2, 2);
+ } else {
+ ctx.fillStyle = ROW_COLOURS[r];
+ ctx.fillRect(x, y, BRICK_W, BRICK_H);
+ ctx.fillStyle = ROW_LIGHT[r];
+ ctx.fillRect(x, y, BRICK_W, 2);
+ ctx.fillStyle = ROW_DARK[r];
+ ctx.fillRect(x, y + BRICK_H - 2, BRICK_W, 2);
+ if (hp === 2) {
+ ctx.fillStyle = ROW_LIGHT[r];
+ ctx.fillRect(x + 4, y + 4, BRICK_W - 8, 2);
+ }
+ }
+ if (s.hitFlash[i] > 0) {
+ ctx.globalAlpha = clamp(s.hitFlash[i] / 0.12, 0, 1);
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(x, y, BRICK_W, BRICK_H);
+ ctx.globalAlpha = 1;
+ }
+ }
+ }
+}
+
+function drawPaddle(ctx: CanvasRenderingContext2D, s: BrickState): void {
+ const w = Math.round(s.paddleW), x = Math.round(s.paddleX - w / 2);
+ const ends = s.wideTime > 0 ? "#3da2ff" : "#ff3d7f";
+ ctx.globalAlpha = 0.25;
+ ctx.fillStyle = ends;
+ ctx.fillRect(x - 2, PADDLE_Y - 2, w + 4, PADDLE_H + 4);
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = "#ffd1e0";
+ ctx.fillRect(x, PADDLE_Y, w, PADDLE_H);
+ ctx.fillStyle = ends;
+ ctx.fillRect(x, PADDLE_Y, 6, PADDLE_H);
+ ctx.fillRect(x + w - 6, PADDLE_Y, 6, PADDLE_H);
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(x + 6, PADDLE_Y, w - 12, 1);
+ ctx.fillStyle = "#8a5566";
+ ctx.fillRect(x, PADDLE_Y + PADDLE_H - 1, w, 1);
+}
+
+function drawBalls(ctx: CanvasRenderingContext2D, s: BrickState): void {
+ const colour = s.slowTime > 0 ? "#9cf2e3" : "#ffffff";
+ for (const b of s.balls) {
+ if (!b.alive) continue;
+ if (!b.stuck) {
+ ctx.globalAlpha = 0.3;
+ ctx.fillStyle = colour;
+ ctx.fillRect(Math.round(b.x - b.vx * 0.03) - 2, Math.round(b.y - b.vy * 0.03) - 2, 4, 4);
+ ctx.globalAlpha = 1;
+ }
+ ctx.fillStyle = colour;
+ ctx.beginPath();
+ ctx.arc(b.x, b.y, BALL_R, 0, Math.PI * 2);
+ ctx.fill();
+ }
+}
+
+/** A capsule with a little icon: arrows (wide), three dots (multi), two bars (slow), a heart (life). */
+function drawDrop(ctx: CanvasRenderingContext2D, d: Drop): void {
+ const x = Math.round(d.x), y = Math.round(d.y);
+ ctx.fillStyle = DROP_COLOURS[d.kind];
+ ctx.fillRect(x - 8, y - 4, 16, 8);
+ ctx.fillRect(x - 9, y - 3, 18, 6);
+ ctx.fillStyle = "#0b0611";
+ if (d.kind === "wide") {
+ ctx.fillRect(x - 5, y - 1, 10, 2);
+ ctx.fillRect(x - 6, y - 2, 1, 4);
+ ctx.fillRect(x + 5, y - 2, 1, 4);
+ } else if (d.kind === "multi") {
+ ctx.fillRect(x - 5, y - 1, 2, 2);
+ ctx.fillRect(x - 1, y - 1, 2, 2);
+ ctx.fillRect(x + 3, y - 1, 2, 2);
+ } else if (d.kind === "slow") {
+ ctx.fillRect(x - 3, y - 2, 2, 4);
+ ctx.fillRect(x + 1, y - 2, 2, 4);
+ } else {
+ ctx.fillRect(x - 3, y - 2, 2, 2);
+ ctx.fillRect(x + 1, y - 2, 2, 2);
+ ctx.fillRect(x - 3, y - 1, 6, 2);
+ ctx.fillRect(x - 1, y + 1, 2, 1);
+ }
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(x - 7, y - 4, 14, 1);
+}
+
+function drawBrickGame(ctx: CanvasRenderingContext2D, s: BrickState, info: { time: number; reduced: boolean; idle: boolean }): void {
+ ctx.save();
+ if (!info.reduced && s.shake > 0) {
+ const m = s.shake * 7;
+ ctx.translate(Math.round(Math.sin(s.time * 83) * m), Math.round(Math.cos(s.time * 67) * m));
+ }
+ ctx.fillStyle = "#0b0611";
+ ctx.fillRect(-8, -8, WIDTH + 16, HEIGHT + 16);
+ // Soft vertical bands and neon side rails.
+ ctx.fillStyle = "#120a1c";
+ for (let x = 0; x < WIDTH; x += 40) ctx.fillRect(x, 0, 20, HEIGHT);
+ ctx.globalAlpha = 0.6;
+ ctx.fillStyle = "#ff3d7f";
+ ctx.fillRect(0, 0, 1, HEIGHT);
+ ctx.fillRect(WIDTH - 1, 0, 1, HEIGHT);
+ ctx.fillRect(0, 0, WIDTH, 1);
+ ctx.globalAlpha = 1;
+ drawBricks(ctx, s);
+ for (const d of s.drops) if (d.alive) drawDrop(ctx, d);
+ drawPaddle(ctx, s);
+ drawBalls(ctx, s);
+ drawSparks(ctx, s.sparks);
+ ctx.restore();
+ if (!info.reduced && s.flash > 0) {
+ ctx.globalAlpha = s.flash * 0.2;
+ ctx.fillStyle = s.flashColor;
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
+ ctx.globalAlpha = 1;
+ }
+ drawScanlines(ctx, WIDTH, HEIGHT, 0.1);
+}
+
+const brickBreaker: RetroGame<BrickState> = {
+ id: "brick-breaker",
+ width: WIDTH,
+ height: HEIGHT,
+ pointer: true,
+ create: () => createBricks(),
+ step: stepBricks,
+ draw: drawBrickGame,
+ status: (s) => ({ score: s.score, lives: s.lives, level: s.level, over: s.over }),
+};
+
+export default brickBreaker;
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/cityDefense.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/cityDefense.test.ts
new file mode 100644
index 0000000000..a9d0bf952c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/cityDefense.test.ts
@@ -0,0 +1,268 @@
+import { describe, expect, it } from "vitest";
+import { idleInput, RETRO_STEP, seededRandom, type RetroInput } from "../retroGame";
+import game, {
+ AMMO, BATTERY_X, BATTERY_Y, BLAST_R, BLAST_S, CITY_X, GROUND_Y, WIDTH,
+ addWarhead, blastRadius, citiesStanding, firingBattery, multiplier, type DefenseState,
+} from "./cityDefense";
+
+const rnd = seededRandom(17);
+const run = (s: DefenseState, input: RetroInput, seconds: number) => {
+ for (let t = 0; t < seconds; t += RETRO_STEP) game.step(s, input, RETRO_STEP, rnd);
+};
+/** A wave in progress with the sky held empty, so one rule can be watched at a time. */
+const quiet = (): DefenseState => {
+ const s = game.create(seededRandom(4));
+ run(s, idleInput(), 2);
+ for (const w of s.warheads) w.active = false;
+ s.toLaunch = 5;
+ s.salvoTimer = 999;
+ s.flyerTimer = 999;
+ return s;
+};
+const pressA = (): RetroInput => {
+ const input = idleInput();
+ input.a = true;
+ input.pressed.a = true;
+ return input;
+};
+const pressB = (): RetroInput => {
+ const input = idleInput();
+ input.b = true;
+ input.pressed.b = true;
+ return input;
+};
+const click = (x: number, y: number): RetroInput => ({ ...idleInput(), pointer: { x, y, down: true, clicked: true } });
+const activeMissiles = (s: DefenseState) => s.missiles.filter((m) => m.active);
+const activeWarheads = (s: DefenseState) => s.warheads.filter((w) => w.active).length;
+
+function fakeContext(): { ctx: CanvasRenderingContext2D; depth: () => number; rects: () => number } {
+ let depth = 0, rects = 0;
+ const finite = (...v: number[]) => {
+ if (!v.every(Number.isFinite)) throw new Error(`non-finite draw arguments ${v.join(",")}`);
+ };
+ const noop = () => {};
+ const ctx = {
+ fillStyle: "", strokeStyle: "", lineWidth: 1, globalAlpha: 1, lineCap: "butt",
+ fillRect: (x: number, y: number, w: number, h: number) => { finite(x, y, w, h); rects += 1; },
+ strokeRect: (x: number, y: number, w: number, h: number) => finite(x, y, w, h),
+ beginPath: noop, closePath: noop, fill: noop, stroke: noop,
+ moveTo: (x: number, y: number) => finite(x, y),
+ lineTo: (x: number, y: number) => finite(x, y),
+ arc: (x: number, y: number, r: number) => { finite(x, y, r); if (r < 0) throw new Error("negative radius"); },
+ translate: (x: number, y: number) => finite(x, y),
+ save: () => { depth += 1; },
+ restore: () => { depth -= 1; },
+ };
+ return { ctx: ctx as unknown as CanvasRenderingContext2D, depth: () => depth, rects: () => rects };
+}
+
+describe("city defense", () => {
+ it("starts with six cities, three full batteries and a short pause", () => {
+ const s = game.create(seededRandom(1));
+ expect(game.pointer).toBe(true);
+ expect(game.status(s)).toEqual({ score: 0, lives: 6, level: 1, over: false });
+ expect(s.batteries.map((b) => b.ammo)).toEqual([AMMO, AMMO, AMMO]);
+ expect(s.phase).toBe("ready");
+ run(s, idleInput(), 2);
+ expect(s.phase).toBe("play");
+ });
+
+ it("a click aims there and fires from the nearest battery", () => {
+ const s = quiet();
+ game.step(s, click(290, 90), RETRO_STEP, rnd);
+ expect(s.batteries.map((b) => b.ammo)).toEqual([AMMO, AMMO, AMMO - 1]);
+ const [m] = activeMissiles(s);
+ expect([m.ox, m.tx, m.ty]).toEqual([BATTERY_X[2], 290, 90]);
+ });
+
+ it("a resting mouse does not undo keyboard aiming", () => {
+ const s = quiet();
+ game.step(s, { ...idleInput(), pointer: { x: 100, y: 100, down: false, clicked: false } }, RETRO_STEP, rnd);
+ run(s, { ...idleInput(), right: true, pointer: { x: 100, y: 100, down: false, clicked: false } }, 0.5);
+ expect(s.cx).toBeGreaterThan(160);
+ });
+
+ it("the keyboard moves the crosshair and fires with the action button", () => {
+ const s = quiet();
+ run(s, { ...idleInput(), left: true, up: true }, 2);
+ expect(s.cx).toBeLessThan(10);
+ game.step(s, pressA(), RETRO_STEP, rnd);
+ expect(s.batteries[0].ammo).toBe(AMMO - 1);
+ expect(activeMissiles(s)).toHaveLength(1);
+ });
+
+ it("an empty or wrecked battery hands over to the next nearest one", () => {
+ const s = quiet();
+ s.batteries[0].ammo = 0;
+ s.cx = 20;
+ expect(firingBattery(s)).toBe(1);
+ s.batteries[1].alive = false;
+ expect(firingBattery(s)).toBe(2);
+ s.batteries[2].ammo = 0;
+ expect(firingBattery(s)).toBe(-1);
+ game.step(s, pressA(), RETRO_STEP, rnd);
+ expect(activeMissiles(s)).toHaveLength(0);
+ });
+
+ it("the secondary button forces a battery, cycling back to nearest", () => {
+ const s = quiet();
+ s.cx = 300;
+ game.step(s, pressB(), RETRO_STEP, rnd);
+ expect(s.selected).toBe(0);
+ game.step(s, pressA(), RETRO_STEP, rnd);
+ expect(s.batteries[0].ammo).toBe(AMMO - 1);
+ game.step(s, pressB(), RETRO_STEP, rnd);
+ game.step(s, pressB(), RETRO_STEP, rnd);
+ game.step(s, pressB(), RETRO_STEP, rnd);
+ expect(s.selected).toBe(-1);
+ expect(firingBattery(s)).toBe(2);
+ });
+
+ it("a counter-missile bursts at the aim point and its blast destroys a warhead", () => {
+ const s = quiet();
+ s.cx = 160;
+ s.cy = 120;
+ addWarhead(s, 160, 118, 160, GROUND_Y, 1, false);
+ game.step(s, pressA(), RETRO_STEP, rnd);
+ run(s, idleInput(), 0.6);
+ expect(activeWarheads(s)).toBe(0);
+ expect(s.score).toBe(25 * multiplier(1));
+ });
+
+ it("blasts grow, hold and fade", () => {
+ expect(blastRadius(0, BLAST_R)).toBe(0);
+ expect(blastRadius(0.5, BLAST_R)).toBe(BLAST_R);
+ expect(blastRadius(BLAST_S, BLAST_R)).toBeCloseTo(0, 6);
+ });
+
+ it("a destroyed warhead's own blast catches the next one (chain reaction)", () => {
+ const s = quiet();
+ s.cx = 100;
+ s.cy = 100;
+ // The second warhead is out of reach of our blast but within the first one's.
+ addWarhead(s, 112, 100, 112, GROUND_Y, 0.01, false);
+ addWarhead(s, 124, 100, 124, GROUND_Y, 0.01, false);
+ expect(124 - 100).toBeGreaterThan(BLAST_R);
+ game.step(s, click(100, 100), RETRO_STEP, rnd);
+ run(s, idleInput(), 1.5);
+ expect(activeWarheads(s)).toBe(0);
+ expect(s.score).toBe(50);
+ });
+
+ it("a warhead reaching a city wrecks it", () => {
+ const s = quiet();
+ addWarhead(s, CITY_X[0], GROUND_Y - 4, CITY_X[0], GROUND_Y, 60, false);
+ run(s, idleInput(), 0.3);
+ expect(s.cities[0]).toBe(0);
+ expect(game.status(s).lives).toBe(5);
+ });
+
+ it("a warhead on a battery wrecks it and its ammo", () => {
+ const s = quiet();
+ addWarhead(s, BATTERY_X[1], BATTERY_Y, BATTERY_X[1], BATTERY_Y + 4, 60, false);
+ run(s, idleInput(), 0.3);
+ expect(s.batteries[1]).toMatchObject({ alive: false, ammo: 0 });
+ });
+
+ it("later waves split warheads mid-air", () => {
+ const s = quiet();
+ s.wave = 5;
+ addWarhead(s, 160, 40, 160, GROUND_Y, 60, true, 50);
+ run(s, idleInput(), 0.3);
+ expect(activeWarheads(s)).toBeGreaterThanOrEqual(3);
+ });
+
+ it("a bomber caught in a blast is worth extra", () => {
+ const s = quiet();
+ s.flyer.active = true;
+ s.flyer.x = 150;
+ s.flyer.y = 60;
+ s.flyer.speed = 0;
+ s.flyer.dropTimer = 99;
+ game.step(s, click(150, 60), RETRO_STEP, rnd);
+ run(s, idleInput(), 1);
+ expect(s.flyer.active).toBe(false);
+ expect(s.score).toBe(100);
+ });
+
+ it("the wave ends with a bonus for ammo and cities, then the next wave refills", () => {
+ const s = quiet();
+ s.toLaunch = 0;
+ s.batteries[0].ammo = 4;
+ s.cities[5] = 0;
+ run(s, idleInput(), 0.1);
+ expect(s.phase).toBe("bonus");
+ expect(s.score).toBe((4 + AMMO * 2) * 5 + 5 * 100);
+ run(s, idleInput(), 3);
+ expect(s.wave).toBe(2);
+ expect(s.batteries.map((b) => b.ammo)).toEqual([AMMO, AMMO, AMMO]);
+ expect(citiesStanding(s)).toBe(5);
+ });
+
+ it("a banked bonus city rebuilds a lost one", () => {
+ const s = quiet();
+ s.score = 9990;
+ s.toLaunch = 0;
+ s.cities[2] = 0;
+ run(s, idleInput(), 0.1);
+ expect(s.banked).toBe(1);
+ run(s, idleInput(), 3);
+ expect(citiesStanding(s)).toBe(6);
+ expect(s.banked).toBe(0);
+ });
+
+ it("losing every city ends the run", () => {
+ const s = quiet();
+ s.cities.fill(0);
+ s.cities[3] = 1;
+ addWarhead(s, CITY_X[3], GROUND_Y - 2, CITY_X[3], GROUND_Y, 60, false);
+ run(s, idleInput(), 3);
+ expect(game.status(s)).toMatchObject({ lives: 0, over: true });
+ });
+
+ it("a whole wave plays out without help and keeps every pool bounded", () => {
+ const s = game.create(seededRandom(8));
+ s.wave = 6;
+ for (let i = 0; i < 60 * 90 && s.phase !== "over" && s.wave === 6; i += 1) {
+ game.step(s, idleInput(), RETRO_STEP, rnd);
+ expect(s.warheads.length).toBe(40);
+ }
+ expect(s.wave === 7 || s.phase === "over" || s.phase === "lost").toBe(true);
+ });
+
+ it("draws every phase without throwing, idle and reduced included", () => {
+ const s = game.create(seededRandom(3));
+ for (const info of [
+ { time: 0, reduced: false, idle: true },
+ { time: 5.5, reduced: true, idle: true },
+ { time: 1, reduced: false, idle: false },
+ ]) {
+ const fake = fakeContext();
+ game.draw(fake.ctx, s, info);
+ expect(fake.depth()).toBe(0);
+ expect(fake.rects()).toBeGreaterThan(50);
+ }
+ run(s, idleInput(), 2);
+ addWarhead(s, 100, 10, 120, GROUND_Y, 30, true, 80);
+ game.step(s, click(200, 80), RETRO_STEP, rnd);
+ s.flyer.active = true;
+ s.flyer.x = 80;
+ s.flyer.y = 60;
+ run(s, idleInput(), 0.3);
+ s.shake = 0.3;
+ s.selected = 1;
+ s.banked = 2;
+ for (const kind of [0, 1] as const) {
+ s.flyer.kind = kind;
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: false, idle: false });
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: true, idle: false });
+ }
+ s.cities[1] = 0;
+ s.batteries[2].alive = false;
+ s.phase = "bonus";
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: false, idle: false });
+ s.phase = "over";
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: false, idle: false });
+ expect(WIDTH).toBe(game.width);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/cityDefense.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/cityDefense.ts
new file mode 100644
index 0000000000..4556062a10
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/cityDefense.ts
@@ -0,0 +1,673 @@
+/**
+ * "City Defense": warheads rain down on six cities and three missile
+ * batteries. Aim the crosshair (mouse, or arrow keys) and fire: a
+ * counter-missile flies from the nearest battery with ammo to that point and
+ * bursts into a blast that grows and fades. Any warhead caught in a blast
+ * blows up too, and its blast can catch the next one (chain reactions).
+ * Later waves bring warheads that split mid-air and a fast bomber or
+ * satellite that drops more. Each wave ends with a bonus for unused ammo and
+ * surviving cities; every 10,000 points banks a city that rebuilds a lost
+ * one. When the last city falls and none is banked, the run is over.
+ */
+import type { RetroDrawInfo, RetroGame, RetroInput, RetroStatus } from "../retroGame";
+import {
+ clamp, drawNumber, drawParticles, drawSprite, drawStars, emitBurst, makeParticles, sprite, starField, stepParticles,
+ type Particle,
+} from "./games3Kit";
+
+export const WIDTH = 320;
+export const HEIGHT = 240;
+export const GROUND_Y = 222;
+/** The crosshair stays in the sky. */
+const AIM_TOP = 10;
+const AIM_BOTTOM = 196;
+const AIM_SPEED = 170;
+
+export const CITY_X: readonly number[] = [64, 92, 120, 200, 228, 256];
+export const BATTERY_X: readonly number[] = [24, 160, 296];
+/** Where counter-missiles leave a battery (the top of its mound). */
+export const BATTERY_Y = 204;
+export const AMMO = 10;
+/** The centre battery fires faster missiles. */
+const MISSILE_SPEED = [170, 260, 170] as const;
+
+const BLAST_GROW = 0.45;
+const BLAST_HOLD = 0.25;
+const BLAST_SHRINK = 0.45;
+export const BLAST_S = BLAST_GROW + BLAST_HOLD + BLAST_SHRINK;
+export const BLAST_R = 16;
+/** A warhead destroyed in the air bursts into a slightly smaller blast of its own. */
+export const CHAIN_R = 13;
+const IMPACT_R = 11;
+/** How close to a city or battery an impact must be to wreck it. */
+const CITY_HIT = 12;
+const BATTERY_HIT = 14;
+
+const MAX_MISSILES = 10;
+const MAX_WARHEADS = 40;
+const MAX_BLASTS = 48;
+
+const WARHEAD_POINTS = 25;
+const FLYER_POINTS = 100;
+const AMMO_BONUS = 5;
+const CITY_BONUS = 100;
+export const BONUS_CITY_EVERY = 10000;
+const READY_S = 1.6;
+const BONUS_S = 2.6;
+const LOST_S = 2.2;
+
+export type DefensePhase = "ready" | "play" | "bonus" | "lost" | "over";
+
+export interface Battery { x: number; ammo: number; alive: boolean }
+export interface Counter { active: boolean; ox: number; oy: number; x: number; y: number; tx: number; ty: number; vx: number; vy: number; left: number }
+export interface Warhead { active: boolean; ox: number; oy: number; x: number; y: number; vx: number; vy: number; ty: number; mirv: boolean; splitY: number }
+/** A blast: `friendly` ones (ours and chains) destroy what they touch in the air; impacts only wreck the ground. */
+export interface Blast { active: boolean; x: number; y: number; age: number; r: number; friendly: boolean }
+export interface Flyer { active: boolean; kind: 0 | 1; x: number; y: number; dir: 1 | -1; speed: number; dropTimer: number }
+
+export interface DefenseState {
+ phase: DefensePhase;
+ timer: number;
+ /** Total seconds simulated; zero means the run has not started (attract screen). */
+ elapsed: number;
+ score: number;
+ wave: number;
+ nextCityAt: number;
+ /** Bonus cities waiting to rebuild a destroyed one at the next wave. */
+ banked: number;
+ cx: number;
+ cy: number;
+ /** Last pointer position seen, so a resting mouse does not undo keyboard aiming. */
+ lastPx: number;
+ lastPy: number;
+ /** The battery forced with `b`, or -1 for "nearest with ammo". */
+ selected: number;
+ cities: Uint8Array;
+ batteries: Battery[];
+ missiles: Counter[];
+ warheads: Warhead[];
+ blasts: Blast[];
+ flyer: Flyer;
+ /** Warheads (including the flyer's drops) still to come this wave. */
+ toLaunch: number;
+ salvoTimer: number;
+ flyerTimer: number;
+ /** The last wave's bonus tally, for the bonus screen. */
+ bonusAmmo: number;
+ bonusCities: number;
+ particles: Particle[];
+ shake: number;
+}
+
+/** Score multiplier: ×1 for waves 1–2, ×2 for 3–4 … up to ×6. */
+export function multiplier(wave: number): number {
+ return Math.min(6, 1 + Math.floor((wave - 1) / 2));
+}
+
+export function warheadSpeed(wave: number): number {
+ return Math.min(70, 16 + wave * 4);
+}
+
+function wavePayload(wave: number): number {
+ return Math.min(36, 10 + wave * 2);
+}
+
+/** Radius of a blast at a given age: it grows, holds and shrinks away. */
+export function blastRadius(age: number, max: number): number {
+ if (age < BLAST_GROW) return (max * age) / BLAST_GROW;
+ if (age < BLAST_GROW + BLAST_HOLD) return max;
+ return Math.max(0, max * (1 - (age - BLAST_GROW - BLAST_HOLD) / BLAST_SHRINK));
+}
+
+function startWave(state: DefenseState, random: () => number): void {
+ state.phase = "ready";
+ state.timer = READY_S;
+ for (const b of state.batteries) { b.alive = true; b.ammo = AMMO; }
+ for (const m of state.missiles) m.active = false;
+ for (const w of state.warheads) w.active = false;
+ for (const b of state.blasts) b.active = false;
+ state.flyer.active = false;
+ state.toLaunch = wavePayload(state.wave);
+ state.salvoTimer = 0.4;
+ state.flyerTimer = 8 + random() * 8;
+ state.selected = -1;
+}
+
+function create(random: () => number): DefenseState {
+ const state: DefenseState = {
+ phase: "ready", timer: 0, elapsed: 0, score: 0, wave: 1, nextCityAt: BONUS_CITY_EVERY, banked: 0,
+ cx: WIDTH / 2, cy: 110, lastPx: -1, lastPy: -1, selected: -1,
+ cities: new Uint8Array(CITY_X.length).fill(1),
+ batteries: BATTERY_X.map((x) => ({ x, ammo: AMMO, alive: true })),
+ missiles: Array.from({ length: MAX_MISSILES }, () => ({ active: false, ox: 0, oy: 0, x: 0, y: 0, tx: 0, ty: 0, vx: 0, vy: 0, left: 0 })),
+ warheads: Array.from({ length: MAX_WARHEADS }, () => ({ active: false, ox: 0, oy: 0, x: 0, y: 0, vx: 0, vy: 0, ty: 0, mirv: false, splitY: 0 })),
+ blasts: Array.from({ length: MAX_BLASTS }, () => ({ active: false, x: 0, y: 0, age: 0, r: 0, friendly: false })),
+ flyer: { active: false, kind: 0, x: 0, y: 0, dir: 1, speed: 0, dropTimer: 0 },
+ toLaunch: 0, salvoTimer: 0, flyerTimer: 0, bonusAmmo: 0, bonusCities: 0,
+ particles: makeParticles(160),
+ shake: 0,
+ };
+ startWave(state, random);
+ return state;
+}
+
+function addScore(state: DefenseState, points: number): void {
+ state.score += points;
+ while (state.score >= state.nextCityAt) {
+ state.banked += 1;
+ state.nextCityAt += BONUS_CITY_EVERY;
+ }
+}
+
+function spawnBlast(state: DefenseState, x: number, y: number, r: number, friendly: boolean): void {
+ let slot: Blast | undefined;
+ for (const b of state.blasts) if (!b.active) { slot = b; break; }
+ if (!slot) return;
+ slot.active = true; slot.x = x; slot.y = y; slot.age = 0; slot.r = r; slot.friendly = friendly;
+}
+
+/**
+ * Send a warhead from (x, y) to the ground at `tx` (to the battery top when it
+ * aims at a battery). Returns false when the sky is full.
+ */
+export function addWarhead(state: DefenseState, x: number, y: number, tx: number, ty: number, speed: number, mirv: boolean, splitY = 0): boolean {
+ let w: Warhead | undefined;
+ for (const c of state.warheads) if (!c.active) { w = c; break; }
+ if (!w) return false;
+ const dx = tx - x, dy = ty - y;
+ const len = Math.max(1, Math.hypot(dx, dy));
+ w.active = true; w.ox = x; w.oy = y; w.x = x; w.y = y;
+ w.vx = (dx / len) * speed; w.vy = (dy / len) * speed;
+ w.ty = ty; w.mirv = mirv; w.splitY = splitY;
+ return true;
+}
+
+/** A target on the ground: a standing city or battery most of the time, sometimes open ground. */
+function pickTarget(state: DefenseState, random: () => number, out: number[]): void {
+ let standing = 0;
+ for (const c of state.cities) standing += c;
+ for (const b of state.batteries) if (b.alive) standing += 1;
+ if (standing === 0 || random() < 0.15) {
+ out[0] = 12 + random() * (WIDTH - 24);
+ out[1] = GROUND_Y;
+ return;
+ }
+ let pick = Math.floor(random() * standing);
+ for (let i = 0; i < CITY_X.length; i += 1) {
+ if (state.cities[i] && pick-- === 0) { out[0] = CITY_X[i]; out[1] = GROUND_Y; return; }
+ }
+ for (const b of state.batteries) {
+ if (b.alive && pick-- === 0) { out[0] = b.x; out[1] = BATTERY_Y + 4; return; }
+ }
+}
+const target = [0, 0];
+
+function launchFromSky(state: DefenseState, random: () => number): void {
+ pickTarget(state, random, target);
+ const mirvChance = state.wave >= 3 ? Math.min(0.35, 0.06 * (state.wave - 2)) : 0;
+ const mirv = random() < mirvChance;
+ if (addWarhead(state, 8 + random() * (WIDTH - 16), 0, target[0], target[1], warheadSpeed(state.wave), mirv, 50 + random() * 70)) {
+ state.toLaunch -= 1;
+ }
+}
+
+/** Split a MIRV: two or three new warheads leave from where it is now; the original flies on. */
+function split(state: DefenseState, w: Warhead, random: () => number): void {
+ w.mirv = false;
+ const count = 2 + (random() < 0.4 ? 1 : 0);
+ const speed = Math.hypot(w.vx, w.vy);
+ for (let i = 0; i < count; i += 1) {
+ pickTarget(state, random, target);
+ addWarhead(state, w.x, w.y, target[0], target[1], speed, false);
+ }
+}
+
+/** The battery that would fire at the crosshair now: the forced one if it can, else the nearest with ammo; -1 if none. */
+export function firingBattery(state: DefenseState): number {
+ const forced = state.selected >= 0 ? state.batteries[state.selected] : null;
+ if (forced && forced.alive && forced.ammo > 0) return state.selected;
+ let best = -1, bestD = Infinity;
+ for (let i = 0; i < state.batteries.length; i += 1) {
+ const b = state.batteries[i];
+ if (!b.alive || b.ammo <= 0) continue;
+ // Ties go to the centre battery, whose missiles are faster.
+ const d = Math.abs(b.x - state.cx) - (i === 1 ? 0.5 : 0);
+ if (d < bestD) { bestD = d; best = i; }
+ }
+ return best;
+}
+
+function fire(state: DefenseState): boolean {
+ const i = firingBattery(state);
+ if (i < 0) return false;
+ let m: Counter | undefined;
+ for (const c of state.missiles) if (!c.active) { m = c; break; }
+ if (!m) return false;
+ const b = state.batteries[i];
+ b.ammo -= 1;
+ const dx = state.cx - b.x, dy = state.cy - BATTERY_Y;
+ const len = Math.max(1, Math.hypot(dx, dy));
+ m.active = true; m.ox = b.x; m.oy = BATTERY_Y; m.x = b.x; m.y = BATTERY_Y;
+ m.tx = state.cx; m.ty = state.cy; m.left = len;
+ m.vx = (dx / len) * MISSILE_SPEED[i]; m.vy = (dy / len) * MISSILE_SPEED[i];
+ return true;
+}
+
+/** Cycle the forced battery: nearest → left → centre → right → nearest, skipping empty ones. */
+function cycleBattery(state: DefenseState): void {
+ for (let n = 0; n < 4; n += 1) {
+ state.selected = state.selected >= 2 ? -1 : state.selected + 1;
+ if (state.selected < 0) return;
+ const b = state.batteries[state.selected];
+ if (b.alive && b.ammo > 0) return;
+ }
+}
+
+/** A warhead reached the ground: wreck what stands there. */
+function impact(state: DefenseState, x: number, y: number, random: () => number): void {
+ spawnBlast(state, x, y, IMPACT_R, false);
+ emitBurst(state.particles, x, y, 12, 60, "#ff7a3a", random, 0.7);
+ for (let i = 0; i < CITY_X.length; i += 1) {
+ if (state.cities[i] && Math.abs(CITY_X[i] - x) <= CITY_HIT) {
+ state.cities[i] = 0;
+ state.shake = 0.35;
+ emitBurst(state.particles, CITY_X[i], GROUND_Y - 4, 24, 80, "#7ff0ff", random, 1);
+ }
+ }
+ for (const b of state.batteries) {
+ if (b.alive && Math.abs(b.x - x) <= BATTERY_HIT) {
+ b.alive = false;
+ b.ammo = 0;
+ state.shake = 0.35;
+ emitBurst(state.particles, b.x, BATTERY_Y, 20, 70, "#ffd35a", random, 0.9);
+ }
+ }
+}
+
+export function citiesStanding(state: DefenseState): number {
+ let n = 0;
+ for (const c of state.cities) n += c;
+ return n;
+}
+
+/** Everything in the air moves; blasts grow, catch warheads and fade. */
+function stepWorld(state: DefenseState, dt: number, random: () => number): void {
+ const mult = multiplier(state.wave);
+ for (const m of state.missiles) {
+ if (!m.active) continue;
+ const travel = Math.hypot(m.vx, m.vy) * dt;
+ if (travel >= m.left) {
+ m.active = false;
+ spawnBlast(state, m.tx, m.ty, BLAST_R, true);
+ continue;
+ }
+ m.left -= travel;
+ m.x += m.vx * dt;
+ m.y += m.vy * dt;
+ }
+ for (const w of state.warheads) {
+ if (!w.active) continue;
+ w.x += w.vx * dt;
+ w.y += w.vy * dt;
+ if (w.mirv && w.y >= w.splitY) split(state, w, random);
+ if (w.y >= w.ty) {
+ w.active = false;
+ impact(state, w.x, w.ty, random);
+ }
+ }
+ const f = state.flyer;
+ if (f.active) {
+ f.x += f.dir * f.speed * dt;
+ if (f.x < -24 || f.x > WIDTH + 24) f.active = false;
+ else if ((f.dropTimer -= dt) <= 0 && state.toLaunch > 0 && f.x > 16 && f.x < WIDTH - 16) {
+ pickTarget(state, random, target);
+ if (addWarhead(state, f.x, f.y + 4, target[0], target[1], warheadSpeed(state.wave), false)) state.toLaunch -= 1;
+ f.dropTimer = 1.1 + random() * 1.2;
+ }
+ }
+ for (const b of state.blasts) {
+ if (!b.active) continue;
+ b.age += dt;
+ if (b.age >= BLAST_S) { b.active = false; continue; }
+ if (!b.friendly) continue;
+ const r = blastRadius(b.age, b.r);
+ const r2 = r * r;
+ for (const w of state.warheads) {
+ if (!w.active) continue;
+ const dx = w.x - b.x, dy = w.y - b.y;
+ if (dx * dx + dy * dy <= r2) {
+ w.active = false;
+ addScore(state, WARHEAD_POINTS * mult);
+ spawnBlast(state, w.x, w.y, CHAIN_R, true);
+ emitBurst(state.particles, w.x, w.y, 8, 50, "#ffe9a8", random, 0.5);
+ }
+ }
+ if (f.active) {
+ const dx = f.x - b.x, dy = f.y - b.y;
+ if (dx * dx + dy * dy <= (r + 5) * (r + 5)) {
+ f.active = false;
+ addScore(state, FLYER_POINTS * mult);
+ spawnBlast(state, f.x, f.y, BLAST_R, true);
+ emitBurst(state.particles, f.x, f.y, 20, 80, "#c8f0ff", random, 0.8);
+ }
+ }
+ }
+}
+
+function airborne(state: DefenseState): boolean {
+ if (state.flyer.active) return true;
+ for (const m of state.missiles) if (m.active) return true;
+ for (const w of state.warheads) if (w.active) return true;
+ for (const b of state.blasts) if (b.active) return true;
+ return false;
+}
+
+function endWave(state: DefenseState): void {
+ const mult = multiplier(state.wave);
+ let ammo = 0;
+ for (const b of state.batteries) ammo += b.ammo;
+ state.bonusAmmo = ammo;
+ state.bonusCities = citiesStanding(state);
+ addScore(state, (ammo * AMMO_BONUS + state.bonusCities * CITY_BONUS) * mult);
+ state.phase = "bonus";
+ state.timer = BONUS_S;
+}
+
+function aim(state: DefenseState, input: RetroInput, dt: number): void {
+ const p = input.pointer;
+ if (p && (p.x !== state.lastPx || p.y !== state.lastPy || p.clicked)) {
+ state.cx = clamp(p.x, 4, WIDTH - 4);
+ state.cy = clamp(p.y, AIM_TOP, AIM_BOTTOM);
+ state.lastPx = p.x;
+ state.lastPy = p.y;
+ }
+ const dx = (input.right ? 1 : 0) - (input.left ? 1 : 0);
+ const dy = (input.down ? 1 : 0) - (input.up ? 1 : 0);
+ if (dx || dy) {
+ state.cx = clamp(state.cx + dx * AIM_SPEED * dt, 4, WIDTH - 4);
+ state.cy = clamp(state.cy + dy * AIM_SPEED * dt, AIM_TOP, AIM_BOTTOM);
+ }
+}
+
+function step(state: DefenseState, input: RetroInput, dt: number, random: () => number): void {
+ stepParticles(state.particles, dt, 60);
+ if (state.phase === "over") return;
+ state.elapsed += dt;
+ state.shake = Math.max(0, state.shake - dt);
+ aim(state, input, dt);
+
+ if (state.phase === "ready") {
+ if ((state.timer -= dt) <= 0) state.phase = "play";
+ return;
+ }
+ if (state.phase === "bonus") {
+ if ((state.timer -= dt) <= 0) {
+ // Banked cities rebuild lost ones; with none standing and none banked the run is over.
+ for (let i = 0; i < state.cities.length && state.banked > 0; i += 1) {
+ if (!state.cities[i]) { state.cities[i] = 1; state.banked -= 1; }
+ }
+ if (citiesStanding(state) === 0) {
+ state.phase = "over";
+ return;
+ }
+ state.wave += 1;
+ startWave(state, random);
+ }
+ return;
+ }
+
+ stepWorld(state, dt, random);
+ if (state.phase === "lost") {
+ if ((state.timer -= dt) <= 0) state.phase = "over";
+ return;
+ }
+
+ if (input.pressed.b) cycleBattery(state);
+ if (input.pressed.a || input.pointer?.clicked) fire(state);
+
+ // The attack: salvoes from the top, and now and then a flyer.
+ if (state.toLaunch > 0) {
+ if ((state.salvoTimer -= dt) <= 0) {
+ const size = Math.min(state.toLaunch, 1 + Math.floor(random() * Math.min(4, 1 + state.wave / 2)));
+ for (let i = 0; i < size; i += 1) launchFromSky(state, random);
+ state.salvoTimer = Math.max(1.2, 3.4 - state.wave * 0.2) + random() * 0.8;
+ }
+ if (state.wave >= 2 && !state.flyer.active && (state.flyerTimer -= dt) <= 0) {
+ const f = state.flyer;
+ f.active = true;
+ f.kind = random() < 0.5 ? 0 : 1;
+ f.dir = random() < 0.5 ? 1 : -1;
+ f.x = f.dir > 0 ? -16 : WIDTH + 16;
+ f.y = 44 + random() * 50;
+ f.speed = f.kind === 0 ? 58 : 76;
+ f.dropTimer = 0.8 + random();
+ state.flyerTimer = 12 + random() * 10;
+ }
+ }
+
+ if (citiesStanding(state) === 0 && state.banked === 0) {
+ state.phase = "lost";
+ state.timer = LOST_S;
+ return;
+ }
+ if (state.toLaunch <= 0 && !airborne(state)) endWave(state);
+}
+
+function status(state: DefenseState): RetroStatus {
+ return { score: state.score, lives: citiesStanding(state), level: state.wave, over: state.phase === "over" };
+}
+
+// ---- Drawing --------------------------------------------------------------
+
+const SKY = ["#05061a", "#080a24", "#0c0d2e", "#120f36", "#1a1240", "#24154a"] as const;
+const STARS = starField(60, WIDTH, 150, 23);
+const CITY_SPRITES = [
+ sprite(["....##..............", "....##.....###......", ".####.#...####..##..", ".####.##..####.###..", "#########.########.#", "####################", "####################", "####################"]),
+ sprite([".........##.........", "..###....##...##....", "..###...####..##.##.", "######..####.#######", "######.#############", "####################", "####################", "####################"]),
+ sprite(["...##...............", "...##.......####....", "######.....######...", "######.##..######.##", "#########.##########", "####################", "####################", "####################"]),
+];
+const RUBBLE = sprite(["......#.......#.....", "..#..###...#.###....", ".####.####.#######..", "####################"]);
+const BOMBER = sprite(["......##........", ".....####.......", "################", ".##############.", "....######......", ".....##........."]);
+const SATELLITE = sprite(["###.......###", "###..###..###", "#############", "###..###..###", "###.......###"]);
+
+function drawSky(ctx: CanvasRenderingContext2D): void {
+ const band = Math.ceil(GROUND_Y / SKY.length);
+ for (let i = 0; i < SKY.length; i += 1) {
+ ctx.fillStyle = SKY[i];
+ ctx.fillRect(0, i * band, WIDTH, band);
+ }
+}
+
+function drawGround(ctx: CanvasRenderingContext2D, state: DefenseState): void {
+ ctx.fillStyle = "#6b4a1e";
+ ctx.fillRect(0, GROUND_Y, WIDTH, HEIGHT - GROUND_Y);
+ ctx.fillStyle = "#d4a843";
+ ctx.fillRect(0, GROUND_Y, WIDTH, 1);
+ for (const b of state.batteries) {
+ // A stepped mound under each battery.
+ for (let s = 0; s < 4; s += 1) {
+ const half = 22 - s * 4;
+ ctx.fillStyle = s === 3 ? "#d4a843" : "#8c6a2a";
+ ctx.fillRect(b.x - half, GROUND_Y - (s + 1) * 4, half * 2, 4);
+ }
+ }
+}
+
+function drawBatteries(ctx: CanvasRenderingContext2D, state: DefenseState, info: RetroDrawInfo): void {
+ for (const b of state.batteries) {
+ if (!b.alive) {
+ ctx.fillStyle = "#2a1a0c";
+ ctx.fillRect(b.x - 8, BATTERY_Y + 2, 16, 3);
+ continue;
+ }
+ // Ammo as rows of little missiles: 4, 3, 2, 1 from the bottom.
+ ctx.fillStyle = "#7ff0ff";
+ let left = b.ammo;
+ for (let row = 0; row < 4 && left > 0; row += 1) {
+ const n = 4 - row;
+ for (let k = 0; k < n && left > 0; k += 1, left -= 1) ctx.fillRect(b.x - n * 3 + k * 6 + 2, BATTERY_Y + 12 - row * 4 - 3, 2, 3);
+ }
+ }
+ const firing = firingBattery(state);
+ if (firing >= 0 && state.phase !== "over") {
+ const x = state.batteries[firing].x;
+ const bob = info.reduced ? 0 : Math.round(Math.sin(info.time * 5));
+ ctx.fillStyle = state.selected >= 0 ? "#ffd35a" : "#9aa3c7";
+ ctx.fillRect(x - 2, BATTERY_Y - 10 + bob, 5, 1);
+ ctx.fillRect(x - 1, BATTERY_Y - 9 + bob, 3, 1);
+ ctx.fillRect(x, BATTERY_Y - 8 + bob, 1, 1);
+ }
+}
+
+function drawCities(ctx: CanvasRenderingContext2D, state: DefenseState): void {
+ for (let i = 0; i < CITY_X.length; i += 1) {
+ const x = CITY_X[i] - 10;
+ if (state.cities[i]) {
+ ctx.fillStyle = "#3fb6d9";
+ drawSprite(ctx, CITY_SPRITES[i % CITY_SPRITES.length], x, GROUND_Y - 8);
+ // Lit windows, a fixed pattern per city.
+ ctx.fillStyle = "#ffe08a";
+ for (let k = 0; k < 6; k += 1) ctx.fillRect(x + 2 + ((k * 7 + i * 3) % 16), GROUND_Y - 4 + (k % 2) * 2, 1, 1);
+ } else {
+ ctx.fillStyle = "#5a3328";
+ drawSprite(ctx, RUBBLE, x, GROUND_Y - 4);
+ }
+ }
+}
+
+function drawCross(ctx: CanvasRenderingContext2D, x: number, y: number, size: number): void {
+ ctx.fillRect(x - size, y, size - 1, 1);
+ ctx.fillRect(x + 2, y, size - 1, 1);
+ ctx.fillRect(x, y - size, 1, size - 1);
+ ctx.fillRect(x, y + 2, 1, size - 1);
+}
+
+function draw(ctx: CanvasRenderingContext2D, state: DefenseState, info: RetroDrawInfo): void {
+ drawSky(ctx);
+ drawStars(ctx, STARS, info.time, info.reduced);
+
+ ctx.save();
+ if (state.shake > 0 && !info.reduced) {
+ ctx.translate(Math.round(Math.sin(info.time * 77) * state.shake * 6), Math.round(Math.cos(info.time * 91) * state.shake * 4));
+ }
+ drawGround(ctx, state);
+ drawCities(ctx, state);
+ drawBatteries(ctx, state, info);
+
+ // Trails: incoming in red, ours in blue.
+ ctx.lineWidth = 1;
+ ctx.strokeStyle = "#ff5a4a";
+ ctx.globalAlpha = 0.75;
+ ctx.beginPath();
+ for (const w of state.warheads) {
+ if (!w.active) continue;
+ ctx.moveTo(w.ox, w.oy);
+ ctx.lineTo(w.x, w.y);
+ }
+ ctx.stroke();
+ ctx.strokeStyle = "#5ab8ff";
+ ctx.beginPath();
+ for (const m of state.missiles) {
+ if (!m.active) continue;
+ ctx.moveTo(m.ox, m.oy);
+ ctx.lineTo(m.x, m.y);
+ }
+ ctx.stroke();
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = "#fff4d0";
+ for (const w of state.warheads) if (w.active) ctx.fillRect(Math.round(w.x) - 1, Math.round(w.y) - 1, 2, 2);
+ for (const m of state.missiles) {
+ if (!m.active) continue;
+ ctx.fillStyle = "#e6f6ff";
+ ctx.fillRect(Math.round(m.x) - 1, Math.round(m.y) - 1, 2, 2);
+ ctx.fillStyle = "#5ab8ff";
+ // The target mark: a small x where the missile will burst.
+ const tx = Math.round(m.tx), ty = Math.round(m.ty);
+ for (let k = -2; k <= 2; k += 1) {
+ ctx.fillRect(tx + k, ty + k, 1, 1);
+ ctx.fillRect(tx + k, ty - k, 1, 1);
+ }
+ }
+
+ const f = state.flyer;
+ if (f.active) {
+ ctx.fillStyle = f.kind === 0 ? "#c8d0e0" : "#ffd35a";
+ if (f.kind === 0) drawSprite(ctx, BOMBER, f.x - 8, f.y - 3, 1, f.dir < 0);
+ else drawSprite(ctx, SATELLITE, f.x - 6, f.y - 2);
+ }
+
+ // Blasts: a warm outer ball with a hot core; steady colours (no strobing).
+ for (const b of state.blasts) {
+ if (!b.active) continue;
+ const r = blastRadius(b.age, b.r);
+ if (r <= 0.5) continue;
+ ctx.fillStyle = b.friendly ? "#ff9f43" : "#ff5a3a";
+ ctx.globalAlpha = 0.85;
+ ctx.beginPath();
+ ctx.arc(b.x, b.y, r, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = b.friendly ? "#fff3c4" : "#ffd27a";
+ ctx.beginPath();
+ ctx.arc(b.x, b.y, r * 0.55, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ }
+ drawParticles(ctx, state.particles);
+ ctx.restore();
+
+ // Crosshair; on the attract screen it drifts lazily across the sky.
+ let ax = state.cx, ay = state.cy;
+ if (info.idle && state.elapsed === 0 && !info.reduced) {
+ ax = WIDTH / 2 + Math.sin(info.time * 0.7) * 90;
+ ay = 100 + Math.sin(info.time * 1.1) * 40;
+ }
+ ctx.fillStyle = "#ffffff";
+ drawCross(ctx, Math.round(ax), Math.round(ay), 6);
+
+ // Score, wave and banked cities.
+ ctx.fillStyle = "#ffcf5a";
+ drawNumber(ctx, state.score, 6, 5, 2);
+ ctx.fillStyle = "#ff8a6a";
+ drawNumber(ctx, state.wave, WIDTH - 6, 5, 2, "right");
+ ctx.fillStyle = "#3fb6d9";
+ for (let i = 0; i < Math.min(state.banked, 5); i += 1) ctx.fillRect(WIDTH - 10 - i * 6, 18, 4, 3);
+
+ if (state.phase === "ready") {
+ ctx.fillStyle = "#ffcf5a";
+ drawNumber(ctx, state.wave, WIDTH / 2, 80, 5, "center");
+ const mult = multiplier(state.wave);
+ // "×n" as a pixel cross and the digit.
+ ctx.fillStyle = "#ff8a6a";
+ for (let k = 0; k < 5; k += 1) {
+ ctx.fillRect(WIDTH / 2 - 10 + k * 2, 112 + k * 2, 2, 2);
+ ctx.fillRect(WIDTH / 2 - 2 - k * 2, 112 + k * 2, 2, 2);
+ }
+ drawNumber(ctx, mult, WIDTH / 2 + 4, 112, 2);
+ } else if (state.phase === "bonus") {
+ // The tally: missiles left and cities saved, each with its points.
+ const mult = multiplier(state.wave);
+ ctx.fillStyle = "#7ff0ff";
+ ctx.fillRect(WIDTH / 2 - 60, 84, 2, 5);
+ drawNumber(ctx, state.bonusAmmo, WIDTH / 2 - 50, 84, 1);
+ ctx.fillStyle = "#ffcf5a";
+ drawNumber(ctx, state.bonusAmmo * AMMO_BONUS * mult, WIDTH / 2 + 60, 84, 1, "right");
+ ctx.fillStyle = "#3fb6d9";
+ ctx.fillRect(WIDTH / 2 - 62, 100, 6, 5);
+ drawNumber(ctx, state.bonusCities, WIDTH / 2 - 50, 100, 1);
+ ctx.fillStyle = "#ffcf5a";
+ drawNumber(ctx, state.bonusCities * CITY_BONUS * mult, WIDTH / 2 + 60, 100, 1, "right");
+ }
+}
+
+const cityDefense: RetroGame<DefenseState> = {
+ id: "city-defense",
+ width: WIDTH,
+ height: HEIGHT,
+ create,
+ step,
+ draw,
+ status,
+ pointer: true,
+};
+
+export default cityDefense;
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/desertDash.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/desertDash.test.ts
new file mode 100644
index 0000000000..27d4b36687
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/desertDash.test.ts
@@ -0,0 +1,231 @@
+import { describe, expect, it } from "vitest";
+import { RETRO_STEP, idleInput, seededRandom, type RetroInput } from "../retroGame";
+import desertDash, {
+ AIRTIME, DUCK_HIT, JUMP_APEX, KINDS, MAX_SPEED, RUNNER_X, STAND_HIT, START_SPEED,
+ clearable, collides, createDesert, jumpWindow, minGap, speedAt, spawnObstacle, type DesertState, type Obstacle,
+} from "./desertDash";
+
+/** A 2D context stand-in: every call is a no-op, texts are recorded, non-finite numbers are flagged. */
+function fakeContext(texts: string[], bad: string[]): CanvasRenderingContext2D {
+ const target: Record<string, unknown> = {
+ fillText: (s: unknown) => { texts.push(String(s)); },
+ createLinearGradient: () => ({ addColorStop: () => undefined }),
+ createRadialGradient: () => ({ addColorStop: () => undefined }),
+ measureText: (s: string) => ({ width: s.length * 6 }),
+ };
+ return new Proxy(target, {
+ get: (t, key) => {
+ if (typeof key === "string" && key in t) return t[key];
+ return (...args: unknown[]) => {
+ if (args.some((a) => typeof a === "number" && !Number.isFinite(a))) bad.push(String(key));
+ };
+ },
+ set: (t, key, value) => { t[String(key)] = value; return true; },
+ }) as unknown as CanvasRenderingContext2D;
+}
+
+const random = seededRandom(3);
+/** A run with no obstacles coming for a long while. */
+const clearRun = (): DesertState => {
+ const s = createDesert(random);
+ s.nextGap = 1e9;
+ return s;
+};
+const jumpInput = (held: boolean, pressed: boolean): RetroInput => {
+ const input = idleInput();
+ input.a = held;
+ input.pressed.a = pressed;
+ return input;
+};
+/** Fly a jump: press, hold for `holdSteps`, then let go; returns the peak height and the steps in the air. */
+const jump = (s: DesertState, holdSteps: number, dive = false): { peak: number; steps: number } => {
+ let peak = 0, steps = 0;
+ desertDash.step(s, jumpInput(true, true), RETRO_STEP, random);
+ while (!s.onGround && steps < 600) {
+ steps += 1;
+ const input = jumpInput(steps < holdSteps, false);
+ input.down = dive && s.vy < 0;
+ desertDash.step(s, input, RETRO_STEP, random);
+ peak = Math.max(peak, s.y);
+ }
+ return { peak, steps };
+};
+
+describe("desert dash: moves", () => {
+ it("starts on the ground at the start speed with nothing in the way", () => {
+ const s = desertDash.create(random);
+ expect(s.onGround).toBe(true);
+ expect(s.speed).toBe(START_SPEED);
+ expect(s.obstacles.some((o) => o.active)).toBe(false);
+ expect(desertDash.status(s)).toEqual({ score: 0, over: false });
+ });
+
+ it("jumps higher the longer the button is held", () => {
+ const full = jump(clearRun(), 999);
+ const hop = jump(clearRun(), 1);
+ const mid = jump(clearRun(), 8);
+ expect(full.peak).toBeCloseTo(JUMP_APEX, 0);
+ expect(full.peak).toBeGreaterThan(60);
+ expect(hop.peak).toBeLessThan(full.peak * 0.45);
+ expect(mid.peak).toBeGreaterThan(hop.peak);
+ expect(mid.peak).toBeLessThan(full.peak);
+ expect(full.steps * RETRO_STEP).toBeCloseTo(AIRTIME, 1);
+ });
+
+ it("cannot jump again in mid-air, but a press just before landing is kept", () => {
+ const s = clearRun();
+ desertDash.step(s, jumpInput(true, true), RETRO_STEP, random);
+ for (let i = 0; i < 10; i += 1) desertDash.step(s, jumpInput(true, false), RETRO_STEP, random);
+ const vy = s.vy;
+ desertDash.step(s, jumpInput(true, true), RETRO_STEP, random);
+ expect(s.vy).toBeLessThan(vy);
+ // Fall until just above the ground, press, and the jump comes on landing.
+ while (s.y > 4 || s.vy > 0) desertDash.step(s, idleInput(), RETRO_STEP, random);
+ desertDash.step(s, jumpInput(true, true), RETRO_STEP, random);
+ let relaunched = false;
+ for (let i = 0; i < 6; i += 1) {
+ desertDash.step(s, jumpInput(true, false), RETRO_STEP, random);
+ if (s.vy > 0) relaunched = true;
+ }
+ expect(relaunched).toBe(true);
+ });
+
+ it("ducks on the ground and dives in the air", () => {
+ const s = clearRun();
+ const down = idleInput();
+ down.down = true;
+ desertDash.step(s, down, RETRO_STEP, random);
+ expect(s.ducking).toBe(true);
+ desertDash.step(s, idleInput(), RETRO_STEP, random);
+ expect(s.ducking).toBe(false);
+ const normal = jump(clearRun(), 999);
+ const dived = jump(clearRun(), 999, true);
+ expect(dived.steps).toBeLessThan(normal.steps);
+ });
+});
+
+describe("desert dash: obstacles", () => {
+ const at = (kind: number, x: number): Obstacle => ({ active: true, kind, x });
+
+ it("ends the run on hitting a cactus", () => {
+ const s = clearRun();
+ s.obstacles[0] = at(0, RUNNER_X + 6);
+ desertDash.step(s, idleInput(), RETRO_STEP, random);
+ expect(s.over).toBe(true);
+ expect(desertDash.status(s).over).toBe(true);
+ const d = s.distance;
+ desertDash.step(s, jumpInput(true, true), RETRO_STEP, random);
+ expect(s.distance).toBe(d);
+ });
+
+ it("a high bird hits a standing fox but flies over a ducking one; a low bird must be jumped", () => {
+ const high = KINDS.findIndex((k) => k.bird && k.duck);
+ const low = KINDS.findIndex((k) => k.bird && !k.duck);
+ const s = clearRun();
+ expect(collides(s, at(high, RUNNER_X))).toBe(true);
+ s.ducking = true;
+ expect(collides(s, at(high, RUNNER_X))).toBe(false);
+ expect(collides(s, at(low, RUNNER_X))).toBe(true);
+ s.ducking = false;
+ s.y = KINDS[low].top + 1;
+ expect(collides(s, at(low, RUNNER_X))).toBe(false);
+ });
+
+ it("every kind is clearable at every speed, and the window math matches the hitboxes", () => {
+ for (let v = START_SPEED; v <= MAX_SPEED; v += 10) {
+ for (const k of KINDS) expect(clearable(k, v), `kind ${KINDS.indexOf(k)} at ${v}`).toBe(true);
+ }
+ for (const k of KINDS) if (!k.duck) expect(jumpWindow(k.top)).not.toBeNull();
+ expect(DUCK_HIT.h).toBeLessThan(STAND_HIT.h);
+ expect(jumpWindow(JUMP_APEX + 1)).toBeNull();
+ });
+
+ it("always leaves a whole jump plus reaction time between obstacles", () => {
+ for (const v of [START_SPEED, 220, 300, 380, MAX_SPEED]) {
+ const s = createDesert(seededRandom(v));
+ s.speed = v;
+ s.score = 100000; // every kind unlocked
+ for (let i = 0; i < 300; i += 1) {
+ const gap = spawnObstacle(s, random);
+ expect(gap).toBeGreaterThanOrEqual(minGap(v));
+ // The time from one obstacle's front to the next is at least a jump plus a moment to react.
+ expect(gap / v).toBeGreaterThan(AIRTIME);
+ for (const o of s.obstacles) o.active = false;
+ }
+ }
+ });
+
+ it("speeds up over time, up to a cap", () => {
+ expect(speedAt(0)).toBe(START_SPEED);
+ expect(speedAt(10)).toBeGreaterThan(speedAt(5));
+ expect(speedAt(10_000)).toBe(MAX_SPEED);
+ const s = clearRun();
+ for (let i = 0; i < 600; i += 1) desertDash.step(s, idleInput(), RETRO_STEP, random);
+ expect(s.speed).toBeGreaterThan(START_SPEED);
+ expect(s.score).toBeGreaterThan(0);
+ });
+
+ it("a simple bot that jumps and ducks on time survives long runs at every speed", () => {
+ for (const seed of [1, 2, 3]) {
+ const r = seededRandom(seed);
+ const s = createDesert(r);
+ let birds = 0;
+ for (let i = 0; i < 150 / RETRO_STEP && !s.over; i += 1) {
+ desertDash.step(s, bot(s), RETRO_STEP, r);
+ for (const o of s.obstacles) if (o.active && KINDS[o.kind].bird && o.x > 318) birds += 1;
+ }
+ expect(s.over, `seed ${seed} crashed at speed ${s.speed.toFixed(0)}, score ${s.score}`).toBe(false);
+ expect(s.speed).toBe(MAX_SPEED);
+ expect(birds).toBeGreaterThan(0);
+ }
+ });
+
+ it("draws every state without throwing, without words and without bad numbers", () => {
+ const texts: string[] = [];
+ const bad: string[] = [];
+ const ctx = fakeContext(texts, bad);
+ const s = desertDash.create(random);
+ desertDash.draw(ctx, s, { time: 0, reduced: false, idle: true });
+ desertDash.draw(ctx, s, { time: 2, reduced: true, idle: true });
+ s.obstacles[0] = at(1, 200);
+ s.obstacles[1] = at(5, 260);
+ s.obstacles[2] = at(4, 120);
+ s.ticks = 5;
+ for (const t of [0, 40, 50, 66, 90, 110, 125, 149, 400]) {
+ s.time = t;
+ s.distance = t * 300;
+ desertDash.draw(ctx, s, { time: t, reduced: false, idle: false });
+ desertDash.draw(ctx, s, { time: t, reduced: true, idle: false });
+ }
+ s.ducking = true;
+ s.milestoneGlow = 0.5;
+ desertDash.draw(ctx, s, { time: 1, reduced: false, idle: false });
+ s.over = true;
+ desertDash.draw(ctx, s, { time: 1, reduced: false, idle: false });
+ expect(bad).toEqual([]);
+ expect(texts.length).toBeGreaterThan(0);
+ for (const text of texts) expect(text).not.toMatch(/[A-Za-z]/);
+ });
+});
+
+/** Jump each cactus or low bird at the last moment that clears it; duck under high birds. */
+function bot(s: DesertState): RetroInput {
+ const input = idleInput();
+ let next: Obstacle | null = null;
+ for (const o of s.obstacles) {
+ if (!o.active || o.x + KINDS[o.kind].hx1 <= RUNNER_X + DUCK_HIT.x0) continue;
+ if (!next || o.x < next.x) next = o;
+ }
+ if (!s.onGround) { input.a = s.jumpHeld; }
+ if (!next) return input;
+ const k = KINDS[next.kind];
+ if (k.duck) {
+ if (next.x + k.hx0 - (RUNNER_X + DUCK_HIT.x1) < s.speed * 0.3) input.down = true;
+ return input;
+ }
+ if (!s.onGround) return input;
+ const win = jumpWindow(k.top)!;
+ const enter = (next.x + k.hx0 - (RUNNER_X + STAND_HIT.x1)) / s.speed;
+ if (enter <= win.rise + RETRO_STEP) { input.a = true; input.pressed.a = true; }
+ return input;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/desertDash.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/desertDash.ts
new file mode 100644
index 0000000000..d08f3372e5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/desertDash.ts
@@ -0,0 +1,531 @@
+/**
+ * "Desert Dash": the endless-runner cabinet.
+ *
+ * A little fennec fox runs right across the dunes; cacti and, further in,
+ * birds come at it ever faster. `a` / `up` jumps (hold for a full jump, let
+ * go early for a short hop), `down` ducks on the ground and dives in the
+ * air. One hit ends the run; the score is the distance run.
+ *
+ * Fairness is built in, not hoped for: the full jump is simulated once with
+ * the real step, which gives exactly how long the fox stays above any height.
+ * The spawner only picks an obstacle the fox can clear at the current speed,
+ * and leaves at least a whole jump plus a reaction time of ground between
+ * two obstacles, so every run is always survivable. High birds fly above a
+ * ducking fox.
+ *
+ * The sky drifts from day through dusk and night to dawn and back, blended
+ * smoothly; three parallax layers of dunes and a textured ground scroll at
+ * their own speeds.
+ */
+import { RETRO_STEP, type RetroDrawInfo, type RetroGame, type RetroInput, type RetroStatus } from "../retroGame";
+import { drawDigits, drawSparks, emitSpark, hexRgb, mixRgb, sparkPool, stepSparks, type Rgb, type Spark } from "./games2Kit";
+
+export const WIDTH = 320;
+export const HEIGHT = 180;
+/** Screen y of the ground line. Heights in the game are pixels above it (up is positive). */
+const GROUND_Y = 150;
+/** The fox's left edge on screen; the world scrolls past it. */
+export const RUNNER_X = 36;
+
+export const JUMP_SPEED = 400;
+/** Gravity while rising with the jump button held, and otherwise (falling, or let go). */
+export const GRAVITY_HELD = 1150;
+export const GRAVITY = 2300;
+/** Letting go while rising cuts the upward speed to this: a short hop. */
+export const JUMP_CUT = 220;
+const DIVE_GRAVITY = 5200;
+/** A jump pressed this shortly before landing still happens on landing. */
+const JUMP_BUFFER = 0.1;
+
+export const START_SPEED = 160;
+export const MAX_SPEED = 440;
+/** Pixels per second gained every second. */
+export const SPEED_RAMP = 3.2;
+/** Score is distance in tens of pixels. */
+const SCORE_SCALE = 10;
+/** Seconds of reaction time left between landing from one obstacle and having to jump the next. */
+export const REACTION = 0.18;
+/** One day-dusk-night-dawn cycle, in seconds of running. */
+const DAY_CYCLE = 150;
+
+/** The fox's hitboxes, relative to RUNNER_X and the ground, a little smaller than the drawing. */
+export const STAND_HIT = { x0: 5, x1: 15, h: 17 };
+export const DUCK_HIT = { x0: 3, x1: 20, h: 9 };
+
+export interface ObstacleKind {
+ /** Drawn width in pixels. */
+ w: number;
+ /** Hitbox: left / right inset edges, and bottom / top heights above the ground. */
+ hx0: number; hx1: number; bottom: number; top: number;
+ bird: boolean;
+ /** Passed by ducking instead of jumping. */
+ duck: boolean;
+ /** First appears at this score / speed. */
+ minScore: number;
+ minSpeed: number;
+ /** Relative chance among the kinds that are allowed. */
+ weight: number;
+}
+
+export const KINDS: readonly ObstacleKind[] = [
+ { w: 9, hx0: 1, hx1: 8, bottom: 0, top: 17, bird: false, duck: false, minScore: 0, minSpeed: 0, weight: 4 }, // small cactus
+ { w: 11, hx0: 1, hx1: 10, bottom: 0, top: 27, bird: false, duck: false, minScore: 0, minSpeed: 0, weight: 3 }, // tall cactus
+ { w: 20, hx0: 1, hx1: 19, bottom: 0, top: 17, bird: false, duck: false, minScore: 60, minSpeed: 0, weight: 2 }, // pair
+ { w: 22, hx0: 1, hx1: 21, bottom: 0, top: 27, bird: false, duck: false, minScore: 200, minSpeed: 220, weight: 2 }, // tall + small
+ { w: 31, hx0: 1, hx1: 30, bottom: 0, top: 17, bird: false, duck: false, minScore: 400, minSpeed: 260, weight: 1 }, // triple
+ { w: 16, hx0: 2, hx1: 14, bottom: 3, top: 11, bird: true, duck: false, minScore: 300, minSpeed: 0, weight: 2 }, // low bird: jump
+ { w: 16, hx0: 2, hx1: 14, bottom: 12, top: 20, bird: true, duck: true, minScore: 300, minSpeed: 0, weight: 2 }, // high bird: duck
+];
+
+export interface Obstacle { active: boolean; kind: number; x: number }
+
+export interface DesertState {
+ /** The fox's height above the ground and vertical speed (up positive). */
+ y: number;
+ vy: number;
+ onGround: boolean;
+ ducking: boolean;
+ /** The jump button has been held since take-off (letting go cuts the jump once). */
+ jumpHeld: boolean;
+ jumpBuffer: number;
+ speed: number;
+ distance: number;
+ /** Seconds of running; drives the speed ramp and the sky. */
+ time: number;
+ score: number;
+ over: boolean;
+ obstacles: Obstacle[];
+ /** Pixels of ground still to scroll before the next obstacle appears. */
+ nextGap: number;
+ /** Score of the last milestone reached (every 500) and the seconds its glow has left. */
+ milestone: number;
+ milestoneGlow: number;
+ dustTimer: number;
+ sparks: Spark[];
+ /** Star positions as x, y pairs (picked once per run). */
+ stars: Float32Array;
+ ticks: number;
+}
+
+/**
+ * The full held jump, simulated once at the real step: heights per step from
+ * take-off to landing. Everything about fairness is read off this.
+ */
+const JUMP_PROFILE: readonly number[] = (() => {
+ const heights: number[] = [];
+ let y = 0, vy = JUMP_SPEED;
+ for (let i = 0; i < 400; i += 1) {
+ vy -= (vy > 0 ? GRAVITY_HELD : GRAVITY) * RETRO_STEP;
+ y += vy * RETRO_STEP;
+ if (y <= 0) break;
+ heights.push(y);
+ }
+ return heights;
+})();
+
+/** Seconds a full jump spends in the air. */
+export const AIRTIME = (JUMP_PROFILE.length + 1) * RETRO_STEP;
+export const JUMP_APEX = Math.max(...JUMP_PROFILE);
+
+/** When, after take-off, a full jump is first and last above `height` (seconds); null if it never is. */
+export function jumpWindow(height: number): { rise: number; fall: number } | null {
+ let first = -1, last = -1;
+ for (let i = 0; i < JUMP_PROFILE.length; i += 1) {
+ if (JUMP_PROFILE[i] > height) { if (first < 0) first = i; last = i; }
+ }
+ if (first < 0) return null;
+ return { rise: (first + 1) * RETRO_STEP, fall: (last + 1) * RETRO_STEP };
+}
+
+/** Whether a full jump at this speed carries the fox's hitbox over the obstacle (with two steps to spare). */
+export function clearable(kind: ObstacleKind, speed: number): boolean {
+ if (kind.duck) return DUCK_HIT.h < kind.bottom;
+ const win = jumpWindow(kind.top);
+ if (!win) return false;
+ const overlap = (kind.hx1 - kind.hx0 + STAND_HIT.x1 - STAND_HIT.x0) / speed;
+ return win.fall - win.rise >= overlap + RETRO_STEP * 2;
+}
+
+/** The least ground between two obstacles at this speed: land from one, react, take off for the next. */
+export function minGap(speed: number): number {
+ return speed * (AIRTIME + REACTION);
+}
+
+export function speedAt(time: number): number {
+ return Math.min(MAX_SPEED, START_SPEED + SPEED_RAMP * time);
+}
+
+export function createDesert(random: () => number): DesertState {
+ const stars = new Float32Array(48 * 2);
+ for (let i = 0; i < 48; i += 1) { stars[i * 2] = random() * WIDTH; stars[i * 2 + 1] = random() * 95; }
+ const obstacles: Obstacle[] = [];
+ for (let i = 0; i < 8; i += 1) obstacles.push({ active: false, kind: 0, x: 0 });
+ return {
+ y: 0, vy: 0, onGround: true, ducking: false, jumpHeld: false, jumpBuffer: 0,
+ speed: START_SPEED, distance: 0, time: 0, score: 0, over: false,
+ obstacles, nextGap: WIDTH * 0.6, milestone: 0, milestoneGlow: 0, dustTimer: 0,
+ sparks: sparkPool(40), stars, ticks: 0,
+ };
+}
+
+/** Pick an obstacle the fox can clear at this speed and that fits the score so far. */
+export function pickKind(s: DesertState, random: () => number): number {
+ let total = 0;
+ for (let i = 0; i < KINDS.length; i += 1) if (allowed(KINDS[i], s)) total += KINDS[i].weight;
+ let roll = random() * total;
+ for (let i = 0; i < KINDS.length; i += 1) {
+ if (!allowed(KINDS[i], s)) continue;
+ roll -= KINDS[i].weight;
+ if (roll < 0) return i;
+ }
+ return 0;
+}
+
+function allowed(kind: ObstacleKind, s: DesertState): boolean {
+ return s.score >= kind.minScore && s.speed >= kind.minSpeed && clearable(kind, s.speed);
+}
+
+/** Spawn one obstacle just off the right edge and set the ground until the next. Returns its gap. */
+export function spawnObstacle(s: DesertState, random: () => number): number {
+ let slot: Obstacle | null = null;
+ for (const o of s.obstacles) if (!o.active) { slot = o; break; }
+ const kind = pickKind(s, random);
+ const gap = minGap(s.speed) * (1 + random() * 0.9) + random() * 40;
+ if (slot) {
+ slot.active = true;
+ slot.kind = kind;
+ // Carry over the overshoot so spacing is exact whatever the step size.
+ slot.x = WIDTH + 4 + Math.min(0, s.nextGap);
+ }
+ s.nextGap = KINDS[kind].w + gap;
+ return gap;
+}
+
+function hitbox(s: DesertState): { x0: number; x1: number; h: number } {
+ return s.ducking ? DUCK_HIT : STAND_HIT;
+}
+
+export function collides(s: DesertState, o: Obstacle): boolean {
+ const k = KINDS[o.kind];
+ const box = hitbox(s);
+ const rx0 = RUNNER_X + box.x0, rx1 = RUNNER_X + box.x1;
+ const ox0 = o.x + k.hx0, ox1 = o.x + k.hx1;
+ return rx1 > ox0 && rx0 < ox1 && s.y + box.h > k.bottom && s.y < k.top;
+}
+
+function dust(s: DesertState, count: number, random: () => number): void {
+ for (let i = 0; i < count; i += 1) {
+ emitSpark(s.sparks, RUNNER_X + 6 + random() * 6, GROUND_Y - 1, -s.speed * 0.3 - random() * 30, -10 - random() * 30,
+ 0.25 + random() * 0.25, 2, "#e8c896");
+ }
+}
+
+export function stepDesert(s: DesertState, input: RetroInput, dt: number, random: () => number): void {
+ s.ticks += 1;
+ stepSparks(s.sparks, dt, 90);
+ if (s.over) return;
+ s.time += dt;
+ s.speed = speedAt(s.time);
+ s.distance += s.speed * dt;
+ s.score = Math.floor(s.distance / SCORE_SCALE);
+ s.milestoneGlow = Math.max(0, s.milestoneGlow - dt);
+ if (s.score >= s.milestone + 500) { s.milestone += 500; s.milestoneGlow = 1; }
+
+ const jumpPressed = input.pressed.a || input.pressed.up;
+ const jumpDown = input.a || input.up;
+ if (jumpPressed) s.jumpBuffer = JUMP_BUFFER;
+ else s.jumpBuffer = Math.max(0, s.jumpBuffer - dt);
+
+ if (s.onGround) {
+ if (s.jumpBuffer > 0) {
+ s.onGround = false;
+ s.ducking = false;
+ s.vy = JUMP_SPEED;
+ // A buffered press already released before landing gives the short hop.
+ s.jumpHeld = jumpDown;
+ s.jumpBuffer = 0;
+ } else {
+ s.ducking = input.down;
+ }
+ }
+ if (!s.onGround) {
+ if (s.jumpHeld && !jumpDown) {
+ s.jumpHeld = false;
+ if (s.vy > JUMP_CUT) s.vy = JUMP_CUT;
+ }
+ const g = input.down ? DIVE_GRAVITY : s.vy > 0 && s.jumpHeld ? GRAVITY_HELD : GRAVITY;
+ s.vy -= g * dt;
+ s.y += s.vy * dt;
+ if (s.y <= 0) {
+ s.y = 0; s.vy = 0; s.onGround = true; s.jumpHeld = false;
+ s.ducking = input.down;
+ dust(s, 5, random);
+ }
+ }
+
+ s.dustTimer -= dt;
+ if (s.onGround && s.dustTimer <= 0) { s.dustTimer = 0.09; dust(s, 1, random); }
+
+ const shift = s.speed * dt;
+ for (const o of s.obstacles) {
+ if (!o.active) continue;
+ o.x -= shift;
+ if (o.x + KINDS[o.kind].w < -4) o.active = false;
+ }
+ s.nextGap -= shift;
+ if (s.nextGap <= 0) spawnObstacle(s, random);
+
+ for (const o of s.obstacles) {
+ if (o.active && collides(s, o)) {
+ s.over = true;
+ for (let i = 0; i < 14; i += 1) {
+ const a = random() * Math.PI * 2, v = 30 + random() * 70;
+ emitSpark(s.sparks, RUNNER_X + 10, GROUND_Y - s.y - 10, Math.cos(a) * v, Math.sin(a) * v - 30, 0.4 + random() * 0.4, 2, "#ff9a3d");
+ }
+ return;
+ }
+ }
+}
+
+// ---------------------------------------------------------------- drawing
+
+interface Palette { skyTop: Rgb; skyBottom: Rgb; far: Rgb; near: Rgb; ground: Rgb; detail: Rgb; cactus: Rgb }
+
+const pal = (skyTop: string, skyBottom: string, far: string, near: string, ground: string, detail: string, cactus: string): Palette => ({
+ skyTop: hexRgb(skyTop), skyBottom: hexRgb(skyBottom), far: hexRgb(far), near: hexRgb(near),
+ ground: hexRgb(ground), detail: hexRgb(detail), cactus: hexRgb(cactus),
+});
+
+const DAY = pal("#6ec6ff", "#ffe9b8", "#e9b97a", "#d99a55", "#f0c27b", "#b8844a", "#2f8f4e");
+const DUSK = pal("#4b3a78", "#ff8a5c", "#b8705a", "#8f4f43", "#c98a5e", "#7a4a3a", "#2a6a48");
+const NIGHT = pal("#070b24", "#1d2457", "#2b2f5c", "#222650", "#3a3a66", "#262850", "#2a6a5a");
+const WHITE = hexRgb("#ffffff");
+const GOLD = hexRgb("#ffd23f");
+const DAWN = pal("#3f6fb8", "#ffb8a0", "#c99a8a", "#a8766a", "#d8a888", "#8a6a5a", "#2a7a52");
+
+/** Keyframes over one cycle (0..1): long day and night, short smooth dusk and dawn. */
+const SKY_KEYS: readonly (readonly [number, Palette])[] = [
+ [0, DAY], [0.24, DAY], [0.34, DUSK], [0.44, NIGHT], [0.68, NIGHT], [0.78, DAWN], [0.88, DAY], [1, DAY],
+];
+
+/** Where the sky is: the two keyframes around `phase` and the smoothed blend between them, plus how dark it is. */
+function skyAt(phase: number): { a: Palette; b: Palette; k: number; night: number } {
+ let i = 0;
+ while (i < SKY_KEYS.length - 2 && phase >= SKY_KEYS[i + 1][0]) i += 1;
+ const [t0, a] = SKY_KEYS[i];
+ const [t1, b] = SKY_KEYS[i + 1];
+ const raw = t1 > t0 ? (phase - t0) / (t1 - t0) : 0;
+ const k = raw * raw * (3 - 2 * raw);
+ const dark = (p: Palette) => (p === NIGHT ? 1 : p === DUSK ? 0.45 : p === DAWN ? 0.35 : 0);
+ return { a, b, k, night: dark(a) + (dark(b) - dark(a)) * k };
+}
+
+function duneLayer(ctx: CanvasRenderingContext2D, scroll: number, base: number, amp: number, freq: number, color: string): void {
+ ctx.fillStyle = color;
+ ctx.beginPath();
+ ctx.moveTo(0, GROUND_Y);
+ for (let x = 0; x <= WIDTH; x += 8) {
+ const wx = x + scroll;
+ const y = base - (Math.sin(wx * freq) * amp + Math.sin(wx * freq * 2.7 + 1.3) * amp * 0.35);
+ ctx.lineTo(x, y);
+ }
+ ctx.lineTo(WIDTH, GROUND_Y);
+ ctx.closePath();
+ ctx.fill();
+}
+
+function drawCactus(ctx: CanvasRenderingContext2D, x: number, w: number, h: number, color: string): void {
+ const top = GROUND_Y - h;
+ const stem = Math.max(3, Math.round(w * 0.4));
+ const sx = Math.round(x + (w - stem) / 2);
+ ctx.fillStyle = color;
+ ctx.fillRect(sx, top + 1, stem, h - 1);
+ ctx.fillRect(sx + 1, top, stem - 2, 1);
+ // Arms: one up on each side, at different heights.
+ const armY = top + Math.round(h * 0.35);
+ ctx.fillRect(Math.round(x), armY + 2, sx - Math.round(x), 2);
+ ctx.fillRect(Math.round(x), armY - 2, 2, 5);
+ ctx.fillRect(sx + stem, armY + 5, Math.round(x + w) - sx - stem, 2);
+ ctx.fillRect(Math.round(x + w) - 2, armY + 1, 2, 6);
+ ctx.fillStyle = "rgba(255,255,255,0.18)";
+ ctx.fillRect(sx + 1, top + 2, 1, h - 4);
+}
+
+/** Draw one obstacle kind at screen x (cactus groups are built from single cacti). */
+function drawObstacle(ctx: CanvasRenderingContext2D, kindIndex: number, x: number, cactus: string, time: number, reduced: boolean): void {
+ const k = KINDS[kindIndex];
+ if (k.bird) {
+ const y = GROUND_Y - k.top;
+ const flap = reduced ? 0 : Math.floor(time * 8) % 2;
+ ctx.fillStyle = "#5a3a2a";
+ ctx.fillRect(Math.round(x + 4), Math.round(y + 3), 9, 4); // body
+ ctx.fillRect(Math.round(x + 1), Math.round(y + 2), 4, 3); // head
+ ctx.fillStyle = "#ffb000";
+ ctx.fillRect(Math.round(x - 1), Math.round(y + 3), 2, 1); // beak
+ ctx.fillStyle = "#5a3a2a";
+ ctx.fillRect(Math.round(x + 13), Math.round(y + 4), 3, 2); // tail
+ if (flap === 0) ctx.fillRect(Math.round(x + 6), Math.round(y - 2), 4, 5); // wing up
+ else ctx.fillRect(Math.round(x + 6), Math.round(y + 6), 4, 4); // wing down
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(Math.round(x + 2), Math.round(y + 3), 1, 1);
+ return;
+ }
+ switch (kindIndex) {
+ case 0: drawCactus(ctx, x, 9, 18, cactus); break;
+ case 1: drawCactus(ctx, x, 11, 28, cactus); break;
+ case 2: drawCactus(ctx, x, 9, 18, cactus); drawCactus(ctx, x + 11, 9, 15, cactus); break;
+ case 3: drawCactus(ctx, x, 11, 28, cactus); drawCactus(ctx, x + 13, 9, 18, cactus); break;
+ default: drawCactus(ctx, x, 9, 16, cactus); drawCactus(ctx, x + 11, 9, 18, cactus); drawCactus(ctx, x + 22, 9, 14, cactus);
+ }
+}
+
+/** The fennec fox: big ears, a bushy tail, two-frame legs; flat and stretched when ducking. */
+function drawFox(ctx: CanvasRenderingContext2D, s: DesertState, legFrame: number, dead: boolean): void {
+ const x = RUNNER_X;
+ const fur = "#ff9a3d", cream = "#ffe6c0", dark = "#2a1a0a";
+ if (s.ducking && s.onGround && !dead) {
+ const top = GROUND_Y - 11;
+ ctx.fillStyle = fur;
+ ctx.fillRect(x - 3, top + 3, 6, 3); // tail
+ ctx.fillRect(x + 2, top + 3, 14, 6); // body
+ ctx.fillRect(x + 14, top + 1, 8, 6); // head
+ ctx.fillRect(x + 11, top, 5, 2); // ears laid back
+ ctx.fillStyle = cream;
+ ctx.fillRect(x - 3, top + 3, 2, 2);
+ ctx.fillRect(x + 20, top + 4, 3, 2);
+ ctx.fillRect(x + 6, top + 7, 8, 2);
+ ctx.fillStyle = dark;
+ ctx.fillRect(x + 18, top + 3, 1, 1);
+ ctx.fillRect(x + 23, top + 4, 1, 1);
+ ctx.fillStyle = fur;
+ ctx.fillRect(x + 4 + legFrame * 2, top + 9, 2, 2);
+ ctx.fillRect(x + 12 - legFrame * 2, top + 9, 2, 2);
+ return;
+ }
+ const top = GROUND_Y - 20 - Math.round(s.y);
+ ctx.fillStyle = fur;
+ ctx.fillRect(x, top + 8, 5, 4); // tail
+ ctx.fillRect(x + 4, top + 8, 9, 7); // body
+ ctx.fillRect(x + 8, top + 2, 8, 7); // head
+ ctx.fillRect(x + 9, top - 2, 2, 4); // ears
+ ctx.fillRect(x + 13, top - 2, 2, 4);
+ ctx.fillStyle = cream;
+ ctx.fillRect(x, top + 8, 2, 3); // tail tip
+ ctx.fillRect(x + 7, top + 11, 5, 3); // belly
+ ctx.fillRect(x + 14, top + 5, 3, 3); // snout
+ ctx.fillRect(x + 10, top - 1, 1, 2); // inner ears
+ ctx.fillRect(x + 14, top - 1, 1, 2);
+ ctx.fillStyle = dark;
+ ctx.fillRect(x + 17, top + 5, 1, 1); // nose
+ if (dead) {
+ // Crossed-out eye: a tiny x.
+ ctx.fillRect(x + 11, top + 3, 1, 1); ctx.fillRect(x + 13, top + 3, 1, 1);
+ ctx.fillRect(x + 12, top + 4, 1, 1);
+ ctx.fillRect(x + 11, top + 5, 1, 1); ctx.fillRect(x + 13, top + 5, 1, 1);
+ } else {
+ ctx.fillRect(x + 12, top + 4, 1, 2);
+ }
+ ctx.fillStyle = fur;
+ if (!s.onGround) {
+ ctx.fillRect(x + 5, top + 15, 2, 3);
+ ctx.fillRect(x + 10, top + 15, 2, 3);
+ } else {
+ ctx.fillRect(x + 5, top + 15, 2, legFrame === 0 ? 5 : 3);
+ ctx.fillRect(x + 10, top + 15, 2, legFrame === 0 ? 3 : 5);
+ }
+}
+
+export function drawDesert(ctx: CanvasRenderingContext2D, s: DesertState, info: RetroDrawInfo): void {
+ const attract = info.idle && s.ticks === 0;
+ const scroll = attract ? (info.reduced ? 0 : info.time * 24) : s.distance;
+ const phase = ((s.time / DAY_CYCLE) % 1 + 1) % 1;
+ const sky = skyAt(phase);
+ const c = (pick: (p: Palette) => Rgb) => mixRgb(pick(sky.a), pick(sky.b), sky.k);
+
+ const grad = ctx.createLinearGradient(0, 0, 0, GROUND_Y);
+ grad.addColorStop(0, c((p) => p.skyTop));
+ grad.addColorStop(1, c((p) => p.skyBottom));
+ ctx.fillStyle = grad;
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
+
+ // Stars fade in with the night.
+ if (sky.night > 0.05) {
+ ctx.fillStyle = "#ffffff";
+ for (let i = 0; i < s.stars.length; i += 2) {
+ const twinkle = info.reduced ? 1 : 0.6 + 0.4 * Math.sin(info.time * 2 + i);
+ ctx.globalAlpha = sky.night * twinkle * 0.9;
+ const sx = ((s.stars[i] - scroll * 0.02) % WIDTH + WIDTH) % WIDTH;
+ ctx.fillRect(Math.round(sx), Math.round(s.stars[i + 1]), 1, 1);
+ }
+ ctx.globalAlpha = 1;
+ }
+ // Sun by day, sinking at dusk; the moon by night.
+ const sunAlpha = 1 - sky.night;
+ if (sunAlpha > 0.02) {
+ ctx.globalAlpha = sunAlpha;
+ ctx.fillStyle = "#fff4c2";
+ ctx.beginPath();
+ ctx.arc(250, 36 + sky.night * 70, 14, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ }
+ if (sky.night > 0.02) {
+ ctx.globalAlpha = sky.night;
+ ctx.fillStyle = "#f2f0ff";
+ ctx.beginPath();
+ ctx.arc(70, 34, 9, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = c((p) => p.skyTop);
+ ctx.beginPath();
+ ctx.arc(74, 31, 8, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ }
+
+ duneLayer(ctx, scroll * 0.12, 112, 9, 0.011, c((p) => p.far));
+ duneLayer(ctx, scroll * 0.35, 132, 7, 0.02, c((p) => p.near));
+
+ // Ground with pebbles and ridges that scroll at full speed (placed by a fixed hash, not at random).
+ ctx.fillStyle = c((p) => p.ground);
+ ctx.fillRect(0, GROUND_Y, WIDTH, HEIGHT - GROUND_Y);
+ const detail = c((p) => p.detail);
+ ctx.fillStyle = detail;
+ ctx.fillRect(0, GROUND_Y, WIDTH, 1);
+ const first = Math.floor(scroll / 13);
+ for (let i = first; i < first + Math.ceil(WIDTH / 13) + 2; i += 1) {
+ const h = (Math.imul(i, 2654435761) >>> 0) / 4294967296;
+ const px = Math.round(i * 13 - scroll + h * 9);
+ const py = GROUND_Y + 3 + Math.floor(h * 24);
+ ctx.fillRect(px, py, h > 0.7 ? 3 : 1, 1);
+ }
+
+ const cactus = c((p) => p.cactus);
+ if (attract) {
+ drawCactus(ctx, 170, 11, 28, cactus);
+ drawCactus(ctx, 250, 9, 18, cactus);
+ } else {
+ for (const o of s.obstacles) if (o.active) drawObstacle(ctx, o.kind, o.x, cactus, info.time, info.reduced);
+ }
+
+ const legFrame = attract ? (info.reduced ? 0 : Math.floor(info.time * 8) % 2) : Math.floor(s.distance / 14) % 2;
+ drawFox(ctx, s, legFrame, s.over);
+ drawSparks(ctx, s.sparks);
+
+ // Score, padded like an odometer; it warms to gold for a moment at each 500.
+ const color = s.milestoneGlow > 0 ? mixRgb(WHITE, GOLD, s.milestoneGlow) : "#ffffff";
+ ctx.fillStyle = "rgba(0,0,0,0.25)";
+ ctx.fillRect(WIDTH - 52, 4, 48, 13);
+ drawDigits(ctx, String(s.score).padStart(5, "0"), WIDTH - 7, 5, 10, color, "right", 600);
+}
+
+const desertDash: RetroGame<DesertState> = {
+ id: "desert-dash",
+ width: WIDTH,
+ height: HEIGHT,
+ create: (random) => createDesert(random),
+ step: (state, input, dt, random) => stepDesert(state, input, dt, random),
+ draw: (ctx, state, info) => drawDesert(ctx, state, info),
+ status: (state): RetroStatus => ({ score: state.score, over: state.over }),
+};
+
+export default desertDash;
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/games1Kit.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/games1Kit.ts
new file mode 100644
index 0000000000..9f03c1ea52
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/games1Kit.ts
@@ -0,0 +1,122 @@
+/**
+ * Small shared pieces for Neon Snake, Brick Breaker and Paddle Duel: a fixed
+ * spark pool (so a busy screen never allocates per step), a clamp, and the
+ * recording 2D context their draw tests paint into.
+ */
+
+export function clamp(value: number, lo: number, hi: number): number {
+ return value < lo ? lo : value > hi ? hi : value;
+}
+
+/** One square particle. `life` counts down to 0; a dead spark is reused. */
+export interface Spark {
+ x: number; y: number; vx: number; vy: number;
+ life: number; max: number; size: number; color: string;
+}
+
+/** A ring of preallocated sparks: emitting overwrites the oldest one when full. */
+export interface SparkPool {
+ list: Spark[];
+ next: number;
+}
+
+export function sparkPool(capacity: number): SparkPool {
+ const list: Spark[] = [];
+ for (let i = 0; i < capacity; i += 1) list.push({ x: 0, y: 0, vx: 0, vy: 0, life: 0, max: 1, size: 1, color: "#fff" });
+ return { list, next: 0 };
+}
+
+/** Burst `count` sparks out of (x, y) in random directions at up to `speed` px/s. */
+export function emitSparks(
+ pool: SparkPool, x: number, y: number, count: number, speed: number, color: string,
+ random: () => number, life = 0.5, size = 2,
+): void {
+ for (let i = 0; i < count; i += 1) {
+ const p = pool.list[pool.next];
+ pool.next = (pool.next + 1) % pool.list.length;
+ const a = random() * Math.PI * 2;
+ const v = speed * (0.3 + random() * 0.7);
+ p.x = x; p.y = y; p.vx = Math.cos(a) * v; p.vy = Math.sin(a) * v;
+ p.max = life * (0.6 + random() * 0.4); p.life = p.max; p.size = size; p.color = color;
+ }
+}
+
+/** Move and age the live sparks; `drag` is the fraction of speed kept per second. */
+export function stepSparks(pool: SparkPool, dt: number, gravity = 0, drag = 0.15): void {
+ const keep = Math.pow(drag, dt);
+ for (const p of pool.list) {
+ if (p.life <= 0) continue;
+ p.life -= dt;
+ p.vx *= keep; p.vy = p.vy * keep + gravity * dt;
+ p.x += p.vx * dt; p.y += p.vy * dt;
+ }
+}
+
+export function liveSparks(pool: SparkPool): number {
+ let n = 0;
+ for (const p of pool.list) if (p.life > 0) n += 1;
+ return n;
+}
+
+/** Paint the live sparks as fading squares; leaves globalAlpha at 1. */
+export function drawSparks(ctx: CanvasRenderingContext2D, pool: SparkPool): void {
+ for (const p of pool.list) {
+ if (p.life <= 0) continue;
+ ctx.globalAlpha = clamp(p.life / p.max, 0, 1);
+ ctx.fillStyle = p.color;
+ const s = p.size;
+ ctx.fillRect(Math.round(p.x - s / 2), Math.round(p.y - s / 2), s, s);
+ }
+ ctx.globalAlpha = 1;
+}
+
+/** Faint horizontal scanlines over the whole screen, for the CRT look. */
+export function drawScanlines(ctx: CanvasRenderingContext2D, width: number, height: number, alpha = 0.12): void {
+ ctx.globalAlpha = alpha;
+ ctx.fillStyle = "#000";
+ for (let y = 1; y < height; y += 3) ctx.fillRect(0, y, width, 1);
+ ctx.globalAlpha = 1;
+}
+
+/** What a draw test can check after painting into `recordingContext`. */
+export interface DrawRecord {
+ ctx: CanvasRenderingContext2D;
+ /** Method names in call order. */
+ calls: string[];
+ /** Every string passed to fillText. */
+ texts: string[];
+ /** Numeric arguments that were NaN or infinite (a broken frame). */
+ nonFinite: number;
+ /** save() minus restore(); 0 after a well-behaved draw. */
+ depth: number;
+}
+
+/**
+ * A stand-in 2D context for tests: it implements only the methods these games
+ * use, records the calls and counts bad numbers, so a draw test needs no
+ * canvas package and fails loudly when a game calls something else.
+ */
+export function recordingContext(): DrawRecord {
+ const record: DrawRecord = { ctx: null as unknown as CanvasRenderingContext2D, calls: [], texts: [], nonFinite: 0, depth: 0 };
+ const call = (name: string) => (...args: unknown[]): void => {
+ record.calls.push(name);
+ for (const a of args) if (typeof a === "number" && !Number.isFinite(a)) record.nonFinite += 1;
+ };
+ const fake = {
+ fillStyle: "#000" as string, strokeStyle: "#000" as string, globalAlpha: 1, lineWidth: 1,
+ font: "", textAlign: "start", textBaseline: "alphabetic",
+ fillRect: call("fillRect"), strokeRect: call("strokeRect"), clearRect: call("clearRect"),
+ beginPath: call("beginPath"), closePath: call("closePath"), moveTo: call("moveTo"), lineTo: call("lineTo"),
+ arc: call("arc"), rect: call("rect"), fill: call("fill"), stroke: call("stroke"),
+ translate: call("translate"),
+ save: (): void => { record.calls.push("save"); record.depth += 1; },
+ restore: (): void => { record.calls.push("restore"); record.depth -= 1; },
+ fillText: (text: string, x: number, y: number): void => {
+ record.calls.push("fillText");
+ record.texts.push(text);
+ if (!Number.isFinite(x) || !Number.isFinite(y)) record.nonFinite += 1;
+ },
+ };
+ record.ctx = fake as unknown as CanvasRenderingContext2D;
+ return record;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/games2Kit.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/games2Kit.ts
new file mode 100644
index 0000000000..258f6995b7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/games2Kit.ts
@@ -0,0 +1,105 @@
+/**
+ * Small helpers shared by Block Drop, Maze Muncher and Desert Dash.
+ *
+ * A fixed-size spark pool gives the games their juice (line-clear sparks,
+ * dust, bursts) without allocating per frame: the pool is created once with
+ * the run and dead slots are reused. Colour mixing turns a palette shift into
+ * a smooth blend instead of a hard cut, and `drawDigits` writes numbers (never
+ * words) in the arcade face.
+ */
+import { retroFont } from "../retroGame";
+
+export interface Spark {
+ x: number; y: number; vx: number; vy: number;
+ /** Seconds left; a spark with `life <= 0` is a free slot. */
+ life: number;
+ max: number;
+ size: number;
+ color: string;
+}
+
+export function sparkPool(capacity: number): Spark[] {
+ const pool: Spark[] = [];
+ for (let i = 0; i < capacity; i += 1) pool.push({ x: 0, y: 0, vx: 0, vy: 0, life: 0, max: 1, size: 1, color: "#ffffff" });
+ return pool;
+}
+
+/** Light a spark in a free slot, or in the one closest to dying when all are lit (the pool never grows). */
+export function emitSpark(pool: Spark[], x: number, y: number, vx: number, vy: number, life: number, size: number, color: string): void {
+ if (pool.length === 0) return;
+ let slot = pool[0];
+ for (let i = 0; i < pool.length; i += 1) {
+ const s = pool[i];
+ if (s.life <= 0) { slot = s; break; }
+ if (s.life < slot.life) slot = s;
+ }
+ slot.x = x; slot.y = y; slot.vx = vx; slot.vy = vy;
+ slot.life = life; slot.max = life; slot.size = size; slot.color = color;
+}
+
+/** Move every lit spark; `gravity` pulls down in pixels per second squared. */
+export function stepSparks(pool: Spark[], dt: number, gravity: number): void {
+ for (let i = 0; i < pool.length; i += 1) {
+ const s = pool[i];
+ if (s.life <= 0) continue;
+ s.life -= dt;
+ s.vy += gravity * dt;
+ s.x += s.vx * dt;
+ s.y += s.vy * dt;
+ }
+}
+
+export function clearSparks(pool: Spark[]): void {
+ for (let i = 0; i < pool.length; i += 1) pool[i].life = 0;
+}
+
+export function liveSparks(pool: Spark[]): number {
+ let n = 0;
+ for (let i = 0; i < pool.length; i += 1) if (pool[i].life > 0) n += 1;
+ return n;
+}
+
+/** Square sparks that fade out over their life. */
+export function drawSparks(ctx: CanvasRenderingContext2D, pool: Spark[]): void {
+ for (let i = 0; i < pool.length; i += 1) {
+ const s = pool[i];
+ if (s.life <= 0) continue;
+ ctx.globalAlpha = Math.max(0, Math.min(1, s.life / s.max));
+ ctx.fillStyle = s.color;
+ const half = s.size / 2;
+ ctx.fillRect(Math.round(s.x - half), Math.round(s.y - half), s.size, s.size);
+ }
+ ctx.globalAlpha = 1;
+}
+
+/** A number in the arcade face. Only digits and symbols ever reach the canvas. */
+export function drawDigits(
+ ctx: CanvasRenderingContext2D, value: number | string, x: number, y: number, px: number, color: string,
+ align: CanvasTextAlign = "left", weight = 400,
+): void {
+ ctx.font = retroFont(px, weight);
+ ctx.textAlign = align;
+ ctx.textBaseline = "top";
+ ctx.fillStyle = color;
+ ctx.fillText(typeof value === "number" ? String(Math.floor(value)) : value, x, y);
+}
+
+export type Rgb = readonly [number, number, number];
+
+export function hexRgb(hex: string): Rgb {
+ const n = parseInt(hex.slice(1), 16);
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
+}
+
+/** `a` blended towards `b` by `t` (0..1), as a CSS colour. */
+export function mixRgb(a: Rgb, b: Rgb, t: number): string {
+ const k = Math.max(0, Math.min(1, t));
+ const r = Math.round(a[0] + (b[0] - a[0]) * k);
+ const g = Math.round(a[1] + (b[1] - a[1]) * k);
+ const bl = Math.round(a[2] + (b[2] - a[2]) * k);
+ return `rgb(${r},${g},${bl})`;
+}
+
+export function clamp(v: number, lo: number, hi: number): number {
+ return v < lo ? lo : v > hi ? hi : v;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/games3Kit.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/games3Kit.ts
new file mode 100644
index 0000000000..eada9fad81
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/games3Kit.ts
@@ -0,0 +1,189 @@
+/**
+ * Small drawing and effect helpers shared by Pixel Raiders, Road Hopper and
+ * City Defense: pixel sprites compiled once from text, a pixel digit font
+ * (so scores look crisp before the web font loads and never need words), and
+ * a fixed-size particle pool. Nothing here allocates per frame.
+ */
+
+/** A bitmap compiled to horizontal runs: (x, y, length) triplets. */
+export interface PixelSprite {
+ w: number;
+ h: number;
+ runs: Int16Array;
+}
+
+/** Compile a sprite from rows of text where `#` is a lit pixel and anything else is empty. */
+export function sprite(rows: readonly string[]): PixelSprite {
+ const runs: number[] = [];
+ let w = 0;
+ rows.forEach((row, y) => {
+ w = Math.max(w, row.length);
+ let start = -1;
+ for (let x = 0; x <= row.length; x += 1) {
+ const lit = x < row.length && row[x] === "#";
+ if (lit && start < 0) start = x;
+ if (!lit && start >= 0) {
+ runs.push(start, y, x - start);
+ start = -1;
+ }
+ }
+ });
+ return { w, h: rows.length, runs: Int16Array.from(runs) };
+}
+
+/** Paint a sprite in the current fill style with its top-left at (x, y); `flip` mirrors it horizontally. */
+export function drawSprite(ctx: CanvasRenderingContext2D, s: PixelSprite, x: number, y: number, scale = 1, flip = false): void {
+ const r = s.runs;
+ const ox = Math.round(x), oy = Math.round(y);
+ for (let i = 0; i < r.length; i += 3) {
+ const rx = flip ? s.w - r[i] - r[i + 2] : r[i];
+ ctx.fillRect(ox + rx * scale, oy + r[i + 1] * scale, r[i + 2] * scale, scale);
+ }
+}
+
+const DIGITS: readonly PixelSprite[] = [
+ ["###", "#.#", "#.#", "#.#", "###"],
+ [".#.", "##.", ".#.", ".#.", "###"],
+ ["###", "..#", "###", "#..", "###"],
+ ["###", "..#", ".##", "..#", "###"],
+ ["#.#", "#.#", "###", "..#", "..#"],
+ ["###", "#..", "###", "..#", "###"],
+ ["###", "#..", "###", "#.#", "###"],
+ ["###", "..#", ".#.", ".#.", ".#."],
+ ["###", "#.#", "###", "#.#", "###"],
+ ["###", "#.#", "###", "..#", "###"],
+].map(sprite);
+
+/** Width in pixels of `value` written with `drawNumber` at `scale`. */
+export function numberWidth(value: number, scale = 1): number {
+ let n = Math.max(0, Math.floor(value));
+ let count = 1;
+ while (n >= 10) { n = Math.floor(n / 10); count += 1; }
+ return (count * 4 - 1) * scale;
+}
+
+/**
+ * Write a non-negative integer in the 3×5 pixel digit font, in the current
+ * fill style. `align` anchors x at the number's left edge, centre or right edge.
+ */
+export function drawNumber(
+ ctx: CanvasRenderingContext2D, value: number, x: number, y: number, scale = 1, align: "left" | "center" | "right" = "left",
+): void {
+ const n = Math.max(0, Math.floor(value));
+ const width = numberWidth(n, scale);
+ let right = align === "left" ? x + width : align === "center" ? x + width / 2 : x;
+ let rest = n;
+ do {
+ const d = rest % 10;
+ rest = Math.floor(rest / 10);
+ right -= 3 * scale;
+ drawSprite(ctx, DIGITS[d], right, y, scale);
+ right -= scale;
+ } while (rest > 0);
+}
+
+export function clamp(v: number, lo: number, hi: number): number {
+ return v < lo ? lo : v > hi ? hi : v;
+}
+
+/** One spark of an explosion, splash or puff; pooled, never allocated during play. */
+export interface Particle {
+ active: boolean;
+ x: number;
+ y: number;
+ vx: number;
+ vy: number;
+ life: number;
+ max: number;
+ size: number;
+ color: string;
+}
+
+export function makeParticles(count: number): Particle[] {
+ const pool: Particle[] = [];
+ for (let i = 0; i < count; i += 1) pool.push({ active: false, x: 0, y: 0, vx: 0, vy: 0, life: 0, max: 1, size: 1, color: "#fff" });
+ return pool;
+}
+
+/** Throw `count` sparks out of (x, y); when the pool is full the oldest-looking slots are reused. */
+export function emitBurst(
+ pool: Particle[], x: number, y: number, count: number, speed: number, color: string, random: () => number, life = 0.6, size = 1,
+): void {
+ let cursor = 0;
+ for (let n = 0; n < count; n += 1) {
+ // Find a free slot; if there is none, take the one closest to dying.
+ let slot = -1;
+ for (; cursor < pool.length; cursor += 1) if (!pool[cursor].active) { slot = cursor; break; }
+ if (slot < 0) {
+ let least = Infinity;
+ for (let i = 0; i < pool.length; i += 1) if (pool[i].life < least) { least = pool[i].life; slot = i; }
+ }
+ if (slot < 0) return;
+ const p = pool[slot];
+ const a = random() * Math.PI * 2;
+ const v = speed * (0.3 + random() * 0.7);
+ p.active = true;
+ p.x = x; p.y = y;
+ p.vx = Math.cos(a) * v; p.vy = Math.sin(a) * v;
+ p.max = life * (0.6 + random() * 0.4);
+ p.life = p.max;
+ p.size = size;
+ p.color = color;
+ }
+}
+
+export function stepParticles(pool: Particle[], dt: number, gravity = 0): void {
+ for (const p of pool) {
+ if (!p.active) continue;
+ p.life -= dt;
+ if (p.life <= 0) { p.active = false; continue; }
+ p.vy += gravity * dt;
+ p.x += p.vx * dt;
+ p.y += p.vy * dt;
+ }
+}
+
+export function clearParticles(pool: Particle[]): void {
+ for (const p of pool) p.active = false;
+}
+
+/** Sparks fade out over their life (alpha, not blinking, so this is fine under reduced motion). */
+export function drawParticles(ctx: CanvasRenderingContext2D, pool: Particle[]): void {
+ for (const p of pool) {
+ if (!p.active) continue;
+ ctx.globalAlpha = clamp(p.life / p.max, 0, 1);
+ ctx.fillStyle = p.color;
+ ctx.fillRect(Math.round(p.x), Math.round(p.y), p.size, p.size);
+ }
+ ctx.globalAlpha = 1;
+}
+
+/** Fixed star positions for a backdrop, derived from a seed so the sky never changes between frames. */
+export function starField(count: number, width: number, height: number, seed: number): Float32Array {
+ const stars = new Float32Array(count * 3);
+ let a = seed >>> 0;
+ const next = (): number => {
+ a = (Math.imul(a, 1664525) + 1013904223) >>> 0;
+ return a / 4294967296;
+ };
+ for (let i = 0; i < count; i += 1) {
+ stars[i * 3] = Math.floor(next() * width);
+ stars[i * 3 + 1] = Math.floor(next() * height);
+ stars[i * 3 + 2] = next();
+ }
+ return stars;
+}
+
+/**
+ * Paint a star field. Stars twinkle softly with `time` unless `reduced`, where
+ * they hold a steady brightness.
+ */
+export function drawStars(ctx: CanvasRenderingContext2D, stars: Float32Array, time: number, reduced: boolean, color = "#cfd8ff"): void {
+ ctx.fillStyle = color;
+ for (let i = 0; i < stars.length; i += 3) {
+ const phase = stars[i + 2];
+ ctx.globalAlpha = reduced ? 0.35 + phase * 0.4 : 0.3 + 0.45 * (0.5 + 0.5 * Math.sin(time * (0.8 + phase * 1.6) + phase * 40));
+ ctx.fillRect(stars[i], stars[i + 1], 1, 1);
+ }
+ ctx.globalAlpha = 1;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/mazeMuncher.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/mazeMuncher.test.ts
new file mode 100644
index 0000000000..39184f8d78
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/mazeMuncher.test.ts
@@ -0,0 +1,308 @@
+import { describe, expect, it } from "vitest";
+import { RETRO_STEP, idleInput, seededRandom, type RetroInput } from "../retroGame";
+import mazeMuncher, {
+ BONUS_X, BONUS_Y, CHAIN_POINTS, CLEAR_TIME, DOT_POINTS, DOWN, DYING_TIME, EXIT_X, EXIT_Y, LEFT, MAZE, MAZE_H, MAZE_W, NONE, ORB_POINTS,
+ PLAYER_START_X, PLAYER_START_Y, READY_TIME, RIGHT, UP, bugTarget, createMaze, frightDuration, isOpen, type MazeState,
+} from "./mazeMuncher";
+
+/** A 2D context stand-in: every call is a no-op, texts are recorded, non-finite numbers are flagged. */
+function fakeContext(texts: string[], bad: string[]): CanvasRenderingContext2D {
+ const target: Record<string, unknown> = {
+ fillText: (s: unknown) => { texts.push(String(s)); },
+ createLinearGradient: () => ({ addColorStop: () => undefined }),
+ createRadialGradient: () => ({ addColorStop: () => undefined }),
+ measureText: (s: string) => ({ width: s.length * 6 }),
+ };
+ return new Proxy(target, {
+ get: (t, key) => {
+ if (typeof key === "string" && key in t) return t[key];
+ return (...args: unknown[]) => {
+ if (args.some((a) => typeof a === "number" && !Number.isFinite(a))) bad.push(String(key));
+ };
+ },
+ set: (t, key, value) => { t[String(key)] = value; return true; },
+ }) as unknown as CanvasRenderingContext2D;
+}
+
+const random = seededRandom(5);
+const run = (s: MazeState, input: RetroInput, seconds: number) => {
+ for (let t = 0; t < seconds; t += RETRO_STEP) mazeMuncher.step(s, input, RETRO_STEP, random);
+};
+const press = (button: "left" | "right" | "up" | "down"): RetroInput => {
+ const input = idleInput();
+ input[button] = true;
+ input.pressed[button] = true;
+ return input;
+};
+/** A run already playing, with every bug parked in the pen for good. */
+const quiet = (): MazeState => {
+ const s = createMaze();
+ s.phase = "play";
+ s.phaseTimer = 0;
+ s.roundTime = -1e9;
+ s.dotsThisRound = -1e9;
+ for (const b of s.bugs) { b.mode = "pen"; b.x = 10; b.y = 9; }
+ return s;
+};
+const place = (s: MazeState, x: number, y: number, dir: number) => {
+ s.player.x = x; s.player.y = y; s.player.dir = dir; s.player.want = dir;
+};
+
+describe("maze muncher: the maze", () => {
+ it("is 21 × 21, mirror-symmetric, with four orbs and a wrap tunnel", () => {
+ expect(MAZE).toHaveLength(MAZE_H);
+ for (const row of MAZE) {
+ expect(row).toHaveLength(MAZE_W);
+ expect(row).toBe([...row].reverse().join(""));
+ }
+ expect(MAZE.join("").split("o")).toHaveLength(5);
+ expect(MAZE.some((row) => row[0] === "T" && row[MAZE_W - 1] === "T")).toBe(true);
+ expect(isOpen(-1, 9)).toBe(true);
+ expect(isOpen(EXIT_X, EXIT_Y + 1)).toBe(false); // the pen door
+ });
+
+ it("has no dead ends and every open tile is reachable", () => {
+ const open: Array<[number, number]> = [];
+ for (let y = 0; y < MAZE_H; y += 1) for (let x = 0; x < MAZE_W; x += 1) if (isOpen(x, y)) open.push([x, y]);
+ for (const [x, y] of open) {
+ const exits = [[0, -1], [-1, 0], [0, 1], [1, 0]].filter(([dx, dy]) => isOpen(x + dx, y + dy)).length;
+ expect(exits, `tile ${x},${y}`).toBeGreaterThanOrEqual(2);
+ }
+ const seen = new Set<string>([`${PLAYER_START_X},${PLAYER_START_Y}`]);
+ const queue: Array<[number, number]> = [[PLAYER_START_X, PLAYER_START_Y]];
+ while (queue.length) {
+ const [x, y] = queue.shift()!;
+ for (const [dx, dy] of [[0, -1], [-1, 0], [0, 1], [1, 0]]) {
+ const nx = (x + dx + MAZE_W) % MAZE_W, ny = y + dy;
+ if (!isOpen(nx, ny) || seen.has(`${nx},${ny}`)) continue;
+ seen.add(`${nx},${ny}`);
+ queue.push([nx, ny]);
+ }
+ }
+ expect(seen.size).toBe(open.length);
+ });
+});
+
+describe("maze muncher: play", () => {
+ it("starts with three lives, a full maze and a ready pause", () => {
+ const s = mazeMuncher.create(random);
+ expect(mazeMuncher.status(s)).toEqual({ score: 0, lives: 3, level: 1, over: false });
+ expect(s.dotsLeft).toBe(s.totalDots);
+ expect(s.totalDots).toBeGreaterThan(150);
+ run(s, idleInput(), READY_TIME / 2);
+ expect(s.player.x).toBe(PLAYER_START_X);
+ run(s, idleInput(), READY_TIME);
+ expect(s.phase).toBe("play");
+ expect(s.player.x).toBeLessThan(PLAYER_START_X);
+ });
+
+ it("stops at walls", () => {
+ const s = quiet();
+ place(s, 1, 1, UP);
+ run(s, idleInput(), 0.5);
+ expect([s.player.x, s.player.y]).toEqual([1, 1]);
+ place(s, 4, 1, LEFT);
+ run(s, idleInput(), 1);
+ expect([s.player.x, s.player.y]).toEqual([1, 1]);
+ expect(s.player.dir).toBe(NONE);
+ });
+
+ it("takes a buffered turn at the next junction where it is open", () => {
+ const s = quiet();
+ place(s, 7, 3, LEFT);
+ run(s, press("up"), RETRO_STEP);
+ // Columns 6 and 5 have walls above: keep running left.
+ run(s, idleInput(), 0.3);
+ expect(s.player.y).toBe(3);
+ expect(s.player.x).toBeLessThan(6);
+ run(s, idleInput(), 0.5);
+ expect(s.player.x).toBe(4);
+ expect(s.player.y).toBe(1); // turned up and ran on to the wall
+ });
+
+ it("reverses at once, mid-tile", () => {
+ const s = quiet();
+ place(s, 7, 3, LEFT);
+ run(s, idleInput(), 0.05);
+ const x = s.player.x;
+ run(s, press("right"), RETRO_STEP);
+ expect(s.player.dir).toBe(RIGHT);
+ expect(s.player.x).toBeGreaterThan(x);
+ });
+
+ it("wraps through the tunnel", () => {
+ const s = quiet();
+ place(s, 2, 9, LEFT);
+ run(s, idleInput(), 0.6);
+ expect(s.player.x).toBeGreaterThan(15);
+ expect(s.player.y).toBe(9);
+ });
+
+ it("eats dots for points", () => {
+ const s = quiet();
+ place(s, 1, 1, RIGHT);
+ const left = s.dotsLeft;
+ run(s, idleInput(), 0.6);
+ const eaten = left - s.dotsLeft;
+ expect(eaten).toBeGreaterThanOrEqual(3);
+ expect(s.score).toBe(eaten * DOT_POINTS);
+ expect(s.dots[1 * MAZE_W + 2]).toBe(0);
+ });
+
+ it("an orb frightens the bugs, and eaten bugs chain their points and go home", () => {
+ const s = quiet();
+ const [, a, b] = s.bugs;
+ a.mode = "active"; a.x = 9; a.y = 19; a.dir = LEFT;
+ b.mode = "active"; b.x = 15; b.y = 19; b.dir = LEFT;
+ place(s, 1, 1, DOWN);
+ s.dots[1 * MAZE_W + 1] = 0;
+ run(s, idleInput(), 0.15);
+ expect(s.dots[2 * MAZE_W + 1]).toBe(0);
+ expect(s.score).toBe(ORB_POINTS);
+ expect(s.frightTimer).toBeGreaterThan(0);
+ expect(a.frightened && b.frightened).toBe(true);
+
+ a.x = s.player.x; a.y = s.player.y;
+ run(s, idleInput(), RETRO_STEP);
+ expect(a.mode).toBe("eaten");
+ expect(s.score).toBe(ORB_POINTS + CHAIN_POINTS[0]);
+ run(s, idleInput(), 0.6);
+ b.x = s.player.x; b.y = s.player.y;
+ run(s, idleInput(), RETRO_STEP);
+ expect(b.mode).toBe("eaten");
+ expect(s.score - ORB_POINTS - CHAIN_POINTS[0]).toBeGreaterThanOrEqual(CHAIN_POINTS[1]);
+
+ // The eyes find their way back into the pen and come out again as a normal bug.
+ run(s, idleInput(), 6);
+ expect(["leaving", "active"]).toContain(a.mode);
+ expect(a.frightened).toBe(false);
+ });
+
+ it("the power wears off, sooner on later levels", () => {
+ const s = quiet();
+ s.bugs[1].mode = "active"; s.bugs[1].x = 9; s.bugs[1].y = 19; s.bugs[1].dir = LEFT;
+ place(s, 1, 1, DOWN);
+ run(s, idleInput(), frightDuration(1) + 0.5);
+ expect(s.frightTimer).toBe(0);
+ expect(s.bugs[1].frightened).toBe(false);
+ expect(frightDuration(4)).toBeLessThan(frightDuration(1));
+ });
+
+ it("loses a life on touching a bug, then restarts the round with the dots kept", () => {
+ const s = quiet();
+ place(s, 1, 1, RIGHT);
+ run(s, idleInput(), 0.4);
+ const left = s.dotsLeft;
+ const bug = s.bugs[0];
+ bug.mode = "active"; bug.x = s.player.x; bug.y = s.player.y; bug.dir = LEFT;
+ run(s, idleInput(), RETRO_STEP);
+ expect(s.phase).toBe("dying");
+ expect(mazeMuncher.status(s).lives).toBe(2);
+ run(s, idleInput(), DYING_TIME + 0.05);
+ expect(s.phase).toBe("ready");
+ expect([s.player.x, s.player.y]).toEqual([PLAYER_START_X, PLAYER_START_Y]);
+ expect(s.dotsLeft).toBe(left);
+ expect(s.over).toBe(false);
+ });
+
+ it("ends the run when the last life is lost", () => {
+ const s = quiet();
+ s.lives = 1;
+ const bug = s.bugs[0];
+ bug.mode = "active"; bug.x = s.player.x; bug.y = s.player.y; bug.dir = LEFT;
+ run(s, idleInput(), RETRO_STEP);
+ run(s, idleInput(), DYING_TIME + 0.05);
+ expect(mazeMuncher.status(s)).toMatchObject({ lives: 0, over: true });
+ });
+
+ it("clears the level when the last dot goes and starts a faster one", () => {
+ const s = quiet();
+ s.dots.fill(0);
+ s.dots[1 * MAZE_W + 2] = 1;
+ s.dotsLeft = 1;
+ place(s, 1, 1, RIGHT);
+ run(s, idleInput(), 0.3);
+ expect(s.phase).toBe("clear");
+ run(s, idleInput(), CLEAR_TIME + 0.05);
+ expect(s.level).toBe(2);
+ expect(s.dotsLeft).toBe(s.totalDots);
+ expect(s.phase).toBe("ready");
+ });
+
+ it("shows a bonus gem after enough dots, worth points when eaten", () => {
+ const s = quiet();
+ let n = 0;
+ const need = Math.floor(s.totalDots * 0.3) - 1;
+ for (let i = 0; i < s.dots.length && n < need; i += 1) if (s.dots[i] === 1) { s.dots[i] = 0; s.dotsLeft -= 1; n += 1; }
+ place(s, 9, 19, RIGHT);
+ s.dots[19 * MAZE_W + 10] = 1;
+ run(s, idleInput(), 0.3);
+ expect(s.bonusTimer).toBeGreaterThan(0);
+ const score = s.score;
+ place(s, BONUS_X - 1, BONUS_Y, RIGHT);
+ run(s, idleInput(), 0.3);
+ expect(s.bonusTimer).toBe(0);
+ expect(s.score - score).toBeGreaterThanOrEqual(100);
+ });
+
+ it("gives the four bugs four different chase targets", () => {
+ const s = quiet();
+ s.modeIndex = 1; // chase
+ place(s, 10, 15, LEFT);
+ s.bugs[0].x = 10; s.bugs[0].y = 7;
+ const out = { x: 0, y: 0 };
+ const targets = s.bugs.map((b) => {
+ b.x = b.index === 0 ? 10 : 18; b.y = b.index === 0 ? 7 : 3;
+ bugTarget(s, b, out);
+ return `${out.x},${out.y}`;
+ });
+ expect(targets[0]).toBe("10,15");
+ expect(targets[1]).toBe("6,15");
+ expect(new Set(targets.slice(0, 3)).size).toBe(3);
+ // The drifter chases from afar but backs off up close.
+ expect(targets[3]).toBe("10,15");
+ const drifter = s.bugs[3];
+ drifter.x = 9; drifter.y = 15;
+ bugTarget(s, drifter, out);
+ expect(`${out.x},${out.y}`).not.toBe("10,15");
+ });
+
+ it("the bugs leave the pen and roam without ever standing in a wall", () => {
+ const s = createMaze();
+ for (let t = 0; t < 30; t += RETRO_STEP) {
+ mazeMuncher.step(s, idleInput(), RETRO_STEP, random);
+ if (s.phase === "dying") { s.phase = "play"; s.lives = 3; }
+ for (const b of s.bugs) {
+ if (b.mode !== "active") continue;
+ expect(isOpen(Math.round(b.x), Math.round(b.y)), `bug ${b.index} at ${b.x},${b.y}`).toBe(true);
+ }
+ }
+ expect(s.bugs.filter((b) => b.mode === "active").length).toBeGreaterThanOrEqual(3);
+ });
+
+ it("draws every state without throwing, without words and without bad numbers", () => {
+ const texts: string[] = [];
+ const bad: string[] = [];
+ const ctx = fakeContext(texts, bad);
+ const s = mazeMuncher.create(random);
+ mazeMuncher.draw(ctx, s, { time: 0, reduced: false, idle: true });
+ mazeMuncher.draw(ctx, s, { time: 1, reduced: true, idle: true });
+ run(s, idleInput(), 3);
+ mazeMuncher.draw(ctx, s, { time: 3, reduced: false, idle: false });
+ s.frightTimer = 1; for (const b of s.bugs) b.frightened = true;
+ s.bonusTimer = 3;
+ s.bugs[0].mode = "eaten";
+ mazeMuncher.draw(ctx, s, { time: 4, reduced: false, idle: false });
+ mazeMuncher.draw(ctx, s, { time: 4, reduced: true, idle: false });
+ s.phase = "dying"; s.phaseTimer = DYING_TIME / 2;
+ mazeMuncher.draw(ctx, s, { time: 5, reduced: false, idle: false });
+ s.phase = "clear"; s.phaseTimer = 1;
+ mazeMuncher.draw(ctx, s, { time: 6, reduced: false, idle: false });
+ mazeMuncher.draw(ctx, s, { time: 6, reduced: true, idle: false });
+ s.over = true;
+ mazeMuncher.draw(ctx, s, { time: 7, reduced: false, idle: false });
+ expect(bad).toEqual([]);
+ expect(texts.length).toBeGreaterThan(0);
+ for (const text of texts) expect(text).not.toMatch(/[A-Za-z]/);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/mazeMuncher.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/mazeMuncher.ts
new file mode 100644
index 0000000000..6fdf8ebb33
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/mazeMuncher.ts
@@ -0,0 +1,722 @@
+/**
+ * "Maze Muncher": the maze-chase cabinet.
+ *
+ * A round chomper clears a symmetric maze of dots while four "glitch bugs"
+ * (little robot beetles) hunt it. The maze is this game's own: 21 × 21 tiles
+ * with a wrap tunnel through the middle row and a pen in the centre the bugs
+ * start in and return to. Turns are buffered: a direction pressed before a
+ * junction is taken at the junction, a reversal is taken at once.
+ *
+ * Each bug has its own targeting personality (hunter, ambusher, flanker,
+ * drifter) and they alternate scatter and chase phases on a schedule. Eating
+ * one of the four power orbs turns them vulnerable for a while (shorter on
+ * later levels); eaten bugs chain 200 / 400 / 800 / 1600 and race back to the
+ * pen as a pair of eyes. A bonus gem shows up twice per level. Clearing every
+ * dot starts the next, faster level; three lives.
+ *
+ * Positions are in tile units with tile centres on integer coordinates;
+ * movers only change direction exactly on a centre, which keeps the grid
+ * logic simple and exact.
+ */
+import type { RetroDrawInfo, RetroGame, RetroInput, RetroStatus } from "../retroGame";
+import { drawDigits, drawSparks, emitSpark, sparkPool, stepSparks, type Spark } from "./games2Kit";
+
+/**
+ * The maze: `#` wall, `.` dot, `o` power orb, ` ` open without a dot,
+ * `T` tunnel mouth (open, wraps to the other side), `P` pen inside, `-` pen door.
+ */
+export const MAZE: readonly string[] = [
+ "#####################",
+ "#.........#.........#",
+ "#o##.####.#.####.##o#",
+ "#...................#",
+ "#.##.#.#######.#.##.#",
+ "#....#....#....#....#",
+ "####.####.#.####.####",
+ "####.#.........#.####",
+ "####.#.###-###.#.####",
+ "T......#PPPPP#......T",
+ "####.#.#######.#.####",
+ "####.#.........#.####",
+ "####.#.#######.#.####",
+ "#.........#.........#",
+ "#.##.####.#.####.##.#",
+ "#o.#...... ......#.o#",
+ "##.#.#.#######.#.#.##",
+ "#....#....#....#....#",
+ "#.#######.#.#######.#",
+ "#...................#",
+ "#####################",
+];
+export const MAZE_W = 21;
+export const MAZE_H = 21;
+
+/** Directions: up, left, down, right (also the tie-break order of the bugs); -1 is standing still. */
+export const UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3, NONE = -1;
+const DX = [0, -1, 0, 1];
+const DY = [-1, 0, 1, 0];
+const OPPOSITE = [DOWN, RIGHT, UP, LEFT];
+
+export const PLAYER_START_X = 10, PLAYER_START_Y = 15;
+/** The tile just above the pen door: bugs leave from here and eyes head back to it. */
+export const EXIT_X = 10, EXIT_Y = 7;
+const PEN_Y = 9;
+const PEN_X = [10, 10, 9, 11];
+export const BONUS_X = 10, BONUS_Y = 11;
+const TUNNEL_ROW = 9;
+
+export const DOT_POINTS = 10;
+export const ORB_POINTS = 50;
+export const CHAIN_POINTS: readonly number[] = [200, 400, 800, 1600];
+export const BONUS_POINTS: readonly number[] = [100, 300, 500, 700, 1000, 2000, 3000, 5000];
+export const START_LIVES = 3;
+export const READY_TIME = 1.6;
+export const DYING_TIME = 1.4;
+export const CLEAR_TIME = 2;
+const EAT_PAUSE = 0.5;
+const BONUS_TIME = 9;
+/** Scatter and chase alternate with these durations (seconds); the last chase lasts forever. */
+const SCHEDULE: readonly number[] = [7, 20, 7, 20, 5, 20, 5, Infinity];
+const RELEASE_TIME = [0, 1, 5, 9];
+const RELEASE_DOTS = [0, 0, 25, 50];
+/** Each bug's scatter corner (outside the maze, so they circle the nearest block). */
+const CORNER_X = [19, 1, 20, 0];
+const CORNER_Y = [-2, -2, 22, 22];
+const EPS = 1e-6;
+
+export type BugMode = "pen" | "leaving" | "active" | "eaten" | "entering";
+
+export interface Mover { x: number; y: number; dir: number }
+
+export interface Chomper extends Mover {
+ /** The buffered direction, taken at the next centre where it is open. */
+ want: number;
+ /** Distance travelled, for the chewing animation. */
+ chew: number;
+}
+
+export interface Bug extends Mover {
+ index: number;
+ mode: BugMode;
+ frightened: boolean;
+}
+
+export type MazePhase = "ready" | "play" | "dying" | "clear";
+
+export interface Popup { x: number; y: number; value: number; time: number }
+
+export interface MazeState {
+ /** One entry per tile: 0 nothing, 1 dot, 2 power orb. */
+ dots: Uint8Array;
+ dotsLeft: number;
+ totalDots: number;
+ player: Chomper;
+ bugs: Bug[];
+ score: number;
+ lives: number;
+ level: number;
+ over: boolean;
+ phase: MazePhase;
+ phaseTimer: number;
+ /** Index into SCHEDULE (even = scatter, odd = chase) and seconds spent in it. */
+ modeIndex: number;
+ modeTimer: number;
+ frightTimer: number;
+ /** Bugs eaten during the current power orb. */
+ chain: number;
+ /** Freeze after eating a bug, while its points show. */
+ eatPause: number;
+ roundTime: number;
+ dotsThisRound: number;
+ bonusTimer: number;
+ bonusShown: number;
+ popups: Popup[];
+ sparks: Spark[];
+ ticks: number;
+}
+
+function tileAt(tx: number, ty: number): string {
+ if (ty < 0 || ty >= MAZE_H) return "#";
+ const x = ((tx % MAZE_W) + MAZE_W) % MAZE_W;
+ return MAZE[ty][x];
+}
+
+/** Whether a mover may stand on this tile (the pen and its door are only entered by script). */
+export function isOpen(tx: number, ty: number): boolean {
+ const c = tileAt(tx, ty);
+ return c !== "#" && c !== "P" && c !== "-";
+}
+
+function openDir(m: Mover, dir: number): boolean {
+ return isOpen(Math.round(m.x) + DX[dir], Math.round(m.y) + DY[dir]);
+}
+
+function atCentre(m: Mover): boolean {
+ return Math.abs(m.x - Math.round(m.x)) < EPS && Math.abs(m.y - Math.round(m.y)) < EPS;
+}
+
+function wrapX(m: Mover): void {
+ if (m.x < -0.5) m.x += MAZE_W;
+ else if (m.x > MAZE_W - 0.5) m.x -= MAZE_W;
+}
+
+export function levelSpeed(level: number): number {
+ return Math.min(1.3, 1 + (level - 1) * 0.06);
+}
+
+export function frightDuration(level: number): number {
+ return Math.max(1.5, 7 - (level - 1) * 1.1);
+}
+
+function fillDots(s: MazeState): void {
+ let n = 0;
+ for (let y = 0; y < MAZE_H; y += 1) {
+ for (let x = 0; x < MAZE_W; x += 1) {
+ const c = MAZE[y][x];
+ const v = c === "." ? 1 : c === "o" ? 2 : 0;
+ s.dots[y * MAZE_W + x] = v;
+ if (v) n += 1;
+ }
+ }
+ s.dotsLeft = n;
+ s.totalDots = n;
+ s.bonusShown = 0;
+ s.bonusTimer = 0;
+}
+
+/** Put everyone back at their start (after a lost life or a cleared level). */
+function resetRound(s: MazeState): void {
+ const p = s.player;
+ p.x = PLAYER_START_X; p.y = PLAYER_START_Y; p.dir = NONE; p.want = LEFT; p.chew = 0;
+ for (const b of s.bugs) {
+ b.frightened = false;
+ if (b.index === 0) { b.x = EXIT_X; b.y = EXIT_Y; b.dir = LEFT; b.mode = "active"; }
+ else { b.x = PEN_X[b.index]; b.y = PEN_Y; b.dir = UP; b.mode = "pen"; }
+ }
+ s.modeIndex = 0; s.modeTimer = 0; s.frightTimer = 0; s.chain = 0; s.eatPause = 0;
+ s.roundTime = 0; s.dotsThisRound = 0; s.bonusTimer = 0;
+ s.phase = "ready"; s.phaseTimer = READY_TIME;
+}
+
+export function createMaze(): MazeState {
+ const s: MazeState = {
+ dots: new Uint8Array(MAZE_W * MAZE_H), dotsLeft: 0, totalDots: 0,
+ player: { x: 0, y: 0, dir: NONE, want: LEFT, chew: 0 },
+ bugs: [0, 1, 2, 3].map((index) => ({ index, x: 0, y: 0, dir: UP, mode: "pen" as BugMode, frightened: false })),
+ score: 0, lives: START_LIVES, level: 1, over: false, phase: "ready", phaseTimer: READY_TIME,
+ modeIndex: 0, modeTimer: 0, frightTimer: 0, chain: 0, eatPause: 0, roundTime: 0, dotsThisRound: 0,
+ bonusTimer: 0, bonusShown: 0,
+ popups: [0, 1, 2].map(() => ({ x: 0, y: 0, value: 0, time: 0 })),
+ sparks: sparkPool(48), ticks: 0,
+ };
+ fillDots(s);
+ resetRound(s);
+ return s;
+}
+
+function scatterPhase(s: MazeState): boolean {
+ return s.modeIndex % 2 === 0;
+}
+
+/** Where a bug is heading right now; its personality decides in chase phases. */
+export function bugTarget(s: MazeState, b: Bug, out: { x: number; y: number }): void {
+ if (b.mode === "eaten") { out.x = EXIT_X; out.y = EXIT_Y; return; }
+ const p = s.player;
+ const px = Math.round(p.x), py = Math.round(p.y);
+ const pd = p.dir >= 0 ? p.dir : p.want >= 0 ? p.want : LEFT;
+ if (scatterPhase(s)) { out.x = CORNER_X[b.index]; out.y = CORNER_Y[b.index]; return; }
+ switch (b.index) {
+ case 0: // Hunter: straight at the chomper.
+ out.x = px; out.y = py; return;
+ case 1: // Ambusher: four tiles ahead of it.
+ out.x = px + DX[pd] * 4; out.y = py + DY[pd] * 4; return;
+ case 2: { // Flanker: mirror the hunter through the point two tiles ahead, closing a pincer.
+ const ax = px + DX[pd] * 2, ay = py + DY[pd] * 2;
+ const h = s.bugs[0];
+ out.x = ax * 2 - Math.round(h.x); out.y = ay * 2 - Math.round(h.y); return;
+ }
+ default: { // Drifter: chases from afar, loses its nerve up close.
+ const dx = b.x - p.x, dy = b.y - p.y;
+ if (dx * dx + dy * dy > 64) { out.x = px; out.y = py; }
+ else { out.x = CORNER_X[3]; out.y = CORNER_Y[3]; }
+ }
+ }
+}
+
+const target = { x: 0, y: 0 };
+
+function chooseBugDir(s: MazeState, b: Bug, random: () => number): number {
+ // Eyes stop on the tile above the door; the pen script takes them in from there.
+ if (b.mode === "eaten" && Math.round(b.x) === EXIT_X && Math.round(b.y) === EXIT_Y) return NONE;
+ const back = b.dir >= 0 ? OPPOSITE[b.dir] : NONE;
+ let count = 0;
+ for (let d = 0; d < 4; d += 1) if (d !== back && openDir(b, d)) count += 1;
+ if (count === 0) return back >= 0 && openDir(b, back) ? back : NONE;
+ if (b.frightened) {
+ // Panicking bugs pick a random open way at every junction.
+ let pick = Math.floor(random() * count);
+ for (let d = 0; d < 4; d += 1) {
+ if (d === back || !openDir(b, d)) continue;
+ if (pick === 0) return d;
+ pick -= 1;
+ }
+ }
+ bugTarget(s, b, target);
+ let best = NONE, bestDist = Infinity;
+ const bx = Math.round(b.x), by = Math.round(b.y);
+ for (let d = 0; d < 4; d += 1) {
+ if (d === back || !openDir(b, d)) continue;
+ const dx = bx + DX[d] - target.x, dy = by + DY[d] - target.y;
+ const dist = dx * dx + dy * dy;
+ if (dist < bestDist) { bestDist = dist; best = d; }
+ }
+ return best;
+}
+
+function choosePlayerDir(p: Chomper): number {
+ if (p.want >= 0 && openDir(p, p.want)) return p.want;
+ if (p.dir >= 0 && openDir(p, p.dir)) return p.dir;
+ return NONE;
+}
+
+/**
+ * Move along the grid by `dist` tiles, choosing a new direction on every tile
+ * centre reached. Returns the distance actually travelled.
+ */
+function advance(s: MazeState, m: Mover, dist: number, bug: Bug | null, random: () => number): number {
+ let moved = 0;
+ for (let guard = 0; dist > EPS && guard < 8; guard += 1) {
+ if (atCentre(m)) {
+ m.x = Math.round(m.x); m.y = Math.round(m.y);
+ const dir = bug ? chooseBugDir(s, bug, random) : choosePlayerDir(m as Chomper);
+ if (dir < 0) { if (!bug) m.dir = NONE; return moved; }
+ m.dir = dir;
+ }
+ const horizontal = DX[m.dir] !== 0;
+ const sign = DX[m.dir] + DY[m.dir];
+ const along = horizontal ? m.x : m.y;
+ const next = sign > 0 ? Math.floor(along + EPS) + 1 : Math.ceil(along - EPS) - 1;
+ const gap = Math.abs(next - along);
+ const stepLen = Math.min(dist, gap);
+ if (horizontal) m.x = gap - stepLen < EPS ? next : m.x + sign * stepLen;
+ else m.y = gap - stepLen < EPS ? next : m.y + sign * stepLen;
+ dist -= stepLen;
+ moved += stepLen;
+ wrapX(m);
+ }
+ return moved;
+}
+
+/** Move straight towards a point (pen moves are scripted, not on the grid). Returns true on arrival. */
+function glide(m: Mover, tx: number, ty: number, dist: number): boolean {
+ const dx = tx - m.x, dy = ty - m.y;
+ const len = Math.hypot(dx, dy);
+ if (len <= dist) { m.x = tx; m.y = ty; return true; }
+ m.x += (dx / len) * dist;
+ m.y += (dy / len) * dist;
+ if (Math.abs(dx) > Math.abs(dy)) m.dir = dx < 0 ? LEFT : RIGHT;
+ else m.dir = dy < 0 ? UP : DOWN;
+ return false;
+}
+
+function inTunnel(m: Mover): boolean {
+ return Math.round(m.y) === TUNNEL_ROW && (m.x < 3.5 || m.x > MAZE_W - 4.5);
+}
+
+function popup(s: MazeState, x: number, y: number, value: number): void {
+ let slot = s.popups[0];
+ for (const p of s.popups) if (p.time < slot.time) slot = p;
+ slot.x = x; slot.y = y; slot.value = value; slot.time = 1;
+}
+
+function burst(s: MazeState, x: number, y: number, color: string, count: number, random: () => number): void {
+ for (let i = 0; i < count; i += 1) {
+ const a = random() * Math.PI * 2, v = 20 + random() * 50;
+ emitSpark(s.sparks, tileCx(x), tileCy(y), Math.cos(a) * v, Math.sin(a) * v, 0.35 + random() * 0.35, 2, color);
+ }
+}
+
+function held(input: RetroInput, dir: number): boolean {
+ return dir === UP ? input.up : dir === LEFT ? input.left : dir === DOWN ? input.down : input.right;
+}
+
+function readInput(p: Chomper, input: RetroInput): void {
+ const pr = input.pressed;
+ if (pr.up) p.want = UP;
+ else if (pr.left) p.want = LEFT;
+ else if (pr.down) p.want = DOWN;
+ else if (pr.right) p.want = RIGHT;
+ else {
+ // Two keys held and the buffered one let go: switch to the one still held.
+ if (p.want >= 0 && !held(input, p.want)) for (let d = 0; d < 4; d += 1) if (held(input, d)) { p.want = d; break; }
+ }
+ if (p.dir >= 0 && p.want === OPPOSITE[p.dir]) p.dir = p.want;
+}
+
+function eatDots(s: MazeState, random: () => number): void {
+ const p = s.player;
+ const tx = ((Math.round(p.x) % MAZE_W) + MAZE_W) % MAZE_W, ty = Math.round(p.y);
+ const i = ty * MAZE_W + tx;
+ const v = s.dots[i];
+ if (v !== 0) {
+ s.dots[i] = 0;
+ s.dotsLeft -= 1;
+ s.dotsThisRound += 1;
+ if (v === 2) {
+ s.score += ORB_POINTS;
+ s.frightTimer = frightDuration(s.level);
+ s.chain = 0;
+ for (const b of s.bugs) {
+ if (b.mode !== "active") continue;
+ b.frightened = true;
+ if (b.dir >= 0) b.dir = OPPOSITE[b.dir];
+ }
+ burst(s, tx, ty, "#ffd23f", 10, random);
+ } else {
+ s.score += DOT_POINTS;
+ }
+ const eaten = s.totalDots - s.dotsLeft;
+ if (s.bonusShown < 2 && eaten >= Math.floor(s.totalDots * (s.bonusShown === 0 ? 0.3 : 0.7))) {
+ s.bonusShown += 1;
+ s.bonusTimer = BONUS_TIME;
+ }
+ if (s.dotsLeft === 0) { s.phase = "clear"; s.phaseTimer = CLEAR_TIME; }
+ }
+ if (s.bonusTimer > 0 && Math.abs(p.x - BONUS_X) < 0.6 && Math.abs(p.y - BONUS_Y) < 0.6) {
+ const points = BONUS_POINTS[Math.min(s.level - 1, BONUS_POINTS.length - 1)];
+ s.score += points;
+ s.bonusTimer = 0;
+ popup(s, BONUS_X, BONUS_Y, points);
+ burst(s, BONUS_X, BONUS_Y, bonusColor(s.level), 12, random);
+ }
+}
+
+function moveBug(s: MazeState, b: Bug, dt: number, random: () => number): void {
+ const k = levelSpeed(s.level);
+ switch (b.mode) {
+ case "pen":
+ if (s.roundTime >= RELEASE_TIME[b.index] / k || s.dotsThisRound >= RELEASE_DOTS[b.index]) b.mode = "leaving";
+ return;
+ case "leaving": {
+ const step = 3.5 * dt;
+ if (Math.abs(b.x - EXIT_X) > EPS) { glide(b, EXIT_X, b.y, step); return; }
+ if (glide(b, EXIT_X, EXIT_Y, step)) { b.mode = "active"; b.dir = LEFT; b.frightened = false; }
+ return;
+ }
+ case "entering":
+ if (glide(b, EXIT_X, PEN_Y, 6 * dt)) b.mode = "leaving";
+ return;
+ case "eaten":
+ advance(s, b, 14 * dt, b, random);
+ if (Math.abs(b.x - EXIT_X) < 0.15 && Math.abs(b.y - EXIT_Y) < 0.15) { b.x = EXIT_X; b.y = EXIT_Y; b.mode = "entering"; }
+ return;
+ default: {
+ const speed = inTunnel(b) ? 3.6 : b.frightened ? 4.2 : 6.8 * k;
+ advance(s, b, speed * dt, b, random);
+ }
+ }
+}
+
+function collide(s: MazeState, random: () => number): void {
+ const p = s.player;
+ for (const b of s.bugs) {
+ if (b.mode !== "active") continue;
+ if (Math.abs(b.x - p.x) > 0.6 || Math.abs(b.y - p.y) > 0.6) continue;
+ if (b.frightened) {
+ const points = CHAIN_POINTS[Math.min(s.chain, CHAIN_POINTS.length - 1)];
+ s.chain += 1;
+ s.score += points;
+ b.frightened = false;
+ b.mode = "eaten";
+ s.eatPause = EAT_PAUSE;
+ popup(s, b.x, b.y, points);
+ burst(s, b.x, b.y, "#3de8ff", 10, random);
+ } else {
+ s.lives -= 1;
+ s.phase = "dying";
+ s.phaseTimer = DYING_TIME;
+ return;
+ }
+ }
+}
+
+export function stepMaze(s: MazeState, input: RetroInput, dt: number, random: () => number): void {
+ s.ticks += 1;
+ stepSparks(s.sparks, dt, 0);
+ for (const p of s.popups) p.time = Math.max(0, p.time - dt);
+ if (s.over) return;
+ readInput(s.player, input);
+
+ if (s.phase !== "play") {
+ s.phaseTimer -= dt;
+ if (s.phase === "dying" && s.phaseTimer < DYING_TIME * 0.25 && s.phaseTimer + dt >= DYING_TIME * 0.25) {
+ burst(s, s.player.x, s.player.y, "#ffd23f", 16, random);
+ }
+ if (s.phaseTimer > 0) return;
+ if (s.phase === "dying") {
+ if (s.lives <= 0) { s.over = true; return; }
+ resetRound(s);
+ } else if (s.phase === "clear") {
+ s.level += 1;
+ fillDots(s);
+ resetRound(s);
+ } else {
+ s.phase = "play";
+ }
+ return;
+ }
+
+ if (s.eatPause > 0) { s.eatPause -= dt; return; }
+ s.roundTime += dt;
+ if (s.bonusTimer > 0) s.bonusTimer = Math.max(0, s.bonusTimer - dt);
+
+ if (s.frightTimer > 0) {
+ s.frightTimer -= dt;
+ if (s.frightTimer <= 0) { s.frightTimer = 0; for (const b of s.bugs) b.frightened = false; }
+ } else {
+ s.modeTimer += dt;
+ if (s.modeTimer >= SCHEDULE[s.modeIndex]) {
+ s.modeTimer = 0;
+ s.modeIndex = Math.min(SCHEDULE.length - 1, s.modeIndex + 1);
+ // A change of phase turns every bug around, the classic tell.
+ for (const b of s.bugs) if (b.mode === "active" && b.dir >= 0) b.dir = OPPOSITE[b.dir];
+ }
+ }
+
+ const p = s.player;
+ p.chew += advance(s, p, 7.2 * levelSpeed(s.level) * dt, null, random);
+ eatDots(s, random);
+ if (s.phase !== "play") return;
+ collide(s, random);
+ if (s.phase !== "play" || s.eatPause > 0) return;
+ for (const b of s.bugs) moveBug(s, b, dt, random);
+ collide(s, random);
+}
+
+// ---------------------------------------------------------------- drawing
+
+export const TILE = 10;
+const OY = 14;
+export const WIDTH = MAZE_W * TILE;
+export const HEIGHT = MAZE_H * TILE + OY * 2;
+
+function tileCx(x: number): number { return x * TILE + TILE / 2; }
+function tileCy(y: number): number { return OY + y * TILE + TILE / 2; }
+
+/** Wall outlines as line segments (x1, y1, x2, y2), traced once: every wall edge facing open floor. */
+const WALL_SEGMENTS: number[] = (() => {
+ const out: number[] = [];
+ // The pen counts as floor here, so its walls are outlined on the inside too.
+ const solid = (x: number, y: number) => x < 0 || x >= MAZE_W || y < 0 || y >= MAZE_H || MAZE[y][x] === "#";
+ const inset = 2;
+ for (let y = 0; y < MAZE_H; y += 1) {
+ for (let x = 0; x < MAZE_W; x += 1) {
+ if (MAZE[y][x] !== "#") continue;
+ const l = x * TILE, t = OY + y * TILE, r = l + TILE, b = t + TILE;
+ // An edge is outlined where the neighbour is floor; the line sits just inside the wall.
+ if (!solid(x, y - 1)) out.push(l, t + inset, r, t + inset);
+ if (!solid(x, y + 1)) out.push(l, b - inset, r, b - inset);
+ if (!solid(x - 1, y)) out.push(l + inset, t, l + inset, b);
+ if (!solid(x + 1, y)) out.push(r - inset, t, r - inset, b);
+ }
+ }
+ return out;
+})();
+
+const BUG_COLORS = ["#ff4d5e", "#ff7ad9", "#3de8ff", "#ffa13d"];
+const BONUS_COLORS = ["#ff4d5e", "#ffa13d", "#ffd23f", "#5dea6a", "#3de8ff", "#4a7dff", "#b06bff", "#ffffff"];
+
+function bonusColor(level: number): string {
+ return BONUS_COLORS[Math.min(level - 1, BONUS_COLORS.length - 1)];
+}
+
+function drawGem(ctx: CanvasRenderingContext2D, cx: number, cy: number, r: number, color: string): void {
+ ctx.fillStyle = color;
+ ctx.beginPath();
+ ctx.moveTo(cx, cy - r); ctx.lineTo(cx + r, cy - r * 0.2); ctx.lineTo(cx, cy + r); ctx.lineTo(cx - r, cy - r * 0.2);
+ ctx.closePath();
+ ctx.fill();
+ ctx.fillStyle = "rgba(255,255,255,0.6)";
+ ctx.beginPath();
+ ctx.moveTo(cx, cy - r); ctx.lineTo(cx + r * 0.4, cy - r * 0.2); ctx.lineTo(cx, cy + r * 0.2); ctx.lineTo(cx - r * 0.4, cy - r * 0.2);
+ ctx.closePath();
+ ctx.fill();
+}
+
+/** The chomper: a disc with a mouth wedge facing its direction. `open` is the half-angle in radians. */
+function drawChomper(ctx: CanvasRenderingContext2D, cx: number, cy: number, r: number, dir: number, open: number): void {
+ const facing = dir === UP ? -Math.PI / 2 : dir === LEFT ? Math.PI : dir === DOWN ? Math.PI / 2 : 0;
+ ctx.fillStyle = "#ffd23f";
+ ctx.beginPath();
+ if (open >= Math.PI - 0.01) return;
+ ctx.moveTo(cx, cy);
+ ctx.arc(cx, cy, r, facing + open, facing + Math.PI * 2 - open);
+ ctx.closePath();
+ ctx.fill();
+ // A little eye, set back from the mouth.
+ const ex = cx + Math.cos(facing - Math.PI / 2 - 0.5) * r * 0.5;
+ const ey = cy + Math.sin(facing - Math.PI / 2 - 0.5) * r * 0.5;
+ ctx.fillStyle = "#2b1f05";
+ ctx.fillRect(Math.round(ex - 1), Math.round(ey - 1), 2, 2);
+}
+
+/** A glitch bug: domed robot beetle with antennae, a visor and scuttling legs. */
+function drawBug(ctx: CanvasRenderingContext2D, s: MazeState, b: Bug, info: RetroDrawInfo): void {
+ const bob = b.mode === "pen" && !info.reduced ? Math.sin(info.time * 5 + b.index * 2) * 1.5 : 0;
+ const cx = tileCx(b.x), cy = tileCy(b.y) + bob;
+ const lookX = b.dir >= 0 ? DX[b.dir] : 0, lookY = b.dir >= 0 ? DY[b.dir] : 0;
+ if (b.mode !== "eaten" && b.mode !== "entering") {
+ let body = BUG_COLORS[b.index];
+ if (b.frightened) {
+ const left = s.frightTimer;
+ body = "#2a3cc8";
+ if (left < 2) {
+ if (info.reduced) {
+ // Fade towards pale instead of blinking.
+ const k = 1 - left / 2;
+ body = `rgb(${Math.round(42 + 180 * k)},${Math.round(60 + 160 * k)},${Math.round(200 + 40 * k)})`;
+ } else if (Math.floor(left * 5) % 2 === 0) {
+ body = "#e8ecff";
+ }
+ }
+ }
+ const legPhase = info.reduced ? 0 : Math.floor((info.time * 10 + b.index) % 2);
+ ctx.strokeStyle = body;
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ for (let i = -1; i <= 1; i += 1) {
+ const lx = cx + i * 3, kick = (i + legPhase) % 2 === 0 ? 1 : 0;
+ ctx.moveTo(lx, cy + 3); ctx.lineTo(lx + (i === 0 ? 0 : i), cy + 5 + kick);
+ }
+ // Antennae.
+ ctx.moveTo(cx - 2, cy - 4); ctx.lineTo(cx - 3, cy - 6);
+ ctx.moveTo(cx + 2, cy - 4); ctx.lineTo(cx + 3, cy - 6);
+ ctx.stroke();
+ ctx.fillStyle = body;
+ ctx.beginPath();
+ ctx.arc(cx, cy, 4.5, Math.PI, 0);
+ ctx.lineTo(cx + 4.5, cy + 3);
+ ctx.lineTo(cx - 4.5, cy + 3);
+ ctx.closePath();
+ ctx.fill();
+ ctx.fillRect(Math.round(cx - 3.5), Math.round(cy - 7), 1, 1);
+ ctx.fillRect(Math.round(cx + 2.5), Math.round(cy - 7), 1, 1);
+ if (b.frightened) {
+ // A jagged glitch mouth instead of a visor.
+ ctx.strokeStyle = "#ffe0f0";
+ ctx.beginPath();
+ ctx.moveTo(cx - 3, cy + 1); ctx.lineTo(cx - 1.5, cy); ctx.lineTo(cx, cy + 1); ctx.lineTo(cx + 1.5, cy); ctx.lineTo(cx + 3, cy + 1);
+ ctx.stroke();
+ ctx.fillStyle = "#ffe0f0";
+ ctx.fillRect(Math.round(cx - 2), Math.round(cy - 3), 1, 1);
+ ctx.fillRect(Math.round(cx + 1), Math.round(cy - 3), 1, 1);
+ return;
+ }
+ }
+ // The visor with two pupils looking where it goes (all that is left of an eaten bug).
+ ctx.fillStyle = "#0b0f22";
+ ctx.fillRect(Math.round(cx - 3.5), Math.round(cy - 2.5), 7, 3);
+ ctx.fillStyle = "#e8fbff";
+ ctx.fillRect(Math.round(cx - 3 + lookX), Math.round(cy - 2 + lookY * 0.5), 2, 2);
+ ctx.fillRect(Math.round(cx + 1 + lookX), Math.round(cy - 2 + lookY * 0.5), 2, 2);
+}
+
+export function drawMaze(ctx: CanvasRenderingContext2D, s: MazeState, info: RetroDrawInfo): void {
+ ctx.fillStyle = "#03040c";
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
+
+ // Walls: dark fill, neon outline. A cleared level makes them glow up and down smoothly.
+ ctx.fillStyle = "#0a0f3a";
+ for (let y = 0; y < MAZE_H; y += 1) {
+ for (let x = 0; x < MAZE_W; x += 1) {
+ if (MAZE[y][x] === "#") ctx.fillRect(x * TILE, OY + y * TILE, TILE, TILE);
+ }
+ }
+ let wall = "#3b6bff";
+ if (s.phase === "clear") {
+ const k = info.reduced ? 0.6 : 0.5 + 0.5 * Math.sin((CLEAR_TIME - s.phaseTimer) * Math.PI * 3);
+ wall = `rgb(${Math.round(59 + 196 * k)},${Math.round(107 + 148 * k)},255)`;
+ }
+ ctx.strokeStyle = wall;
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ for (let i = 0; i < WALL_SEGMENTS.length; i += 4) {
+ ctx.moveTo(WALL_SEGMENTS[i] + 0.5, WALL_SEGMENTS[i + 1] + 0.5);
+ ctx.lineTo(WALL_SEGMENTS[i + 2] + 0.5, WALL_SEGMENTS[i + 3] + 0.5);
+ }
+ ctx.stroke();
+ // The pen door.
+ ctx.fillStyle = "#ff7ad9";
+ ctx.fillRect(EXIT_X * TILE, OY + (EXIT_Y + 1) * TILE + 4, TILE, 2);
+
+ // Dots and orbs.
+ ctx.fillStyle = "#ffe6b0";
+ const orbR = info.reduced ? 3.5 : 3 + Math.sin(info.time * 6) * 0.8;
+ for (let y = 0; y < MAZE_H; y += 1) {
+ for (let x = 0; x < MAZE_W; x += 1) {
+ const v = s.dots[y * MAZE_W + x];
+ if (v === 1) ctx.fillRect(x * TILE + 4, OY + y * TILE + 4, 2, 2);
+ else if (v === 2) {
+ ctx.beginPath();
+ ctx.arc(tileCx(x), tileCy(y), orbR, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ }
+ }
+
+ if (s.bonusTimer > 0) drawGem(ctx, tileCx(BONUS_X), tileCy(BONUS_Y), 4, bonusColor(s.level));
+
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(0, OY, WIDTH, MAZE_H * TILE);
+ ctx.clip();
+ const p = s.player;
+ if (s.phase === "dying") {
+ // The chomper folds open and vanishes.
+ const k = 1 - Math.max(0, s.phaseTimer - DYING_TIME * 0.25) / (DYING_TIME * 0.75);
+ if (s.phaseTimer > DYING_TIME * 0.25) drawChomper(ctx, tileCx(p.x), tileCy(p.y), 4.5, UP, 0.2 + k * (Math.PI - 0.2));
+ } else if (!s.over) {
+ const chew = info.idle || info.reduced ? (info.idle && !info.reduced ? info.time * 2 : 0.25) : p.chew;
+ const open = 0.08 + Math.abs(Math.sin(chew * Math.PI)) * 0.6;
+ drawChomper(ctx, tileCx(p.x), tileCy(p.y), 4.5, p.dir >= 0 ? p.dir : p.want >= 0 ? p.want : LEFT, open);
+ }
+ if (s.phase !== "dying" && s.phase !== "clear") for (const b of s.bugs) drawBug(ctx, s, b, info);
+ ctx.restore();
+
+ drawSparks(ctx, s.sparks);
+ for (const pop of s.popups) {
+ if (pop.time <= 0) continue;
+ ctx.globalAlpha = Math.min(1, pop.time * 2);
+ drawDigits(ctx, pop.value, tileCx(pop.x), tileCy(pop.y) - 4 - (info.reduced ? 0 : (1 - pop.time) * 6), 8, "#3de8ff", "center", 600);
+ }
+ ctx.globalAlpha = 1;
+
+ // HUD: score top left, level gem + number top right, lives bottom left, bonus gems bottom right.
+ drawDigits(ctx, s.score, 4, 2, 10, "#ffffff", "left", 600);
+ drawGem(ctx, WIDTH - 24, 7, 4, bonusColor(s.level));
+ drawDigits(ctx, s.level, WIDTH - 4, 2, 10, "#ffd23f", "right");
+ const spare = s.phase === "dying" ? s.lives : s.lives - 1;
+ for (let i = 0; i < Math.max(0, spare); i += 1) drawChomper(ctx, 8 + i * 12, HEIGHT - 7, 4, LEFT, 0.5);
+ for (let i = 0; i < Math.min(s.level, 6); i += 1) drawGem(ctx, WIDTH - 8 - i * 11, HEIGHT - 7, 3.5, bonusColor(s.level - i));
+ // The ready pause before a round: a soft ring around the chomper (steady when motion is reduced).
+ if (s.phase === "ready" && !info.idle) {
+ ctx.strokeStyle = "rgba(255,210,63,0.6)";
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ const r = info.reduced ? 8 : 7 + (s.phaseTimer % 0.8) * 4;
+ ctx.arc(tileCx(p.x), tileCy(p.y), r, 0, Math.PI * 2);
+ ctx.stroke();
+ }
+}
+
+const mazeMuncher: RetroGame<MazeState> = {
+ id: "maze-muncher",
+ width: WIDTH,
+ height: HEIGHT,
+ create: () => createMaze(),
+ step: (state, input, dt, random) => stepMaze(state, input, dt, random),
+ draw: (ctx, state, info) => drawMaze(ctx, state, info),
+ status: (state): RetroStatus => ({ score: state.score, lives: state.lives, level: state.level, over: state.over }),
+};
+
+export default mazeMuncher;
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/neonSnake.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/neonSnake.test.ts
new file mode 100644
index 0000000000..3bdb3622e5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/neonSnake.test.ts
@@ -0,0 +1,251 @@
+import { describe, expect, it } from "vitest";
+import { RETRO_STEP, idleInput, seededRandom, type RetroButtons, type RetroInput } from "../retroGame";
+import { recordingContext } from "./games1Kit";
+import neonSnake, {
+ BONUS_EVERY, BONUS_S, COLS, DOWN, EMPTY, FOODS_PER_LEVEL, LEFT, MAX_QUEUED_TURNS, RIGHT, ROWS, SNAKE, START_LENGTH, UP, WALL,
+ cellOf, moveInterval, queueTurn, type SnakeState,
+} from "./neonSnake";
+
+const random = seededRandom(7);
+const fresh = (seed = 7): SnakeState => neonSnake.create(seededRandom(seed));
+const press = (...keys: (keyof RetroButtons)[]): RetroInput => {
+ const input = idleInput();
+ for (const k of keys) { input[k] = true; input.pressed[k] = true; }
+ return input;
+};
+/** Run exactly one movement tick (the clock is due, no time passes). */
+const tick = (s: SnakeState, input: RetroInput = idleInput()): void => {
+ s.clock = moveInterval(s);
+ neonSnake.step(s, input, 0, random);
+};
+const headXY = (s: SnakeState): [number, number] => [s.body[0] % COLS, Math.floor(s.body[0] / COLS)];
+/** Replace the snake with the given cells (head first), keeping obstacles. */
+const setBody = (s: SnakeState, cells: [number, number][], dir: number): void => {
+ for (const c of s.body) s.grid[c] = EMPTY;
+ s.body = cells.map(([x, y]) => cellOf(x, y));
+ for (const c of s.body) s.grid[c] = SNAKE;
+ s.dir = dir;
+ s.queue = [];
+ s.grow = 0;
+};
+/** Put the food somewhere far from the action. */
+const parkFood = (s: SnakeState): void => { s.food = cellOf(0, ROWS - 1); };
+
+describe("neon snake", () => {
+ it("starts as a short snake heading right with food on a free cell", () => {
+ const s = fresh();
+ expect(s.body).toHaveLength(START_LENGTH);
+ expect(s.dir).toBe(RIGHT);
+ expect(s.food).toBeGreaterThanOrEqual(0);
+ expect(s.grid[s.food]).toBe(EMPTY);
+ expect(neonSnake.status(s)).toEqual({ score: 0, level: 1, over: false, won: false });
+ expect(neonSnake.width).toBe(320);
+ expect(neonSnake.height).toBe(240);
+ });
+
+ it("is reproducible from the same seed", () => {
+ expect(fresh(3).food).toBe(fresh(3).food);
+ });
+
+ it("moves one cell per tick at the tick rate", () => {
+ const s = fresh();
+ parkFood(s);
+ const [x0] = headXY(s);
+ for (let t = 0; t < 1; t += RETRO_STEP) neonSnake.step(s, idleInput(), RETRO_STEP, random);
+ const [x1] = headXY(s);
+ expect(x1 - x0).toBeGreaterThanOrEqual(6);
+ expect(x1 - x0).toBeLessThanOrEqual(8);
+ });
+
+ it("ignores a turn straight back into its neck", () => {
+ const s = fresh();
+ parkFood(s);
+ const [x0, y0] = headXY(s);
+ tick(s, press("left"));
+ expect(s.dir).toBe(RIGHT);
+ expect(headXY(s)).toEqual([x0 + 1, y0]);
+ });
+
+ it("buffers two quick turns between ticks and drops a third", () => {
+ const s = fresh();
+ parkFood(s);
+ const [x0, y0] = headXY(s);
+ neonSnake.step(s, press("up"), 0, random);
+ neonSnake.step(s, press("left"), 0, random);
+ neonSnake.step(s, press("down"), 0, random);
+ expect(s.queue).toEqual([UP, LEFT]);
+ expect(s.queue.length).toBe(MAX_QUEUED_TURNS);
+ tick(s);
+ expect(headXY(s)).toEqual([x0, y0 - 1]);
+ tick(s);
+ expect(s.dir).toBe(LEFT);
+ expect(headXY(s)).toEqual([x0 - 1, y0 - 1]);
+ });
+
+ it("judges reversal against the last queued turn, not the current heading", () => {
+ const s = fresh();
+ queueTurn(s, UP);
+ queueTurn(s, DOWN); // reverses the queued up
+ expect(s.queue).toEqual([UP]);
+ queueTurn(s, LEFT); // left is fine after up, though it reverses the current right
+ expect(s.queue).toEqual([UP, LEFT]);
+ });
+
+ it("eats food, scores and grows by one", () => {
+ const s = fresh();
+ const [x, y] = headXY(s);
+ s.food = cellOf(x + 1, y);
+ tick(s);
+ expect(s.score).toBe(10);
+ expect(s.eaten).toBe(1);
+ expect(s.food).not.toBe(cellOf(x + 1, y));
+ parkFood(s);
+ tick(s);
+ expect(s.body).toHaveLength(START_LENGTH + 1);
+ });
+
+ it("ends the run at the wall", () => {
+ const s = fresh();
+ parkFood(s);
+ for (let i = 0; i < COLS && !s.over; i += 1) tick(s);
+ expect(neonSnake.status(s).over).toBe(true);
+ const body = [...s.body];
+ tick(s, press("up"));
+ expect(s.body).toEqual(body);
+ });
+
+ it("ends the run when it bites itself", () => {
+ const s = fresh();
+ parkFood(s);
+ setBody(s, [[5, 5], [6, 5], [6, 6], [5, 6], [4, 6], [3, 6]], LEFT);
+ tick(s, press("down"));
+ expect(s.over).toBe(true);
+ });
+
+ it("may follow its own tail into the cell the tail is leaving", () => {
+ const s = fresh();
+ parkFood(s);
+ setBody(s, [[5, 5], [6, 5], [6, 6], [5, 6]], LEFT);
+ tick(s, press("down"));
+ expect(s.over).toBe(false);
+ expect(headXY(s)).toEqual([5, 6]);
+ });
+
+ it("crashes into an obstacle", () => {
+ const s = fresh();
+ parkFood(s);
+ const [x, y] = headXY(s);
+ s.grid[cellOf(x + 1, y)] = WALL;
+ tick(s);
+ expect(s.over).toBe(true);
+ });
+
+ it("levels up every few foods and drops obstacles clear of the snake's path", () => {
+ const s = fresh();
+ for (let i = 0; i < FOODS_PER_LEVEL; i += 1) {
+ const [x, y] = headXY(s);
+ s.bonus = -1;
+ s.food = cellOf(x + 1, y);
+ tick(s);
+ }
+ expect(s.level).toBe(2);
+ expect(s.score).toBe(10 * FOODS_PER_LEVEL);
+ expect(s.obstacles).toHaveLength(4);
+ const [hx, hy] = headXY(s);
+ for (const c of s.obstacles) {
+ const ox = c % COLS, oy = Math.floor(c / COLS);
+ expect(s.body).not.toContain(c);
+ expect(Math.abs(ox - hx) + Math.abs(oy - hy)).toBeGreaterThan(4);
+ expect(oy === hy && ox > hx && ox - hx <= 8).toBe(false);
+ expect(s.grid[c]).toBe(WALL);
+ }
+ // Food scores more on a higher level.
+ const [x, y] = headXY(s);
+ s.food = cellOf(x + 1, y);
+ tick(s);
+ expect(s.score).toBe(10 * FOODS_PER_LEVEL + 20);
+ });
+
+ it("speeds up with length and level but never past the floor", () => {
+ const s = fresh();
+ const base = moveInterval(s);
+ s.body.push(0, 1, 2, 3, 4);
+ expect(moveInterval(s)).toBeLessThan(base);
+ s.level = 3;
+ const higher = moveInterval(s);
+ expect(higher).toBeLessThan(base);
+ s.level = 99;
+ expect(moveInterval(s)).toBe(0.05);
+ });
+
+ it("offers a timed bonus fruit worth more the sooner it is eaten", () => {
+ const s = fresh();
+ for (let i = 0; i < BONUS_EVERY; i += 1) {
+ const [x, y] = headXY(s);
+ s.food = cellOf(x + 1, y);
+ tick(s);
+ }
+ expect(s.bonus).toBeGreaterThanOrEqual(0);
+ expect(s.bonusTime).toBe(BONUS_S);
+ const scoreBefore = s.score;
+ const [x, y] = headXY(s);
+ s.bonus = cellOf(x + 1, y);
+ parkFood(s);
+ tick(s);
+ expect(s.score - scoreBefore).toBe(50 + BONUS_S * 10);
+ expect(s.bonus).toBe(-1);
+ });
+
+ it("lets an uneaten bonus fruit expire", () => {
+ const s = fresh();
+ s.bonus = cellOf(20, 3);
+ s.bonusTime = BONUS_S;
+ parkFood(s);
+ setBody(s, [[3, 20], [2, 20], [1, 20], [0, 20]], UP);
+ for (let t = 0; t < BONUS_S + 0.1; t += RETRO_STEP) {
+ s.clock = 0; // hold still
+ neonSnake.step(s, idleInput(), RETRO_STEP, random);
+ }
+ expect(s.bonus).toBe(-1);
+ });
+
+ it("keeps the grid and the body in sync through a long random game", () => {
+ const rnd = seededRandom(11);
+ const s = neonSnake.create(rnd);
+ const keys: (keyof RetroButtons)[] = ["up", "down", "left", "right"];
+ for (let i = 0; i < 4000 && !s.over; i += 1) {
+ const input = rnd() < 0.08 ? press(keys[Math.floor(rnd() * 4)]) : idleInput();
+ neonSnake.step(s, input, RETRO_STEP, rnd);
+ let snakeCells = 0;
+ for (const v of s.grid) if (v === SNAKE) snakeCells += 1;
+ expect(snakeCells).toBe(s.body.length);
+ }
+ });
+
+ it("draws every state without throwing, words or broken numbers", () => {
+ const s = fresh();
+ s.bonus = cellOf(20, 3);
+ s.bonusTime = 1;
+ s.obstacles.push(cellOf(25, 20));
+ for (const info of [
+ { time: 0, reduced: false, idle: true },
+ { time: 1.3, reduced: false, idle: false },
+ { time: 2.1, reduced: true, idle: false },
+ ]) {
+ const rec = recordingContext();
+ neonSnake.draw(rec.ctx, s, info);
+ expect(rec.calls.length).toBeGreaterThan(50);
+ expect(rec.nonFinite).toBe(0);
+ expect(rec.depth).toBe(0);
+ expect(rec.ctx.globalAlpha).toBe(1);
+ for (const text of rec.texts) expect(text).not.toMatch(/[a-z]/i);
+ }
+ tick(s, press("up"));
+ s.grid[s.body[0] - COLS] = WALL;
+ tick(s);
+ expect(s.over).toBe(true);
+ const rec = recordingContext();
+ neonSnake.draw(rec.ctx, s, { time: 3, reduced: false, idle: false });
+ expect(rec.nonFinite).toBe(0);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/neonSnake.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/neonSnake.ts
new file mode 100644
index 0000000000..23a5e0f4c8
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/neonSnake.ts
@@ -0,0 +1,404 @@
+/**
+ * "Neon Snake": steer a glowing snake around a neon grid, eat to grow, and
+ * never run into a wall, an obstacle or yourself.
+ *
+ * The snake moves one cell per tick; the tick gets shorter as the snake gets
+ * longer and the level rises. Turns are buffered (up to two), so a quick
+ * up-then-left between two ticks is not lost, and a turn straight back into
+ * the neck is ignored. Every few foods a timed golden bonus fruit appears, and
+ * every FOODS_PER_LEVEL foods the level rises and a few obstacle blocks drop
+ * in — never on the snake and never in the cells just ahead of its head.
+ */
+import type { RetroGame, RetroInput } from "../retroGame";
+import { clamp, drawScanlines, drawSparks, emitSparks, sparkPool, stepSparks, type SparkPool } from "./games1Kit";
+
+export const COLS = 32;
+export const ROWS = 24;
+export const CELL = 10;
+const WIDTH = COLS * CELL;
+const HEIGHT = ROWS * CELL;
+
+/** Directions: 0 right, 1 down, 2 left, 3 up; opposite = (d + 2) % 4. */
+export const RIGHT = 0;
+export const DOWN = 1;
+export const LEFT = 2;
+export const UP = 3;
+const DIR_X = [1, 0, -1, 0];
+const DIR_Y = [0, 1, 0, -1];
+
+export const START_LENGTH = 4;
+/** How many turns can wait for the next tick. */
+export const MAX_QUEUED_TURNS = 2;
+export const FOODS_PER_LEVEL = 5;
+/** A bonus fruit appears after every BONUS_EVERY-th food. */
+export const BONUS_EVERY = 4;
+/** Seconds a bonus fruit stays before it fades. */
+export const BONUS_S = 6;
+/** Obstacles never land this close (Manhattan cells) to the head, nor in the line ahead of it. */
+const SAFE_RADIUS = 4;
+const SAFE_AHEAD = 8;
+const MAX_OBSTACLES = 48;
+
+export const EMPTY = 0;
+export const SNAKE = 1;
+export const WALL = 2;
+
+export interface SnakeState {
+ /** Cell indices (y * COLS + x), head first. */
+ body: number[];
+ /** What occupies every cell (EMPTY / SNAKE / WALL), for O(1) collisions. */
+ grid: Uint8Array;
+ dir: number;
+ /** Turns waiting for the next tick, oldest first. */
+ queue: number[];
+ /** Cells still to grow: the tail stays put for that many ticks. */
+ grow: number;
+ /** Seconds since the last tick. */
+ clock: number;
+ food: number;
+ /** The bonus fruit's cell, or -1. */
+ bonus: number;
+ bonusTime: number;
+ obstacles: number[];
+ eaten: number;
+ score: number;
+ level: number;
+ over: boolean;
+ /** The board is full: nowhere left to put food. */
+ won: boolean;
+ /** Game time in seconds, for the fruit's pulse. */
+ time: number;
+ /** Screen flash 0..1 (level up, crash) and its colour; drawn only without reduced motion. */
+ flash: number;
+ flashColor: string;
+ shake: number;
+ sparks: SparkPool;
+}
+
+/** Seconds per tick: 0.13 s at the start, faster with every cell of length and every level, never under 0.05 s. */
+export function moveInterval(s: SnakeState): number {
+ return Math.max(0.05, 0.13 - (s.body.length - START_LENGTH) * 0.002 - (s.level - 1) * 0.004);
+}
+
+export function cellOf(x: number, y: number): number {
+ return y * COLS + x;
+}
+
+function createSnake(random: () => number): SnakeState {
+ const s: SnakeState = {
+ body: [], grid: new Uint8Array(COLS * ROWS), dir: RIGHT, queue: [], grow: 0, clock: 0,
+ food: -1, bonus: -1, bonusTime: 0, obstacles: [], eaten: 0, score: 0, level: 1,
+ over: false, won: false, time: 0, flash: 0, flashColor: "#5dff9c", shake: 0, sparks: sparkPool(96),
+ };
+ const y = Math.floor(ROWS / 2);
+ for (let i = 0; i < START_LENGTH; i += 1) {
+ const c = cellOf(8 - i, y);
+ s.body.push(c);
+ s.grid[c] = SNAKE;
+ }
+ s.food = freeCell(s, random, false);
+ return s;
+}
+
+/** True when the cell is empty and free of fruit; with `guard`, also clear of the snake's path. */
+function isFree(s: SnakeState, cell: number, guard: boolean): boolean {
+ if (s.grid[cell] !== EMPTY || cell === s.food || cell === s.bonus) return false;
+ if (!guard) return true;
+ const head = s.body[0];
+ const hx = head % COLS, hy = Math.floor(head / COLS);
+ const x = cell % COLS, y = Math.floor(cell / COLS);
+ if (Math.abs(x - hx) + Math.abs(y - hy) <= SAFE_RADIUS) return false;
+ // The straight line ahead of the head, for the current and every queued direction.
+ for (let q = -1; q < s.queue.length; q += 1) {
+ const d = q < 0 ? s.dir : s.queue[q];
+ const dx = x - hx, dy = y - hy;
+ for (let k = 1; k <= SAFE_AHEAD; k += 1) if (dx === DIR_X[d] * k && dy === DIR_Y[d] * k) return false;
+ }
+ return true;
+}
+
+/** A random free cell, or -1 when there is none. Tries random picks first, then scans. */
+function freeCell(s: SnakeState, random: () => number, guard: boolean): number {
+ const total = COLS * ROWS;
+ for (let i = 0; i < 64; i += 1) {
+ const c = Math.floor(random() * total);
+ if (isFree(s, c, guard)) return c;
+ }
+ const start = Math.floor(random() * total);
+ for (let i = 0; i < total; i += 1) {
+ const c = (start + i) % total;
+ if (isFree(s, c, guard)) return c;
+ }
+ return -1;
+}
+
+/** Queue a turn unless it repeats the last direction, reverses into the neck, or the buffer is full. */
+export function queueTurn(s: SnakeState, d: number): void {
+ const last = s.queue.length > 0 ? s.queue[s.queue.length - 1] : s.dir;
+ if (d === last || d === (last + 2) % 4 || s.queue.length >= MAX_QUEUED_TURNS) return;
+ s.queue.push(d);
+}
+
+function centre(cell: number): [number, number] {
+ return [(cell % COLS) * CELL + CELL / 2, Math.floor(cell / COLS) * CELL + CELL / 2];
+}
+
+function crash(s: SnakeState, random: () => number): void {
+ s.over = true;
+ s.flash = 1;
+ s.flashColor = "#ff3d5a";
+ s.shake = 0.35;
+ for (let i = 0; i < s.body.length; i += 3) {
+ const cx = (s.body[i] % COLS) * CELL + CELL / 2, cy = Math.floor(s.body[i] / COLS) * CELL + CELL / 2;
+ emitSparks(s.sparks, cx, cy, 3, 70, i === 0 ? "#ffffff" : "#ff5d7a", random, 0.8, 2);
+ }
+}
+
+function levelUp(s: SnakeState, random: () => number): void {
+ s.level += 1;
+ s.flash = 0.8;
+ s.flashColor = "#5dff9c";
+ const add = Math.min(2 + s.level, MAX_OBSTACLES - s.obstacles.length);
+ for (let i = 0; i < add; i += 1) {
+ const c = freeCell(s, random, true);
+ if (c < 0) break;
+ s.grid[c] = WALL;
+ s.obstacles.push(c);
+ const x = (c % COLS) * CELL + CELL / 2, y = Math.floor(c / COLS) * CELL + CELL / 2;
+ emitSparks(s.sparks, x, y, 4, 40, "#ff4fd8", random, 0.5, 2);
+ }
+}
+
+function eatFood(s: SnakeState, random: () => number): void {
+ const [x, y] = centre(s.food);
+ emitSparks(s.sparks, x, y, 10, 90, "#ff4d6d", random, 0.5, 2);
+ s.score += 10 * s.level;
+ s.grow += 1;
+ s.eaten += 1;
+ s.food = -1;
+ if (s.eaten % FOODS_PER_LEVEL === 0) levelUp(s, random);
+ s.food = freeCell(s, random, false);
+ if (s.food < 0) {
+ s.over = true;
+ s.won = true;
+ return;
+ }
+ if (s.eaten % BONUS_EVERY === 0 && s.bonus < 0) {
+ s.bonus = freeCell(s, random, false);
+ s.bonusTime = BONUS_S;
+ }
+}
+
+function eatBonus(s: SnakeState, random: () => number): void {
+ const [x, y] = centre(s.bonus);
+ emitSparks(s.sparks, x, y, 18, 120, "#ffd23f", random, 0.7, 2);
+ // Quicker is richer: up to 60 extra points for a fresh fruit.
+ s.score += (50 + Math.round(s.bonusTime * 10)) * s.level;
+ s.grow += 2;
+ s.bonus = -1;
+ s.bonusTime = 0;
+}
+
+/** One tick: take the next queued turn, move the head one cell, eat or crash. */
+function advance(s: SnakeState, random: () => number): void {
+ const d = s.queue.length > 0 ? (s.queue.shift() as number) : s.dir;
+ s.dir = d;
+ const head = s.body[0];
+ const nx = (head % COLS) + DIR_X[d], ny = Math.floor(head / COLS) + DIR_Y[d];
+ if (nx < 0 || ny < 0 || nx >= COLS || ny >= ROWS) {
+ crash(s, random);
+ return;
+ }
+ const next = cellOf(nx, ny);
+ const tail = s.body[s.body.length - 1];
+ const tailLeaves = s.grow === 0;
+ const hit = s.grid[next];
+ // Moving into the cell the tail is leaving this very tick is fine.
+ if (hit === WALL || (hit === SNAKE && !(tailLeaves && next === tail))) {
+ crash(s, random);
+ return;
+ }
+ if (tailLeaves) {
+ s.body.pop();
+ s.grid[tail] = EMPTY;
+ } else {
+ s.grow -= 1;
+ }
+ s.body.unshift(next);
+ s.grid[next] = SNAKE;
+ if (next === s.food) eatFood(s, random);
+ else if (next === s.bonus) eatBonus(s, random);
+}
+
+function stepSnake(s: SnakeState, input: RetroInput, dt: number, random: () => number): void {
+ s.time += dt;
+ s.flash = Math.max(0, s.flash - dt * 2.5);
+ s.shake = Math.max(0, s.shake - dt);
+ stepSparks(s.sparks, dt);
+ if (s.over) return;
+ const p = input.pressed;
+ if (p.up) queueTurn(s, UP);
+ if (p.down) queueTurn(s, DOWN);
+ if (p.left) queueTurn(s, LEFT);
+ if (p.right) queueTurn(s, RIGHT);
+ if (s.bonus >= 0) {
+ s.bonusTime -= dt;
+ if (s.bonusTime <= 0) {
+ const [x, y] = centre(s.bonus);
+ emitSparks(s.sparks, x, y, 6, 30, "#8a6a10", random, 0.4, 2);
+ s.bonus = -1;
+ s.bonusTime = 0;
+ }
+ }
+ s.clock += dt;
+ const every = moveInterval(s);
+ if (s.clock >= every) {
+ s.clock -= every;
+ advance(s, random);
+ }
+}
+
+// ---- drawing -------------------------------------------------------------
+
+const SHADES = 16;
+/** Body colours from head to tail, built once so a frame allocates no strings. */
+const LIVE_SHADES: string[] = [];
+const DEAD_SHADES: string[] = [];
+for (let i = 0; i < SHADES; i += 1) {
+ const t = i / (SHADES - 1);
+ const mix = (a: number, b: number) => Math.round(a + (b - a) * t);
+ LIVE_SHADES.push(`rgb(${mix(93, 16)},${mix(255, 150)},${mix(156, 140)})`);
+ DEAD_SHADES.push(`rgb(${mix(255, 90)},${mix(93, 30)},${mix(122, 50)})`);
+}
+
+function drawGrid(ctx: CanvasRenderingContext2D): void {
+ ctx.fillStyle = "#04070c";
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
+ ctx.strokeStyle = "rgba(34,224,122,0.08)";
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ for (let x = CELL; x < WIDTH; x += CELL) { ctx.moveTo(x + 0.5, 0); ctx.lineTo(x + 0.5, HEIGHT); }
+ for (let y = CELL; y < HEIGHT; y += CELL) { ctx.moveTo(0, y + 0.5); ctx.lineTo(WIDTH, y + 0.5); }
+ ctx.stroke();
+ ctx.strokeStyle = "rgba(93,255,156,0.45)";
+ ctx.strokeRect(0.5, 0.5, WIDTH - 1, HEIGHT - 1);
+}
+
+function drawObstacles(ctx: CanvasRenderingContext2D, s: SnakeState): void {
+ for (const c of s.obstacles) {
+ const x = (c % COLS) * CELL, y = Math.floor(c / COLS) * CELL;
+ ctx.fillStyle = "#7a1060";
+ ctx.fillRect(x, y, CELL, CELL);
+ ctx.fillStyle = "#ff4fd8";
+ ctx.fillRect(x + 1, y + 1, CELL - 2, CELL - 2);
+ ctx.fillStyle = "#3a0630";
+ ctx.fillRect(x + 3, y + 3, CELL - 6, CELL - 6);
+ ctx.fillStyle = "#ffb3f0";
+ ctx.fillRect(x + 1, y + 1, CELL - 2, 1);
+ }
+}
+
+function drawFruit(ctx: CanvasRenderingContext2D, s: SnakeState, info: { time: number; reduced: boolean }): void {
+ if (s.food >= 0) {
+ const x = (s.food % COLS) * CELL, y = Math.floor(s.food / COLS) * CELL;
+ const pulse = info.reduced ? 0 : Math.round(Math.sin(info.time * 6) + 1);
+ ctx.globalAlpha = 0.25;
+ ctx.fillStyle = "#ff4d6d";
+ ctx.fillRect(x - 1 - pulse, y - 1 - pulse, CELL + 2 + pulse * 2, CELL + 2 + pulse * 2);
+ ctx.globalAlpha = 1;
+ ctx.fillRect(x + 2, y + 3, CELL - 4, CELL - 4);
+ ctx.fillRect(x + 3, y + 2, CELL - 6, CELL - 2);
+ ctx.fillStyle = "#ffc2cc";
+ ctx.fillRect(x + 3, y + 4, 2, 2);
+ ctx.fillStyle = "#5dff9c";
+ ctx.fillRect(x + 5, y, 2, 2);
+ }
+ if (s.bonus >= 0) {
+ const [cx, cy] = centre(s.bonus);
+ // Blinks for its last second and a half; fades instead when motion is reduced.
+ const ending = s.bonusTime < 1.5;
+ if (ending && !info.reduced && Math.floor(s.time * 8) % 2 === 1) return;
+ ctx.globalAlpha = ending && info.reduced ? 0.5 : 1;
+ ctx.fillStyle = "#ffd23f";
+ ctx.beginPath();
+ ctx.moveTo(cx, cy - 5); ctx.lineTo(cx + 5, cy); ctx.lineTo(cx, cy + 5); ctx.lineTo(cx - 5, cy);
+ ctx.closePath();
+ ctx.fill();
+ ctx.fillStyle = "#fff6c8";
+ ctx.fillRect(cx - 1, cy - 3, 2, 2);
+ ctx.strokeStyle = "#ffd23f";
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.arc(cx, cy, 8, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * clamp(s.bonusTime / BONUS_S, 0, 1));
+ ctx.stroke();
+ ctx.globalAlpha = 1;
+ }
+}
+
+function drawSnake(ctx: CanvasRenderingContext2D, s: SnakeState): void {
+ const shades = s.over ? DEAD_SHADES : LIVE_SHADES;
+ const n = s.body.length;
+ for (let i = n - 1; i >= 0; i -= 1) {
+ const c = s.body[i];
+ const x = (c % COLS) * CELL, y = Math.floor(c / COLS) * CELL;
+ const shade = shades[Math.min(SHADES - 1, Math.floor((i / Math.max(1, n - 1)) * (SHADES - 1)))];
+ ctx.fillStyle = shade;
+ ctx.fillRect(x + 1, y + 1, CELL - 2, CELL - 2);
+ // Bridge to the next segment, so the body reads as one tube.
+ if (i + 1 < n) {
+ const nc = s.body[i + 1];
+ const dx = (nc % COLS) - (c % COLS), dy = Math.floor(nc / COLS) - Math.floor(c / COLS);
+ if (Math.abs(dx) + Math.abs(dy) === 1) ctx.fillRect(x + 1 + dx * 2, y + 1 + dy * 2, CELL - 2, CELL - 2);
+ }
+ }
+ // The head: a soft halo and two eyes looking where it goes.
+ const head = s.body[0];
+ const hx = (head % COLS) * CELL, hy = Math.floor(head / COLS) * CELL;
+ ctx.globalAlpha = 0.3;
+ ctx.fillStyle = shades[0];
+ ctx.fillRect(hx - 2, hy - 2, CELL + 4, CELL + 4);
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = s.over ? "#ffffff" : "#d9ffe9";
+ ctx.fillRect(hx + 1, hy + 1, CELL - 2, CELL - 2);
+ ctx.fillStyle = shades[0];
+ ctx.fillRect(hx + 2, hy + 2, CELL - 4, CELL - 4);
+ ctx.fillStyle = "#04070c";
+ const d = s.dir;
+ const fx = DIR_X[d], fy = DIR_Y[d];
+ const ex = hx + CELL / 2 + fx * 2 - 1, ey = hy + CELL / 2 + fy * 2 - 1;
+ ctx.fillRect(ex + fy * 2, ey + fx * 2, 2, 2);
+ ctx.fillRect(ex - fy * 2, ey - fx * 2, 2, 2);
+}
+
+function drawSnakeGame(ctx: CanvasRenderingContext2D, s: SnakeState, info: { time: number; reduced: boolean; idle: boolean }): void {
+ ctx.save();
+ if (!info.reduced && s.shake > 0) {
+ const m = s.shake * 8;
+ ctx.translate(Math.round(Math.sin(s.time * 90) * m), Math.round(Math.cos(s.time * 70) * m));
+ }
+ drawGrid(ctx);
+ drawObstacles(ctx, s);
+ drawFruit(ctx, s, info);
+ drawSnake(ctx, s);
+ drawSparks(ctx, s.sparks);
+ ctx.restore();
+ if (!info.reduced && s.flash > 0) {
+ ctx.globalAlpha = s.flash * 0.22;
+ ctx.fillStyle = s.flashColor;
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
+ ctx.globalAlpha = 1;
+ }
+ drawScanlines(ctx, WIDTH, HEIGHT, 0.1);
+}
+
+const neonSnake: RetroGame<SnakeState> = {
+ id: "neon-snake",
+ width: WIDTH,
+ height: HEIGHT,
+ create: createSnake,
+ step: stepSnake,
+ draw: drawSnakeGame,
+ status: (s) => ({ score: s.score, level: s.level, over: s.over, won: s.won }),
+};
+
+export default neonSnake;
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/paddleDuel.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/paddleDuel.test.ts
new file mode 100644
index 0000000000..0e0a62adef
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/paddleDuel.test.ts
@@ -0,0 +1,225 @@
+import { describe, expect, it } from "vitest";
+import { RETRO_STEP, idleInput, seededRandom, type RetroInput } from "../retroGame";
+import { recordingContext } from "./games1Kit";
+import paddleDuel, {
+ BOTTOM, CPU_X, HEIGHT, HIT_SPEEDUP, MATCH_PAUSE, MAX_BALL_SPEED, PADDLE_H, PADDLE_W, PLAYER_SPEED, PLAYER_X, SERVE_DELAY,
+ SERVE_SPEED, TOP, WIDTH, WIN_POINTS, cpuSkill, predictY, serve, type DuelState,
+} from "./paddleDuel";
+
+const random = seededRandom(3);
+const fresh = (): DuelState => paddleDuel.create(seededRandom(3));
+const step = (s: DuelState, input: RetroInput = idleInput(), rnd: () => number = random): void =>
+ paddleDuel.step(s, input, RETRO_STEP, rnd);
+const run = (s: DuelState, input: RetroInput, seconds: number): void => {
+ for (let t = 0; t < seconds; t += RETRO_STEP) step(s, input);
+};
+const pressA = (): RetroInput => {
+ const input = idleInput();
+ input.a = true;
+ input.pressed.a = true;
+ return input;
+};
+/** A ball in flight at (x, y) with velocity (vx, vy). */
+const rally = (s: DuelState, x: number, y: number, vx: number, vy: number): void => {
+ Object.assign(s, { serving: false, serveTimer: 0, ballX: x, ballY: y, vx, vy, spin: 0, speed: Math.hypot(vx, vy) });
+};
+
+/** Where the ball will reach the player's face, folding wall bounces (spin ignored). */
+function predictPlayerY(s: DuelState): number {
+ const t = (s.ballX - (PLAYER_X + PADDLE_W)) / -s.vx;
+ const lo = TOP + 2.5, span = BOTTOM - 2.5 - lo, period = span * 2;
+ let y = ((s.ballY + s.vy * t - lo) % period + period) % period;
+ if (y > span) y = period - y;
+ return y + lo;
+}
+
+/** A good human: meets the ball near a paddle end, angling it away from the CPU. */
+function botInput(s: DuelState): RetroInput {
+ const input = idleInput();
+ let target = HEIGHT / 2;
+ if (!s.serving && s.vx < 0) {
+ const y = predictPlayerY(s);
+ target = s.cpuY < HEIGHT / 2 ? y - PADDLE_H * 0.38 : y + PADDLE_H * 0.38;
+ }
+ input.up = target < s.playerY - 2;
+ input.down = target > s.playerY + 2;
+ return input;
+}
+
+describe("paddle duel", () => {
+ it("starts serving from the middle with nothing scored", () => {
+ const s = fresh();
+ expect(paddleDuel.status(s)).toEqual({ score: 0, level: 1, over: false, won: false });
+ expect(paddleDuel.pointer).toBe(true);
+ expect(s.serving).toBe(true);
+ expect([s.ballX, s.ballY]).toEqual([WIDTH / 2, HEIGHT / 2]);
+ });
+
+ it("serves by itself after a short pause, or at once with A", () => {
+ const s = fresh();
+ run(s, idleInput(), SERVE_DELAY - 0.2);
+ expect(s.serving).toBe(true);
+ run(s, idleInput(), 0.3);
+ expect(s.serving).toBe(false);
+ expect(s.vx).toBeGreaterThan(0);
+ expect(s.speed).toBe(SERVE_SPEED);
+
+ const quick = fresh();
+ step(quick, pressA());
+ expect(quick.serving).toBe(false);
+ });
+
+ it("moves the player's paddle with the keys and the pointer, inside the court", () => {
+ const s = fresh();
+ run(s, { ...idleInput(), up: true }, 0.1);
+ expect(s.playerY).toBeCloseTo(HEIGHT / 2 - PLAYER_SPEED * 0.1, -1);
+ run(s, { ...idleInput(), up: true }, 3);
+ expect(s.playerY).toBe(TOP + PADDLE_H / 2);
+ const pointed = idleInput();
+ pointed.pointer = { x: 50, y: 180, down: false, clicked: false };
+ run(s, pointed, 1);
+ expect(s.playerY).toBeCloseTo(180);
+ run(s, { ...pointed, up: true }, 0.2);
+ expect(s.playerY).toBeLessThan(170);
+ });
+
+ it("returns the ball at an angle set by the contact point", () => {
+ const centre = fresh();
+ rally(centre, PLAYER_X + 20, centre.playerY, -200, 0);
+ run(centre, idleInput(), 0.1);
+ expect(centre.vx).toBeGreaterThan(0);
+ expect(Math.abs(centre.vy)).toBeLessThan(20);
+
+ const edge = fresh();
+ rally(edge, PLAYER_X + 20, edge.playerY + PADDLE_H / 2 - 1, -200, 0);
+ run(edge, idleInput(), 0.1);
+ expect(edge.vx).toBeGreaterThan(0);
+ expect(edge.vy).toBeGreaterThan(100);
+ expect(edge.rally).toBe(1);
+ expect(edge.speed).toBe(200 + HIT_SPEEDUP);
+ });
+
+ it("puts spin on the ball from a moving paddle, and the ball curves", () => {
+ const s = fresh();
+ rally(s, PLAYER_X + 14, s.playerY, -200, 0);
+ for (let i = 0; i < 6; i += 1) step(s, { ...idleInput(), down: true });
+ expect(s.vx).toBeGreaterThan(0);
+ expect(s.spin).toBeGreaterThan(0.5);
+ const vy = s.vy;
+ run(s, idleInput(), 0.2);
+ expect(s.vy).toBeGreaterThan(vy);
+ });
+
+ it("speeds up with every return but never past the cap", () => {
+ const s = fresh();
+ rally(s, PLAYER_X + 20, s.playerY, -MAX_BALL_SPEED + 2, 0);
+ run(s, idleInput(), 0.1);
+ expect(s.speed).toBe(MAX_BALL_SPEED);
+ });
+
+ it("scores a won point with a rally bonus and serves to the loser", () => {
+ const s = fresh();
+ s.cpuY = TOP + PADDLE_H / 2;
+ rally(s, CPU_X - 10, BOTTOM - 10, 300, 0);
+ s.rally = 4;
+ run(s, idleInput(), 0.3);
+ expect(s.playerPoints).toBe(1);
+ expect(s.score).toBe(100 + 4 * 10);
+ expect(s.serving).toBe(true);
+ expect(s.serveDir).toBe(1);
+
+ rally(s, PLAYER_X + 30, BOTTOM - 10, -300, 0);
+ s.playerY = TOP + PADDLE_H / 2;
+ for (let i = 0; i < 20; i += 1) step(s, { ...idleInput(), up: true });
+ expect(s.cpuPoints).toBe(1);
+ expect(s.serveDir).toBe(-1);
+ });
+
+ it("predicts a ball off the wall", () => {
+ const s = fresh();
+ rally(s, WIDTH / 2, TOP + 20, 200, -200);
+ const y = predictY(s);
+ expect(y).toBeGreaterThan(TOP);
+ expect(y).toBeLessThan(BOTTOM);
+ // Fly it for real up to the CPU's face (or its return) and compare.
+ while (s.vx > 0 && s.ballX + 2.5 < CPU_X) step(s);
+ expect(Math.abs(s.ballY - y)).toBeLessThan(6);
+ });
+
+ it("gets sharper every match without becoming perfect", () => {
+ for (let level = 1; level < 12; level += 1) {
+ const a = cpuSkill(level), b = cpuSkill(level + 1);
+ expect(b.reaction).toBeLessThanOrEqual(a.reaction);
+ expect(b.speed).toBeGreaterThanOrEqual(a.speed);
+ expect(b.error).toBeLessThanOrEqual(a.error);
+ }
+ expect(cpuSkill(2).speed).toBeGreaterThan(cpuSkill(1).speed);
+ expect(cpuSkill(50).reaction).toBeGreaterThan(0);
+ expect(cpuSkill(50).error).toBeGreaterThan(0);
+ expect(cpuSkill(50).speed).toBeLessThan(MAX_BALL_SPEED);
+ });
+
+ it("returns a gentle serve at level one", () => {
+ let returned = 0;
+ for (let seed = 1; seed <= 10; seed += 1) {
+ const rnd = seededRandom(seed);
+ const s = paddleDuel.create(rnd);
+ serve(s, rnd);
+ for (let i = 0; i < 240 && s.vx > 0 && !s.serving; i += 1) step(s, idleInput(), rnd);
+ if (!s.serving && s.vx < 0) returned += 1;
+ }
+ expect(returned).toBeGreaterThanOrEqual(7);
+ });
+
+ it("can be beaten: a good player wins the first match to seven and meets a harder CPU", () => {
+ const rnd = seededRandom(21);
+ const s = paddleDuel.create(rnd);
+ for (let i = 0; i < 60 * 300 && s.level === 1 && !s.over; i += 1) paddleDuel.step(s, botInput(s), RETRO_STEP, rnd);
+ expect(s.over).toBe(false);
+ expect(s.level).toBe(2);
+ expect(s.playerPoints).toBe(WIN_POINTS);
+ expect(s.score).toBeGreaterThanOrEqual(WIN_POINTS * 100 + 1000);
+ // After the break the scores reset for the next match.
+ for (let t = 0; t < MATCH_PAUSE + 0.1; t += RETRO_STEP) paddleDuel.step(s, idleInput(), RETRO_STEP, rnd);
+ expect([s.playerPoints, s.cpuPoints]).toEqual([0, 0]);
+ expect(s.serving).toBe(true);
+ });
+
+ it("ends the run when the CPU takes a match", () => {
+ const rnd = seededRandom(4);
+ const s = paddleDuel.create(rnd);
+ for (let i = 0; i < 60 * 300 && !s.over; i += 1) paddleDuel.step(s, idleInput(), RETRO_STEP, rnd);
+ expect(paddleDuel.status(s)).toMatchObject({ over: true, won: false, level: 1 });
+ expect(s.cpuPoints).toBe(WIN_POINTS);
+ const frozen = s.ballX;
+ step(s, pressA());
+ expect(s.ballX).toBe(frozen);
+ });
+
+ it("draws every state without throwing, words or broken numbers", () => {
+ const s = fresh();
+ const states: [string, () => void][] = [
+ ["serving", () => undefined],
+ ["rally", () => { rally(s, 100, 100, 200, 60); s.spin = 0.6; run(s, idleInput(), 0.1); }],
+ ["flash", () => { s.flash = 1; s.flashSide = -1; s.shake = 0.3; }],
+ ["pause", () => { s.matchPause = 1; s.level = 4; }],
+ ["over", () => { s.matchPause = 0; s.over = true; }],
+ ];
+ for (const [, setup] of states) {
+ setup();
+ for (const info of [
+ { time: 0.5, reduced: false, idle: false },
+ { time: 0.5, reduced: true, idle: false },
+ { time: 0, reduced: false, idle: true },
+ ]) {
+ const rec = recordingContext();
+ paddleDuel.draw(rec.ctx, s, info);
+ expect(rec.calls.length).toBeGreaterThan(30);
+ expect(rec.nonFinite).toBe(0);
+ expect(rec.depth).toBe(0);
+ expect(rec.ctx.globalAlpha).toBe(1);
+ for (const text of rec.texts) expect(text).toMatch(/^\d+$/);
+ }
+ }
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/paddleDuel.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/paddleDuel.ts
new file mode 100644
index 0000000000..47692691dd
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/paddleDuel.ts
@@ -0,0 +1,410 @@
+/**
+ * "Paddle Duel": table tennis on a screen against a CPU opponent.
+ *
+ * You play the left paddle. Where the ball meets the paddle sets its angle,
+ * and a paddle moving at the moment of the hit puts spin on the ball, which
+ * then curves. Every return in a rally makes the ball a little faster. The
+ * CPU is a fair opponent: it reacts late, has a top speed and aims slightly
+ * off, and it gets sharper with every match. First to WIN_POINTS takes the
+ * match and moves on to the next, harder CPU; losing a match ends the run.
+ *
+ * Score: 100 per point won, 10 per return in that rally, 1000 × level per match.
+ */
+import type { RetroGame, RetroInput } from "../retroGame";
+import { retroFont } from "../retroGame";
+import { clamp, drawScanlines, drawSparks, emitSparks, sparkPool, stepSparks, type SparkPool } from "./games1Kit";
+
+export const WIDTH = 320;
+export const HEIGHT = 240;
+/** The inside edges of the top and bottom walls. */
+export const TOP = 8;
+export const BOTTOM = HEIGHT - 8;
+export const PADDLE_W = 6;
+export const PADDLE_H = 34;
+/** Left edge of each paddle. */
+export const PLAYER_X = 14;
+export const CPU_X = WIDTH - 14 - PADDLE_W;
+export const BALL = 5;
+const HALF = BALL / 2;
+export const PLAYER_SPEED = 230;
+/** How fast the paddle chases a pointer (px/s); quicker than the keys, but not a teleport. */
+const POINTER_SPEED = 420;
+export const SERVE_SPEED = 150;
+export const HIT_SPEEDUP = 10;
+export const MAX_BALL_SPEED = 380;
+/** Steepest return, from the horizontal, off the very end of a paddle. */
+const MAX_BOUNCE = 1.0;
+/** Spin curves the ball by this much px/s² at full spin, and fades by half each second. */
+const SPIN_ACCEL = 140;
+/** The ball always keeps this share of its speed horizontal, so a rally never stalls vertically. */
+const MIN_HORIZONTAL = 0.55;
+export const WIN_POINTS = 7;
+export const SERVE_DELAY = 1.1;
+export const MATCH_PAUSE = 2.2;
+/** Positions remembered for the ball's trail. */
+const TRAIL = 6;
+
+export interface CpuSkill {
+ /** Seconds between two looks at the ball; it steers toward the last look in between. */
+ reaction: number;
+ /** Top paddle speed in px/s. */
+ speed: number;
+ /** Largest aiming error in px, re-rolled on every return. */
+ error: number;
+ /** Reads bounces off the walls instead of just following the ball. */
+ predicts: boolean;
+}
+
+/** How good the CPU is in match `level`: slow and sloppy at first, sharp later, never perfect. */
+export function cpuSkill(level: number): CpuSkill {
+ const k = level - 1;
+ return {
+ reaction: Math.max(0.07, 0.22 - 0.025 * k),
+ speed: Math.min(285, 118 + 22 * k),
+ error: Math.max(4, 16 - 2.5 * k),
+ predicts: level >= 3,
+ };
+}
+
+export interface DuelState {
+ /** Paddle centres and their velocity in the last step (for spin). */
+ playerY: number;
+ playerVy: number;
+ cpuY: number;
+ cpuVy: number;
+ cpuTarget: number;
+ cpuThink: number;
+ cpuError: number;
+ ballX: number;
+ ballY: number;
+ vx: number;
+ vy: number;
+ /** -1..1; bends the ball's path up or down. */
+ spin: number;
+ speed: number;
+ serving: boolean;
+ serveTimer: number;
+ /** +1 serves toward the CPU, -1 toward the player. */
+ serveDir: number;
+ /** Returns in the current rally. */
+ rally: number;
+ playerPoints: number;
+ cpuPoints: number;
+ level: number;
+ score: number;
+ over: boolean;
+ /** Seconds left of the break after a won match. */
+ matchPause: number;
+ /** Where the pointer last asked the paddle to go; null when keys are in charge. */
+ pointerTarget: number | null;
+ lastPointerY: number | null;
+ /** Which side just conceded (-1 player, 1 CPU) and how strongly it still flashes. */
+ flashSide: number;
+ flash: number;
+ shake: number;
+ time: number;
+ /** Recent ball positions, x/y pairs in a ring. */
+ trail: Float32Array;
+ trailHead: number;
+ sparks: SparkPool;
+}
+
+function centreBall(s: DuelState): void {
+ s.ballX = WIDTH / 2;
+ s.ballY = HEIGHT / 2;
+ s.vx = 0;
+ s.vy = 0;
+ s.spin = 0;
+ for (let i = 0; i < TRAIL; i += 1) { s.trail[i * 2] = s.ballX; s.trail[i * 2 + 1] = s.ballY; }
+}
+
+function createDuel(): DuelState {
+ const s: DuelState = {
+ playerY: HEIGHT / 2, playerVy: 0, cpuY: HEIGHT / 2, cpuVy: 0, cpuTarget: HEIGHT / 2, cpuThink: 0, cpuError: 0,
+ ballX: WIDTH / 2, ballY: HEIGHT / 2, vx: 0, vy: 0, spin: 0, speed: SERVE_SPEED,
+ serving: true, serveTimer: SERVE_DELAY, serveDir: 1, rally: 0,
+ playerPoints: 0, cpuPoints: 0, level: 1, score: 0, over: false, matchPause: 0,
+ pointerTarget: null, lastPointerY: null, flashSide: 0, flash: 0, shake: 0, time: 0,
+ trail: new Float32Array(TRAIL * 2), trailHead: 0, sparks: sparkPool(120),
+ };
+ centreBall(s);
+ return s;
+}
+
+/** Put the ball in play from the middle toward `serveDir`, at a random height and angle. */
+export function serve(s: DuelState, random: () => number): void {
+ s.serving = false;
+ s.rally = 0;
+ s.speed = SERVE_SPEED + (s.level - 1) * 8;
+ s.ballX = WIDTH / 2;
+ s.ballY = HEIGHT / 2 + (random() - 0.5) * 80;
+ const angle = (random() * 2 - 1) * 0.45;
+ s.vx = Math.cos(angle) * s.speed * s.serveDir;
+ s.vy = Math.sin(angle) * s.speed;
+ s.spin = 0;
+ s.cpuError = (random() * 2 - 1) * cpuSkill(s.level).error;
+}
+
+/** Where the ball will cross the CPU's paddle face, folding wall bounces in (spin ignored). */
+export function predictY(s: DuelState): number {
+ if (s.vx <= 0) return s.ballY;
+ const t = (CPU_X - HALF - s.ballX) / s.vx;
+ const lo = TOP + HALF, span = BOTTOM - HALF - lo;
+ let y = s.ballY + s.vy * t - lo;
+ // Fold the straight line back into the court, like a mirror between the walls.
+ const period = span * 2;
+ y = ((y % period) + period) % period;
+ if (y > span) y = period - y;
+ return y + lo;
+}
+
+function stepCpu(s: DuelState, dt: number): void {
+ const skill = cpuSkill(s.level);
+ s.cpuThink -= dt;
+ if (s.cpuThink <= 0) {
+ s.cpuThink = skill.reaction;
+ const coming = !s.serving && s.vx > 0;
+ s.cpuTarget = coming ? (skill.predicts ? predictY(s) : s.ballY) + s.cpuError : HEIGHT / 2;
+ }
+ const away = s.serving || s.vx <= 0;
+ const max = skill.speed * (away ? 0.5 : 1) * dt;
+ const before = s.cpuY;
+ const diff = s.cpuTarget - s.cpuY;
+ if (Math.abs(diff) > 2) s.cpuY += clamp(diff, -max, max);
+ s.cpuY = clamp(s.cpuY, TOP + PADDLE_H / 2, BOTTOM - PADDLE_H / 2);
+ s.cpuVy = dt > 0 ? (s.cpuY - before) / dt : 0;
+}
+
+function stepPlayer(s: DuelState, input: RetroInput, dt: number): void {
+ const before = s.playerY;
+ const dir = (input.down ? 1 : 0) - (input.up ? 1 : 0);
+ if (dir !== 0) {
+ s.pointerTarget = null;
+ s.playerY += dir * PLAYER_SPEED * dt;
+ }
+ const pointer = input.pointer;
+ if (pointer && pointer.y !== s.lastPointerY) s.pointerTarget = pointer.y;
+ s.lastPointerY = pointer ? pointer.y : null;
+ if (dir === 0 && s.pointerTarget !== null) {
+ const step = POINTER_SPEED * dt;
+ s.playerY += clamp(s.pointerTarget - s.playerY, -step, step);
+ }
+ s.playerY = clamp(s.playerY, TOP + PADDLE_H / 2, BOTTOM - PADDLE_H / 2);
+ s.playerVy = dt > 0 ? (s.playerY - before) / dt : 0;
+}
+
+/** The ball meets a paddle: angle from the contact point, spin from the paddle's motion, a little faster. */
+function returnBall(s: DuelState, byPlayer: boolean, paddleY: number, paddleVy: number, random: () => number): void {
+ s.rally += 1;
+ s.speed = Math.min(MAX_BALL_SPEED, s.speed + HIT_SPEEDUP);
+ const offset = clamp((s.ballY - paddleY) / (PADDLE_H / 2 + HALF), -1, 1);
+ const angle = offset * MAX_BOUNCE;
+ const dir = byPlayer ? 1 : -1;
+ s.vx = Math.cos(angle) * s.speed * dir;
+ s.vy = Math.sin(angle) * s.speed + paddleVy * 0.2;
+ s.spin = clamp(paddleVy / 250, -1, 1);
+ s.ballX = byPlayer ? PLAYER_X + PADDLE_W + HALF : CPU_X - HALF;
+ if (byPlayer) s.cpuError = (random() * 2 - 1) * cpuSkill(s.level).error;
+ emitSparks(s.sparks, s.ballX, s.ballY, 6 + Math.min(10, s.rally), 90, byPlayer ? "#9aa3ff" : "#ff8f6b", random, 0.35, 2);
+}
+
+/** Keep the ball at `speed` and never too steep. */
+function normaliseBall(s: DuelState): void {
+ const len = Math.hypot(s.vx, s.vy);
+ if (len < 1e-6) return;
+ let ux = s.vx / len, uy = s.vy / len;
+ if (Math.abs(ux) < MIN_HORIZONTAL) {
+ ux = Math.sign(ux || 1) * MIN_HORIZONTAL;
+ uy = Math.sign(uy || 1) * Math.sqrt(1 - MIN_HORIZONTAL * MIN_HORIZONTAL);
+ }
+ s.vx = ux * s.speed;
+ s.vy = uy * s.speed;
+}
+
+function pointScored(s: DuelState, byPlayer: boolean, random: () => number): void {
+ emitSparks(s.sparks, clamp(s.ballX, 0, WIDTH), s.ballY, 24, 140, byPlayer ? "#9aa3ff" : "#ff8f6b", random, 0.7, 2);
+ if (byPlayer) {
+ s.playerPoints += 1;
+ s.score += 100 + 10 * s.rally;
+ s.flashSide = 1;
+ } else {
+ s.cpuPoints += 1;
+ s.flashSide = -1;
+ s.shake = 0.3;
+ }
+ s.flash = 1;
+ s.rally = 0;
+ s.serving = true;
+ s.serveTimer = SERVE_DELAY;
+ // The side that lost the point receives the next serve.
+ s.serveDir = byPlayer ? 1 : -1;
+ centreBall(s);
+ if (s.playerPoints >= WIN_POINTS) {
+ s.score += 1000 * s.level;
+ s.level += 1;
+ s.matchPause = MATCH_PAUSE;
+ s.serveDir = -1;
+ for (let i = 0; i < 4; i += 1) emitSparks(s.sparks, WIDTH * (0.2 + i * 0.2), HEIGHT / 2, 12, 150, i % 2 ? "#f5f5f0" : "#9aa3ff", random, 1, 2);
+ } else if (s.cpuPoints >= WIN_POINTS) {
+ s.over = true;
+ }
+}
+
+function moveBall(s: DuelState, dt: number, random: () => number): void {
+ const n = Math.max(1, Math.ceil((Math.hypot(s.vx, s.vy) * dt) / 2));
+ const h = dt / n;
+ for (let k = 0; k < n; k += 1) {
+ s.vy += s.spin * SPIN_ACCEL * h;
+ s.ballX += s.vx * h;
+ s.ballY += s.vy * h;
+ if (s.ballY < TOP + HALF) {
+ s.ballY = TOP + HALF;
+ s.vy = Math.abs(s.vy);
+ s.spin *= 0.5;
+ emitSparks(s.sparks, s.ballX, TOP, 3, 50, "#f5f5f0", random, 0.25, 1);
+ } else if (s.ballY > BOTTOM - HALF) {
+ s.ballY = BOTTOM - HALF;
+ s.vy = -Math.abs(s.vy);
+ s.spin *= 0.5;
+ emitSparks(s.sparks, s.ballX, BOTTOM, 3, 50, "#f5f5f0", random, 0.25, 1);
+ }
+ const reach = PADDLE_H / 2 + HALF;
+ if (s.vx < 0 && s.ballX - HALF <= PLAYER_X + PADDLE_W && s.ballX - HALF >= PLAYER_X - 2
+ && Math.abs(s.ballY - s.playerY) <= reach) {
+ returnBall(s, true, s.playerY, s.playerVy, random);
+ } else if (s.vx > 0 && s.ballX + HALF >= CPU_X && s.ballX + HALF <= CPU_X + PADDLE_W + 2
+ && Math.abs(s.ballY - s.cpuY) <= reach) {
+ returnBall(s, false, s.cpuY, s.cpuVy, random);
+ }
+ if (s.ballX < -BALL * 2) { pointScored(s, false, random); return; }
+ if (s.ballX > WIDTH + BALL * 2) { pointScored(s, true, random); return; }
+ }
+}
+
+function stepDuel(s: DuelState, input: RetroInput, dt: number, random: () => number): void {
+ s.time += dt;
+ s.flash = Math.max(0, s.flash - dt * 2.5);
+ s.shake = Math.max(0, s.shake - dt);
+ stepSparks(s.sparks, dt, 40);
+ if (s.over) return;
+ stepPlayer(s, input, dt);
+ if (s.matchPause > 0) {
+ s.matchPause -= dt;
+ stepCpu(s, dt);
+ if (s.matchPause <= 0) {
+ s.matchPause = 0;
+ s.playerPoints = 0;
+ s.cpuPoints = 0;
+ s.serving = true;
+ s.serveTimer = SERVE_DELAY;
+ }
+ return;
+ }
+ if (s.serving) {
+ s.serveTimer -= dt;
+ if (s.serveTimer <= 0 || input.pressed.a) serve(s, random);
+ }
+ stepCpu(s, dt);
+ if (s.serving) return;
+ s.spin *= Math.pow(0.5, dt);
+ normaliseBall(s);
+ moveBall(s, dt, random);
+ s.trailHead = (s.trailHead + 1) % TRAIL;
+ s.trail[s.trailHead * 2] = s.ballX;
+ s.trail[s.trailHead * 2 + 1] = s.ballY;
+}
+
+// ---- drawing -------------------------------------------------------------
+
+const DIGITS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
+const PLAYER_COLOUR = "#9aa3ff";
+const CPU_COLOUR = "#ff8f6b";
+const LINE = "#e8e4d8";
+
+function drawPaddle(ctx: CanvasRenderingContext2D, x: number, y: number, colour: string): void {
+ const top = Math.round(y - PADDLE_H / 2);
+ ctx.globalAlpha = 0.22;
+ ctx.fillStyle = colour;
+ ctx.fillRect(x - 2, top - 2, PADDLE_W + 4, PADDLE_H + 4);
+ ctx.globalAlpha = 1;
+ ctx.fillRect(x, top, PADDLE_W, PADDLE_H);
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(x + 1, top + 1, 1, PADDLE_H - 2);
+}
+
+function drawDuel(ctx: CanvasRenderingContext2D, s: DuelState, info: { time: number; reduced: boolean; idle: boolean }): void {
+ ctx.save();
+ if (!info.reduced && s.shake > 0) {
+ const m = s.shake * 6;
+ ctx.translate(Math.round(Math.sin(s.time * 77) * m), Math.round(Math.cos(s.time * 61) * m));
+ }
+ ctx.fillStyle = "#0a0b10";
+ ctx.fillRect(-8, -8, WIDTH + 16, HEIGHT + 16);
+ if (!info.reduced && s.flash > 0 && s.flashSide !== 0) {
+ ctx.globalAlpha = s.flash * 0.16;
+ ctx.fillStyle = s.flashSide > 0 ? PLAYER_COLOUR : CPU_COLOUR;
+ ctx.fillRect(s.flashSide > 0 ? WIDTH / 2 : 0, 0, WIDTH / 2, HEIGHT);
+ ctx.globalAlpha = 1;
+ }
+
+ // Court: walls, centre dashes, scores and the CPU's level pips.
+ ctx.fillStyle = LINE;
+ ctx.fillRect(0, TOP - 2, WIDTH, 2);
+ ctx.fillRect(0, BOTTOM, WIDTH, 2);
+ ctx.globalAlpha = 0.35;
+ for (let y = TOP + 4; y < BOTTOM - 4; y += 12) ctx.fillRect(WIDTH / 2 - 1, y, 2, 6);
+ ctx.font = retroFont(28, 600);
+ ctx.textAlign = "center";
+ ctx.textBaseline = "top";
+ ctx.fillStyle = PLAYER_COLOUR;
+ ctx.fillText(DIGITS[Math.min(9, s.playerPoints)], WIDTH / 2 - 36, TOP + 8);
+ ctx.fillStyle = CPU_COLOUR;
+ ctx.fillText(DIGITS[Math.min(9, s.cpuPoints)], WIDTH / 2 + 36, TOP + 8);
+ ctx.globalAlpha = 0.6;
+ const pips = Math.min(10, s.level);
+ for (let i = 0; i < pips; i += 1) ctx.fillRect(WIDTH / 2 + 36 - pips * 2 + i * 4, TOP + 42, 2, 2);
+ ctx.globalAlpha = 1;
+
+ drawPaddle(ctx, PLAYER_X, s.playerY, PLAYER_COLOUR);
+ drawPaddle(ctx, CPU_X, s.cpuY, CPU_COLOUR);
+
+ // Ball, with a trail tinted by its spin.
+ const tint = s.spin > 0.15 ? PLAYER_COLOUR : s.spin < -0.15 ? CPU_COLOUR : "#f5f5f0";
+ if (!s.serving && s.matchPause <= 0) {
+ for (let i = 1; i < TRAIL; i += 1) {
+ const j = (s.trailHead - i + TRAIL) % TRAIL;
+ ctx.globalAlpha = 0.28 * (1 - i / TRAIL);
+ ctx.fillStyle = tint;
+ ctx.fillRect(Math.round(s.trail[j * 2] - HALF), Math.round(s.trail[j * 2 + 1] - HALF), BALL, BALL);
+ }
+ ctx.globalAlpha = 1;
+ }
+ if (s.matchPause <= 0) {
+ ctx.fillStyle = "#f5f5f0";
+ ctx.fillRect(Math.round(s.ballX - HALF), Math.round(s.ballY - HALF), BALL, BALL);
+ if (s.serving && !info.idle) {
+ // A ring that closes until the automatic serve.
+ ctx.strokeStyle = s.serveDir > 0 ? PLAYER_COLOUR : CPU_COLOUR;
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.arc(s.ballX, s.ballY, 8, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * clamp(s.serveTimer / SERVE_DELAY, 0, 1));
+ ctx.stroke();
+ }
+ }
+ drawSparks(ctx, s.sparks);
+ ctx.restore();
+ drawScanlines(ctx, WIDTH, HEIGHT, 0.1);
+}
+
+const paddleDuel: RetroGame<DuelState> = {
+ id: "paddle-duel",
+ width: WIDTH,
+ height: HEIGHT,
+ pointer: true,
+ create: () => createDuel(),
+ step: stepDuel,
+ draw: drawDuel,
+ status: (s) => ({ score: s.score, level: s.level, over: s.over, won: false }),
+};
+
+export default paddleDuel;
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/pixelRaiders.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/pixelRaiders.test.ts
new file mode 100644
index 0000000000..0c92c5725a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/pixelRaiders.test.ts
@@ -0,0 +1,257 @@
+import { describe, expect, it } from "vitest";
+import { idleInput, RETRO_STEP, seededRandom, type RetroInput } from "../retroGame";
+import game, {
+ BUNKER_X, BUNKER_Y, CELL_W, COLS, DROP_Y, KIND_POINTS, MARCH_X, PLAYER_Y, ROWS, WIDTH,
+ alienX, alienY, bunkerCells, march, stepDelay, waveStartY, type RaidersState,
+} from "./pixelRaiders";
+
+const rnd = seededRandom(7);
+const run = (s: RaidersState, input: RetroInput, seconds: number) => {
+ for (let t = 0; t < seconds; t += RETRO_STEP) game.step(s, input, RETRO_STEP, rnd);
+};
+/** A run with the formation and its guns held still, so one rule can be watched at a time. */
+const calm = (): RaidersState => {
+ const s = game.create(seededRandom(1));
+ s.stepTimer = 999;
+ s.fireTimer = 999;
+ s.saucerTimer = 999;
+ return s;
+};
+
+/** A canvas stand-in that only knows the calls a game may make, and rejects non-finite rectangles. */
+function fakeContext(): { ctx: CanvasRenderingContext2D; depth: () => number; rects: () => number } {
+ let depth = 0, rects = 0;
+ const finite = (...v: number[]) => {
+ if (!v.every(Number.isFinite)) throw new Error(`non-finite draw arguments ${v.join(",")}`);
+ };
+ const noop = () => {};
+ const ctx = {
+ fillStyle: "", strokeStyle: "", lineWidth: 1, globalAlpha: 1, lineCap: "butt",
+ fillRect: (x: number, y: number, w: number, h: number) => { finite(x, y, w, h); rects += 1; },
+ strokeRect: (x: number, y: number, w: number, h: number) => finite(x, y, w, h),
+ beginPath: noop, closePath: noop, fill: noop, stroke: noop,
+ moveTo: (x: number, y: number) => finite(x, y),
+ lineTo: (x: number, y: number) => finite(x, y),
+ arc: (x: number, y: number, r: number) => finite(x, y, r),
+ translate: (x: number, y: number) => finite(x, y),
+ save: () => { depth += 1; },
+ restore: () => { depth -= 1; },
+ };
+ return { ctx: ctx as unknown as CanvasRenderingContext2D, depth: () => depth, rects: () => rects };
+}
+
+describe("pixel raiders", () => {
+ it("starts with a full formation, four whole bunkers and three lives", () => {
+ const s = game.create(seededRandom(1));
+ expect(s.aliveCount).toBe(ROWS * COLS);
+ expect(game.status(s)).toEqual({ score: 0, lives: 3, level: 1, over: false });
+ const whole = bunkerCells(s, 0);
+ expect(whole).toBeGreaterThan(60);
+ for (let b = 1; b < 4; b += 1) expect(bunkerCells(s, b)).toBe(whole);
+ expect(s.fy).toBe(waveStartY(1));
+ });
+
+ it("marches sideways one step at a time", () => {
+ const s = calm();
+ const x0 = s.fx;
+ s.stepTimer = 0.001;
+ game.step(s, idleInput(), RETRO_STEP, rnd);
+ expect(s.fx).toBe(x0 + MARCH_X);
+ expect(s.frame).toBe(1);
+ });
+
+ it("drops a row and turns around at the wall", () => {
+ const s = calm();
+ s.fx = WIDTH - COLS * CELL_W - 4;
+ const y0 = s.fy;
+ march(s, rnd);
+ expect(s.fy).toBe(y0 + DROP_Y);
+ expect(s.dir).toBe(-1);
+ const x1 = s.fx;
+ march(s, rnd);
+ expect(s.fx).toBe(x1 - MARCH_X);
+ });
+
+ it("ignores empty outer columns when finding the wall", () => {
+ const s = calm();
+ for (let r = 0; r < ROWS; r += 1) s.alive[r * COLS + COLS - 1] = 0;
+ s.aliveCount -= ROWS;
+ s.fx = WIDTH - COLS * CELL_W - 4;
+ const y0 = s.fy;
+ march(s, rnd);
+ expect(s.fy).toBe(y0);
+ });
+
+ it("speeds up as fewer aliens remain and in later waves", () => {
+ expect(stepDelay(10, 1)).toBeLessThan(stepDelay(55, 1));
+ expect(stepDelay(1, 1)).toBeLessThan(RETRO_STEP);
+ expect(stepDelay(55, 4)).toBeLessThan(stepDelay(55, 1));
+ expect(waveStartY(3)).toBeGreaterThan(waveStartY(1));
+ });
+
+ it("a shot kills the alien it hits and scores its kind", () => {
+ const s = calm();
+ // Bottom row, middle column: clear line of fire above the cannon.
+ const row = ROWS - 1, col = 5;
+ s.shots[0].active = true;
+ s.shots[0].x = alienX(s, row, col) + 4;
+ s.shots[0].y = alienY(s, row) + 12;
+ run(s, idleInput(), 0.1);
+ expect(s.alive[row * COLS + col]).toBe(0);
+ expect(s.aliveCount).toBe(ROWS * COLS - 1);
+ expect(s.score).toBe(KIND_POINTS[2]);
+ expect(s.shots[0].active).toBe(false);
+ });
+
+ it("fires on the action button, at most two shots at once", () => {
+ const s = calm();
+ s.px = 4; // left of the first bunker, so the shots fly free
+ run(s, { ...idleInput(), a: true }, 0.4);
+ expect(s.shots.filter((x) => x.active).length).toBeGreaterThanOrEqual(1);
+ run(s, { ...idleInput(), a: true }, 1);
+ expect(s.shots.filter((x) => x.active).length).toBeLessThanOrEqual(2);
+ });
+
+ it("a tap shorter than one frame still fires (the press edge alone)", () => {
+ const s = calm();
+ s.px = 4;
+ const tap = idleInput();
+ tap.pressed.a = true;
+ game.step(s, tap, RETRO_STEP, rnd);
+ expect(s.shots.filter((x) => x.active).length).toBe(1);
+ });
+
+ it("player shots and alien shots chip bunkers cell by cell", () => {
+ const s = calm();
+ const before = bunkerCells(s, 1);
+ s.shots[0].active = true;
+ s.shots[0].x = BUNKER_X[1] + 10;
+ s.shots[0].y = BUNKER_Y + 20;
+ run(s, idleInput(), 0.2);
+ const afterShot = bunkerCells(s, 1);
+ expect(afterShot).toBeLessThan(before);
+ expect(afterShot).toBeGreaterThan(before - 15);
+ expect(s.shots[0].active).toBe(false);
+
+ s.bombs[0].active = true;
+ s.bombs[0].x = BUNKER_X[2] + 4;
+ s.bombs[0].y = BUNKER_Y - 10;
+ s.bombs[0].speed = 80;
+ s.bombs[0].kind = 0;
+ run(s, idleInput(), 0.3);
+ expect(bunkerCells(s, 2)).toBeLessThan(before);
+ expect(s.bombs[0].active).toBe(false);
+ });
+
+ it("an alien shot costs a life, then the cannon comes back", () => {
+ const s = calm();
+ s.px = 100;
+ s.bombs[0].active = true;
+ s.bombs[0].x = 106;
+ s.bombs[0].y = PLAYER_Y - 8;
+ s.bombs[0].speed = 80;
+ run(s, idleInput(), 0.2);
+ expect(s.lives).toBe(2);
+ expect(s.phase).toBe("dying");
+ run(s, idleInput(), 2);
+ expect(s.phase).toBe("play");
+ expect(game.status(s).over).toBe(false);
+ });
+
+ it("the last life lost ends the run", () => {
+ const s = calm();
+ s.lives = 1;
+ s.px = 100;
+ s.bombs[0].active = true;
+ s.bombs[0].x = 106;
+ s.bombs[0].y = PLAYER_Y - 4;
+ s.bombs[0].speed = 80;
+ run(s, idleInput(), 2);
+ expect(game.status(s)).toMatchObject({ lives: 0, over: true });
+ });
+
+ it("clearing the formation starts a lower, faster wave with fresh bunkers", () => {
+ const s = calm();
+ s.alive.fill(0);
+ s.alive[(ROWS - 1) * COLS + 5] = 1;
+ s.aliveCount = 1;
+ s.bunkers.fill(0);
+ s.shots[0].active = true;
+ s.shots[0].x = alienX(s, ROWS - 1, 5) + 4;
+ s.shots[0].y = alienY(s, ROWS - 1) + 10;
+ run(s, idleInput(), 0.1);
+ expect(s.phase).toBe("clear");
+ run(s, idleInput(), 2);
+ expect(s.wave).toBe(2);
+ expect(s.aliveCount).toBe(ROWS * COLS);
+ expect(s.fy).toBe(waveStartY(2));
+ expect(bunkerCells(s, 0)).toBeGreaterThan(60);
+ expect(stepDelay(55, 2)).toBeLessThan(stepDelay(55, 1));
+ });
+
+ it("the formation reaching the cannon ends the run", () => {
+ const s = calm();
+ s.fy = PLAYER_Y - (ROWS - 1) * 16 - 8 - 2;
+ s.fx = WIDTH - COLS * CELL_W - 4;
+ march(s, rnd);
+ run(s, idleInput(), 2);
+ expect(game.status(s).over).toBe(true);
+ });
+
+ it("the saucer comes by and is worth bonus points", () => {
+ const s = calm();
+ s.saucerTimer = 0.01;
+ run(s, idleInput(), 0.05);
+ expect(s.saucer.active).toBe(true);
+ s.saucer.x = 100;
+ s.shots[0].active = true;
+ s.shots[0].x = 108;
+ s.shots[0].y = 40;
+ const before = s.score;
+ run(s, idleInput(), 0.1);
+ expect(s.saucer.active).toBe(false);
+ expect(s.score - before).toBe(s.popups.find((p) => p.active)?.value);
+ });
+
+ it("aliens shoot back but never more than the cap", () => {
+ const s = game.create(seededRandom(3));
+ s.stepTimer = 999;
+ let most = 0;
+ for (let i = 0; i < 1200 && s.phase === "play"; i += 1) {
+ game.step(s, idleInput(), RETRO_STEP, rnd);
+ most = Math.max(most, s.bombs.filter((b) => b.active).length);
+ }
+ expect(most).toBeGreaterThan(0);
+ expect(most).toBeLessThanOrEqual(2);
+ });
+
+ it("draws every phase without throwing, idle and reduced included", () => {
+ const s = game.create(seededRandom(2));
+ for (const info of [
+ { time: 0, reduced: false, idle: true },
+ { time: 3.3, reduced: true, idle: true },
+ { time: 1.2, reduced: false, idle: false },
+ ]) {
+ const fake = fakeContext();
+ game.draw(fake.ctx, s, info);
+ expect(fake.depth()).toBe(0);
+ expect(fake.rects()).toBeGreaterThan(100);
+ }
+ // A busy frame: shots, bombs, saucer, a dying cannon, then game over.
+ run(s, { ...idleInput(), a: true, right: true }, 3);
+ s.saucer.active = true;
+ s.saucer.x = 60;
+ s.popups[0].active = true;
+ s.popups[0].t = 1;
+ s.popups[0].value = 150;
+ s.shake = 0.3;
+ s.phase = "dying";
+ s.timer = 1;
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: false, idle: false });
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: true, idle: false });
+ s.phase = "clear";
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: false, idle: false });
+ s.phase = "over";
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: false, idle: false });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/pixelRaiders.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/pixelRaiders.ts
new file mode 100644
index 0000000000..3f0e6da226
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/pixelRaiders.ts
@@ -0,0 +1,676 @@
+/**
+ * "Pixel Raiders": a formation of pixel aliens marches sideways, drops a row
+ * at each edge and speeds up as it thins out. They shoot back (some shots
+ * aimed at the cannon, some from a random column); the cannon hides behind
+ * four bunkers that crumble cell by cell. A bonus saucer crosses the top now
+ * and then. Clearing the formation brings the next wave, starting lower and
+ * marching faster; the formation reaching the cannon ends the run.
+ */
+import type { RetroDrawInfo, RetroGame, RetroInput, RetroStatus } from "../retroGame";
+import {
+ clamp, drawNumber, drawParticles, drawSprite, drawStars, emitBurst, makeParticles, sprite, starField, stepParticles,
+ type Particle, type PixelSprite,
+} from "./games3Kit";
+
+export const WIDTH = 224;
+export const HEIGHT = 256;
+
+export const COLS = 11;
+export const ROWS = 5;
+export const CELL_W = 16;
+export const CELL_H = 16;
+const ALIEN_H = 8;
+/** Pixels the formation moves per march step, and drops at an edge. */
+export const MARCH_X = 2;
+export const DROP_Y = 8;
+/** The formation turns when its outer column would come closer than this to a side wall. */
+const EDGE_MARGIN = 6;
+
+/** Which alien kind each row holds (top to bottom), their widths and points. */
+const ROW_KIND = [0, 1, 1, 2, 2] as const;
+const KIND_W = [8, 10, 12] as const;
+export const KIND_POINTS = [30, 20, 10] as const;
+const KIND_COLOR = ["#ff7ae0", "#7ae8ff", "#9dff7a"] as const;
+
+export const PLAYER_Y = 216;
+export const PLAYER_W = 13;
+const PLAYER_H = 8;
+const PLAYER_SPEED = 80;
+const PLAYER_START_X = Math.round((WIDTH - PLAYER_W) / 2);
+export const MAX_SHOTS = 2;
+const SHOT_SPEED = 260;
+const SHOT_COOLDOWN = 0.32;
+const GROUND_Y = 230;
+
+export const MAX_BOMBS = 6;
+
+export const BUNKER_COUNT = 4;
+export const BUNKER_COLS = 11;
+export const BUNKER_ROWS = 8;
+/** Bunker cells are 2 × 2 pixels. */
+export const BUNKER_CELL = 2;
+export const BUNKER_Y = 184;
+export const BUNKER_X: readonly number[] = [0, 1, 2, 3].map((i) => Math.round((WIDTH * (i + 1)) / 5 - (BUNKER_COLS * BUNKER_CELL) / 2));
+const BUNKER_SHAPE = [
+ "..#######..",
+ ".#########.",
+ "###########",
+ "###########",
+ "###########",
+ "###########",
+ "###.....###",
+ "##.......##",
+];
+
+const SAUCER_W = 16;
+const SAUCER_Y = 26;
+const SAUCER_SPEED = 48;
+const SAUCER_POINTS = [50, 100, 100, 150, 150, 300] as const;
+
+const DEATH_S = 1.4;
+const CLEAR_S = 1.6;
+const EXTRA_LIFE_EVERY = 2000;
+const MAX_LIVES = 5;
+
+/** Two animation frames per alien kind: our own designs, a jelly, a horned beetle and a crested trilobite. */
+const ALIEN_SPRITES: readonly (readonly [PixelSprite, PixelSprite])[] = [
+ [
+ sprite(["..####..", ".######.", "##.##.##", "########", ".#.##.#.", "#..##..#", ".#....#.", "..#..#.."]),
+ sprite(["..####..", ".######.", "##.##.##", "########", ".#.##.#.", ".#.##.#.", "#..##..#", "#......#"]),
+ ],
+ [
+ sprite(["#........#", ".#..##..#.", "..######..", ".##.##.##.", "##########", ".#.####.#.", "#.#....#.#", ".#......#."]),
+ sprite(["..#....#..", "..#.##.#..", "..######..", ".##.##.##.", "##########", "#.######.#", "..#....#..", ".#.#..#.#."]),
+ ],
+ [
+ sprite([".....##.....", "...######...", ".##########.", "##.##..##.##", "############", ".#.#.##.#.#.", "#.#......#.#", ".#........#."]),
+ sprite([".....##.....", "...######...", ".##########.", "##.##..##.##", "############", "..#.#..#.#..", ".#.#....#.#.", "#.#......#.#"]),
+ ],
+];
+const BURST_SPRITE = sprite(["#..#..#.#..", ".#..#.#..#.", "..#.....#..", "##.......##", "..#.....#..", ".#..#.#..#.", "#..#...#..#"]);
+const PLAYER_SPRITE = sprite([
+ "......#......",
+ ".....###.....",
+ "....#####....",
+ ".###########.",
+ "#############",
+ "#############",
+ "#.#.#.#.#.#.#",
+ ".#.#.#.#.#.#.",
+]);
+const WRECK_SPRITES = [
+ sprite(["..#.....#....", "....#.#...#..", "#..#####.....", "..#######.#..", ".##.###.###..", "#############", "#.#.#.#.#.#.#", ".#.#.#.#.#.#."]),
+ sprite(["#.....#....#.", "...#.....#...", "..#.##.#.....", "#.##.###.##..", ".###.###.###.", "#############", ".#.#.#.#.#.#.", "#.#.#.#.#.#.#"]),
+];
+const SAUCER_SPRITE = sprite([
+ ".....######.....",
+ "...##########...",
+ "..############..",
+ ".##.##.##.##.##.",
+ "################",
+ "..###..##..###..",
+ "...#........#...",
+]);
+const LIFE_SPRITE = sprite(["...#...", "..###..", "#######", "#######"]);
+
+export type RaidersPhase = "play" | "dying" | "clear" | "over";
+
+export interface Shot { active: boolean; x: number; y: number }
+/** An alien shot. `kind` 0 straight, 1 zigzag (aimed), 2 fast dart. */
+export interface Bomb { active: boolean; x: number; y: number; kind: number; speed: number }
+interface Burst { active: boolean; x: number; y: number; t: number; color: string }
+interface Popup { active: boolean; x: number; y: number; t: number; value: number }
+
+export interface RaidersState {
+ phase: RaidersPhase;
+ /** Seconds left in a dying / clear phase. */
+ timer: number;
+ /** Total seconds simulated; zero means the run has not started (attract screen). */
+ elapsed: number;
+ score: number;
+ lives: number;
+ wave: number;
+ nextLifeAt: number;
+ px: number;
+ cooldown: number;
+ shots: Shot[];
+ bombs: Bomb[];
+ /** One flag per alien, row-major (ROWS × COLS). */
+ alive: Uint8Array;
+ aliveCount: number;
+ /** Top-left of the formation's grid of cells. */
+ fx: number;
+ fy: number;
+ dir: 1 | -1;
+ stepTimer: number;
+ frame: 0 | 1;
+ fireTimer: number;
+ /** One flag per bunker cell, bunker-major (BUNKER_COUNT × BUNKER_ROWS × BUNKER_COLS). */
+ bunkers: Uint8Array;
+ saucer: { active: boolean; x: number; dir: 1 | -1; points: number };
+ saucerTimer: number;
+ bursts: Burst[];
+ popups: Popup[];
+ particles: Particle[];
+ shake: number;
+}
+
+/** Seconds between march steps: slow with a full formation, every frame with one alien left, faster each wave. */
+export function stepDelay(alive: number, wave: number): number {
+ const fill = clamp((alive - 1) / (ROWS * COLS - 1), 0, 1);
+ return (0.012 + 0.45 * fill) * Math.max(0.55, 1 - 0.07 * (wave - 1));
+}
+
+/** The formation's top edge at the start of a wave: each wave starts a row lower, up to a limit. */
+export function waveStartY(wave: number): number {
+ return 48 + Math.min(wave - 1, 7) * 8;
+}
+
+function maxBombs(wave: number): number {
+ return Math.min(MAX_BOMBS, 2 + Math.floor(wave / 2));
+}
+
+function resetBunkers(bunkers: Uint8Array): void {
+ for (let b = 0; b < BUNKER_COUNT; b += 1) {
+ for (let r = 0; r < BUNKER_ROWS; r += 1) {
+ for (let c = 0; c < BUNKER_COLS; c += 1) {
+ bunkers[(b * BUNKER_ROWS + r) * BUNKER_COLS + c] = BUNKER_SHAPE[r][c] === "#" ? 1 : 0;
+ }
+ }
+ }
+}
+
+/** Solid cells left in one bunker (tests and balance). */
+export function bunkerCells(state: RaidersState, bunker: number): number {
+ let n = 0;
+ const base = bunker * BUNKER_ROWS * BUNKER_COLS;
+ for (let i = 0; i < BUNKER_ROWS * BUNKER_COLS; i += 1) n += state.bunkers[base + i];
+ return n;
+}
+
+function startWave(state: RaidersState, random: () => number): void {
+ state.alive.fill(1);
+ state.aliveCount = ROWS * COLS;
+ state.fx = Math.round((WIDTH - COLS * CELL_W) / 2);
+ state.fy = waveStartY(state.wave);
+ state.dir = 1;
+ state.frame = 0;
+ state.stepTimer = stepDelay(state.aliveCount, state.wave);
+ state.fireTimer = 1.2 + random();
+ for (const s of state.shots) s.active = false;
+ for (const b of state.bombs) b.active = false;
+ resetBunkers(state.bunkers);
+ state.saucer.active = false;
+ state.saucerTimer = 14 + random() * 10;
+}
+
+function create(random: () => number): RaidersState {
+ const state: RaidersState = {
+ phase: "play", timer: 0, elapsed: 0, score: 0, lives: 3, wave: 1, nextLifeAt: EXTRA_LIFE_EVERY,
+ px: PLAYER_START_X, cooldown: 0,
+ shots: Array.from({ length: MAX_SHOTS }, () => ({ active: false, x: 0, y: 0 })),
+ bombs: Array.from({ length: MAX_BOMBS }, () => ({ active: false, x: 0, y: 0, kind: 0, speed: 0 })),
+ alive: new Uint8Array(ROWS * COLS), aliveCount: 0,
+ fx: 0, fy: 0, dir: 1, stepTimer: 0, frame: 0, fireTimer: 0,
+ bunkers: new Uint8Array(BUNKER_COUNT * BUNKER_ROWS * BUNKER_COLS),
+ saucer: { active: false, x: 0, dir: 1, points: 0 }, saucerTimer: 0,
+ bursts: Array.from({ length: 8 }, () => ({ active: false, x: 0, y: 0, t: 0, color: "#fff" })),
+ popups: Array.from({ length: 3 }, () => ({ active: false, x: 0, y: 0, t: 0, value: 0 })),
+ particles: makeParticles(120),
+ shake: 0,
+ };
+ startWave(state, random);
+ return state;
+}
+
+/** Left pixel of the alien at (row, col). */
+export function alienX(state: RaidersState, row: number, col: number): number {
+ return state.fx + col * CELL_W + (CELL_W - KIND_W[ROW_KIND[row]]) / 2;
+}
+
+export function alienY(state: RaidersState, row: number): number {
+ return state.fy + row * CELL_H;
+}
+
+function addScore(state: RaidersState, points: number): void {
+ state.score += points;
+ if (state.score >= state.nextLifeAt) {
+ state.nextLifeAt += EXTRA_LIFE_EVERY;
+ state.lives = Math.min(MAX_LIVES, state.lives + 1);
+ }
+}
+
+function spawnBurst(state: RaidersState, x: number, y: number, color: string): void {
+ const slot = state.bursts.find((b) => !b.active) ?? state.bursts[0];
+ slot.active = true; slot.x = x; slot.y = y; slot.t = 0.2; slot.color = color;
+}
+
+/** Erode a bunker around the cell that was hit; `down` is the shot's direction of travel. */
+function erode(state: RaidersState, bunker: number, cx: number, cy: number, down: boolean, random: () => number): void {
+ const base = bunker * BUNKER_ROWS * BUNKER_COLS;
+ for (let dy = -1; dy <= 1; dy += 1) {
+ for (let dx = -1; dx <= 1; dx += 1) {
+ const x = cx + dx, y = cy + dy;
+ if (x < 0 || y < 0 || x >= BUNKER_COLS || y >= BUNKER_ROWS) continue;
+ if ((dx === 0 && dy === 0) || random() < 0.4) state.bunkers[base + y * BUNKER_COLS + x] = 0;
+ }
+ }
+ // Bites go a little deeper in the direction the shot was travelling.
+ const deeper = cy + (down ? 2 : -2);
+ if (deeper >= 0 && deeper < BUNKER_ROWS && random() < 0.5) state.bunkers[base + deeper * BUNKER_COLS + cx] = 0;
+ emitBurst(state.particles, BUNKER_X[bunker] + cx * BUNKER_CELL, BUNKER_Y + cy * BUNKER_CELL, 4, 30, "#4dff88", random, 0.3);
+}
+
+/** If (x, y) is inside a solid bunker cell, chip it and report the hit. */
+function hitBunker(state: RaidersState, x: number, y: number, down: boolean, random: () => number): boolean {
+ if (y < BUNKER_Y || y >= BUNKER_Y + BUNKER_ROWS * BUNKER_CELL) return false;
+ for (let b = 0; b < BUNKER_COUNT; b += 1) {
+ const bx = BUNKER_X[b];
+ if (x < bx || x >= bx + BUNKER_COLS * BUNKER_CELL) continue;
+ const cx = Math.floor((x - bx) / BUNKER_CELL), cy = Math.floor((y - BUNKER_Y) / BUNKER_CELL);
+ if (state.bunkers[(b * BUNKER_ROWS + cy) * BUNKER_COLS + cx]) {
+ erode(state, b, cx, cy, down, random);
+ return true;
+ }
+ return false;
+ }
+ return false;
+}
+
+function killAlien(state: RaidersState, row: number, col: number, random: () => number): void {
+ state.alive[row * COLS + col] = 0;
+ state.aliveCount -= 1;
+ const kind = ROW_KIND[row];
+ addScore(state, KIND_POINTS[kind]);
+ const x = alienX(state, row, col), y = alienY(state, row);
+ spawnBurst(state, x + KIND_W[kind] / 2, y + ALIEN_H / 2, KIND_COLOR[kind]);
+ emitBurst(state.particles, x + KIND_W[kind] / 2, y + ALIEN_H / 2, 10, 70, KIND_COLOR[kind], random, 0.45);
+ if (state.aliveCount === 0) {
+ state.phase = "clear";
+ state.timer = CLEAR_S;
+ for (const b of state.bombs) b.active = false;
+ state.saucer.active = false;
+ }
+}
+
+/** The alien hit by a point, as row * COLS + col, or -1. */
+function alienAt(state: RaidersState, x: number, y: number): number {
+ const col = Math.floor((x - state.fx) / CELL_W), row = Math.floor((y - state.fy) / CELL_H);
+ if (col < 0 || col >= COLS || row < 0 || row >= ROWS || !state.alive[row * COLS + col]) return -1;
+ const ax = alienX(state, row, col), ay = alienY(state, row);
+ return x >= ax && x < ax + KIND_W[ROW_KIND[row]] && y >= ay && y < ay + ALIEN_H ? row * COLS + col : -1;
+}
+
+function killPlayer(state: RaidersState, random: () => number): void {
+ state.phase = "dying";
+ state.timer = DEATH_S;
+ state.lives = Math.max(0, state.lives - 1);
+ state.shake = 0.4;
+ for (const b of state.bombs) b.active = false;
+ for (const s of state.shots) s.active = false;
+ emitBurst(state.particles, state.px + PLAYER_W / 2, PLAYER_Y + 4, 28, 90, "#63f3ff", random, 0.9);
+ emitBurst(state.particles, state.px + PLAYER_W / 2, PLAYER_Y + 4, 14, 60, "#fff6a8", random, 0.6);
+}
+
+/** Bounds of the living formation: [minCol, maxCol, maxRow], or null when it is empty. */
+function formationBounds(state: RaidersState, out: number[]): boolean {
+ let minCol = COLS, maxCol = -1, maxRow = -1;
+ for (let r = 0; r < ROWS; r += 1) {
+ for (let c = 0; c < COLS; c += 1) {
+ if (!state.alive[r * COLS + c]) continue;
+ if (c < minCol) minCol = c;
+ if (c > maxCol) maxCol = c;
+ if (r > maxRow) maxRow = r;
+ }
+ }
+ out[0] = minCol; out[1] = maxCol; out[2] = maxRow;
+ return maxCol >= 0;
+}
+const bounds = [0, 0, 0];
+
+/** One march step: sideways, or down and turn around at a wall. */
+export function march(state: RaidersState, random: () => number): void {
+ if (!formationBounds(state, bounds)) return;
+ const [minCol, maxCol, maxRow] = bounds;
+ const left = state.fx + minCol * CELL_W + 1;
+ const right = state.fx + (maxCol + 1) * CELL_W - 1;
+ const atWall = state.dir > 0 ? right + MARCH_X > WIDTH - EDGE_MARGIN : left - MARCH_X < EDGE_MARGIN;
+ if (atWall) {
+ state.fy += DROP_Y;
+ state.dir = state.dir > 0 ? -1 : 1;
+ } else {
+ state.fx += MARCH_X * state.dir;
+ }
+ state.frame = state.frame ? 0 : 1;
+ const bottom = state.fy + maxRow * CELL_H + ALIEN_H;
+ // Aliens grind through any bunker they march into.
+ if (bottom > BUNKER_Y) {
+ for (let r = 0; r <= maxRow; r += 1) {
+ const ay = alienY(state, r);
+ if (ay + ALIEN_H <= BUNKER_Y) continue;
+ for (let c = 0; c < COLS; c += 1) {
+ if (!state.alive[r * COLS + c]) continue;
+ const ax = alienX(state, r, c);
+ for (let y = ay; y < ay + ALIEN_H; y += BUNKER_CELL) {
+ for (let x = ax; x < ax + KIND_W[ROW_KIND[r]]; x += BUNKER_CELL) clearBunkerAt(state, x, y);
+ }
+ }
+ }
+ }
+ if (bottom >= PLAYER_Y && state.phase === "play") {
+ // The formation has landed: the run is over no matter how many lives are left.
+ killPlayer(state, random);
+ state.lives = 0;
+ }
+}
+
+function clearBunkerAt(state: RaidersState, x: number, y: number): void {
+ if (y < BUNKER_Y || y >= BUNKER_Y + BUNKER_ROWS * BUNKER_CELL) return;
+ for (let b = 0; b < BUNKER_COUNT; b += 1) {
+ const bx = BUNKER_X[b];
+ if (x < bx || x >= bx + BUNKER_COLS * BUNKER_CELL) continue;
+ state.bunkers[(b * BUNKER_ROWS + Math.floor((y - BUNKER_Y) / BUNKER_CELL)) * BUNKER_COLS + Math.floor((x - bx) / BUNKER_CELL)] = 0;
+ }
+}
+
+/** Fire an alien shot: aimed from the column above the cannon, or from a random column. */
+function alienFire(state: RaidersState, random: () => number): void {
+ let active = 0;
+ for (const b of state.bombs) if (b.active) active += 1;
+ if (active >= maxBombs(state.wave)) return;
+ const aimed = random() < 0.45;
+ let col = -1;
+ if (aimed) {
+ let best = Infinity;
+ const target = state.px + PLAYER_W / 2;
+ for (let c = 0; c < COLS; c += 1) {
+ if (!columnAlive(state, c)) continue;
+ const d = Math.abs(state.fx + c * CELL_W + CELL_W / 2 - target);
+ if (d < best) { best = d; col = c; }
+ }
+ } else {
+ // Pick the n-th living column.
+ let living = 0;
+ for (let c = 0; c < COLS; c += 1) if (columnAlive(state, c)) living += 1;
+ let pick = Math.floor(random() * living);
+ for (let c = 0; c < COLS && col < 0; c += 1) if (columnAlive(state, c) && pick-- === 0) col = c;
+ }
+ if (col < 0) return;
+ let row = ROWS - 1;
+ while (row >= 0 && !state.alive[row * COLS + col]) row -= 1;
+ const bomb = state.bombs.find((b) => !b.active);
+ if (!bomb || row < 0) return;
+ bomb.active = true;
+ bomb.x = Math.round(state.fx + col * CELL_W + CELL_W / 2);
+ bomb.y = alienY(state, row) + ALIEN_H;
+ bomb.kind = aimed ? 1 : random() < 0.3 ? 2 : 0;
+ bomb.speed = 70 + 6 * Math.min(state.wave, 8) + (bomb.kind === 2 ? 30 : 0);
+}
+
+function columnAlive(state: RaidersState, col: number): boolean {
+ for (let r = 0; r < ROWS; r += 1) if (state.alive[r * COLS + col]) return true;
+ return false;
+}
+
+function stepShots(state: RaidersState, dt: number, random: () => number): void {
+ for (const shot of state.shots) {
+ if (!shot.active) continue;
+ // Move in 2-pixel steps so a fast shot never skips over a bunker cell or an alien.
+ const steps = Math.max(1, Math.ceil((SHOT_SPEED * dt) / 2));
+ const stepLen = (SHOT_SPEED * dt) / steps;
+ for (let i = 0; i < steps && shot.active; i += 1) {
+ shot.y -= stepLen;
+ if (shot.y < 12) { shot.active = false; break; }
+ if (hitBunker(state, shot.x, shot.y, false, random)) { shot.active = false; break; }
+ const hit = alienAt(state, shot.x, shot.y);
+ if (hit >= 0) {
+ shot.active = false;
+ killAlien(state, Math.floor(hit / COLS), hit % COLS, random);
+ break;
+ }
+ const s = state.saucer;
+ if (s.active && shot.x >= s.x && shot.x < s.x + SAUCER_W && shot.y >= SAUCER_Y && shot.y < SAUCER_Y + 7) {
+ shot.active = false;
+ s.active = false;
+ addScore(state, s.points);
+ const popup = state.popups.find((p) => !p.active) ?? state.popups[0];
+ popup.active = true; popup.x = s.x + SAUCER_W / 2; popup.y = SAUCER_Y; popup.t = 1.2; popup.value = s.points;
+ emitBurst(state.particles, s.x + SAUCER_W / 2, SAUCER_Y + 3, 18, 80, "#ff4f6d", random, 0.6);
+ break;
+ }
+ for (const b of state.bombs) {
+ if (b.active && Math.abs(b.x - shot.x) <= 1.5 && shot.y >= b.y - 1 && shot.y <= b.y + 7) {
+ b.active = false;
+ shot.active = false;
+ emitBurst(state.particles, shot.x, shot.y, 6, 40, "#ffffff", random, 0.3);
+ break;
+ }
+ }
+ }
+ }
+}
+
+function stepBombs(state: RaidersState, dt: number, random: () => number): void {
+ for (const b of state.bombs) {
+ if (!b.active) continue;
+ const steps = Math.max(1, Math.ceil((b.speed * dt) / 2));
+ const stepLen = (b.speed * dt) / steps;
+ for (let i = 0; i < steps && b.active; i += 1) {
+ b.y += stepLen;
+ const tip = b.y + 6;
+ if (tip >= GROUND_Y) {
+ b.active = false;
+ emitBurst(state.particles, b.x, GROUND_Y - 1, 4, 25, "#c58bff", random, 0.3);
+ break;
+ }
+ if (hitBunker(state, b.x, tip, true, random)) { b.active = false; break; }
+ if (state.phase === "play" && b.x >= state.px && b.x < state.px + PLAYER_W && tip >= PLAYER_Y + 2 && b.y < PLAYER_Y + PLAYER_H) {
+ b.active = false;
+ killPlayer(state, random);
+ return;
+ }
+ }
+ }
+}
+
+function step(state: RaidersState, input: RetroInput, dt: number, random: () => number): void {
+ if (state.phase === "over") {
+ stepParticles(state.particles, dt, 40);
+ return;
+ }
+ state.elapsed += dt;
+ state.shake = Math.max(0, state.shake - dt);
+ stepParticles(state.particles, dt, 40);
+ for (const b of state.bursts) if (b.active && (b.t -= dt) <= 0) b.active = false;
+ for (const p of state.popups) if (p.active && (p.t -= dt) <= 0) p.active = false;
+
+ if (state.phase === "dying") {
+ state.timer -= dt;
+ if (state.timer <= 0) {
+ if (state.lives <= 0) {
+ state.phase = "over";
+ } else {
+ state.phase = "play";
+ state.px = PLAYER_START_X;
+ state.cooldown = 0.4;
+ state.fireTimer = Math.max(state.fireTimer, 1);
+ }
+ }
+ return;
+ }
+ if (state.phase === "clear") {
+ stepShots(state, dt, random);
+ state.timer -= dt;
+ if (state.timer <= 0) {
+ state.wave += 1;
+ state.phase = "play";
+ startWave(state, random);
+ }
+ return;
+ }
+
+ // The cannon.
+ const move = (input.right ? 1 : 0) - (input.left ? 1 : 0);
+ state.px = clamp(state.px + move * PLAYER_SPEED * dt, 4, WIDTH - 4 - PLAYER_W);
+ state.cooldown -= dt;
+ // A tap shorter than one frame still fires: the press edge counts like a held button.
+ if ((input.a || input.pressed.a) && state.cooldown <= 0) {
+ const shot = state.shots.find((s) => !s.active);
+ if (shot) {
+ shot.active = true;
+ shot.x = Math.round(state.px) + 6;
+ shot.y = PLAYER_Y - 1;
+ state.cooldown = SHOT_COOLDOWN;
+ }
+ }
+ stepShots(state, dt, random);
+ if (state.phase !== "play") return;
+
+ // The formation.
+ state.stepTimer -= dt;
+ if (state.stepTimer <= 0) {
+ march(state, random);
+ state.stepTimer = stepDelay(state.aliveCount, state.wave);
+ if (state.phase !== "play") return;
+ }
+ state.fireTimer -= dt;
+ if (state.fireTimer <= 0) {
+ alienFire(state, random);
+ state.fireTimer = (0.45 + random() * 0.9) * Math.max(0.45, 1 - 0.08 * (state.wave - 1));
+ }
+ stepBombs(state, dt, random);
+ if (state.phase !== "play") return;
+
+ // The bonus saucer.
+ const s = state.saucer;
+ if (s.active) {
+ s.x += s.dir * SAUCER_SPEED * dt;
+ if (s.x < -SAUCER_W - 2 || s.x > WIDTH + 2) s.active = false;
+ } else {
+ state.saucerTimer -= dt;
+ if (state.saucerTimer <= 0 && state.aliveCount >= 8) {
+ s.active = true;
+ s.dir = random() < 0.5 ? 1 : -1;
+ s.x = s.dir > 0 ? -SAUCER_W : WIDTH;
+ s.points = SAUCER_POINTS[Math.floor(random() * SAUCER_POINTS.length)];
+ state.saucerTimer = 16 + random() * 14;
+ }
+ }
+}
+
+function status(state: RaidersState): RetroStatus {
+ return { score: state.score, lives: state.lives, level: state.wave, over: state.phase === "over" };
+}
+
+const STARS = starField(40, WIDTH, 200, 7);
+
+function draw(ctx: CanvasRenderingContext2D, state: RaidersState, info: RetroDrawInfo): void {
+ ctx.fillStyle = "#05030f";
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
+ drawStars(ctx, STARS, info.time, info.reduced);
+
+ ctx.save();
+ if (state.shake > 0 && !info.reduced) {
+ ctx.translate(Math.round(Math.sin(info.time * 83) * state.shake * 5), Math.round(Math.cos(info.time * 71) * state.shake * 3));
+ }
+
+ // Before the first step the formation shuffles gently on the title screen.
+ const frame = info.idle && state.elapsed === 0 ? Math.floor(info.time * 1.6) % 2 : state.frame;
+ for (let r = 0; r < ROWS; r += 1) {
+ const kind = ROW_KIND[r];
+ ctx.fillStyle = KIND_COLOR[kind];
+ const spr = ALIEN_SPRITES[kind][frame];
+ for (let c = 0; c < COLS; c += 1) {
+ if (state.alive[r * COLS + c]) drawSprite(ctx, spr, alienX(state, r, c), alienY(state, r));
+ }
+ }
+ for (const b of state.bursts) {
+ if (!b.active) continue;
+ ctx.fillStyle = b.color;
+ drawSprite(ctx, BURST_SPRITE, b.x - 5, b.y - 3);
+ }
+
+ const s = state.saucer;
+ if (s.active) {
+ ctx.fillStyle = "#ff4f6d";
+ drawSprite(ctx, SAUCER_SPRITE, s.x, SAUCER_Y);
+ // Running lights travel along the rim (held still under reduced motion).
+ ctx.fillStyle = "#fff3a8";
+ const lit = info.reduced ? 0 : Math.floor(info.time * 8) % 5;
+ for (let i = 0; i < 5; i += 1) if (i === lit || info.reduced) ctx.fillRect(Math.round(s.x) + 1 + i * 3, SAUCER_Y + 3, 1, 1);
+ }
+ ctx.fillStyle = "#ffd35a";
+ for (const p of state.popups) {
+ if (p.active) drawNumber(ctx, p.value, p.x, p.y + (info.reduced ? 0 : -(1.2 - p.t) * 6), 1, "center");
+ }
+
+ ctx.fillStyle = "#4dff88";
+ for (let b = 0; b < BUNKER_COUNT; b += 1) {
+ for (let r = 0; r < BUNKER_ROWS; r += 1) {
+ for (let c = 0; c < BUNKER_COLS; c += 1) {
+ if (state.bunkers[(b * BUNKER_ROWS + r) * BUNKER_COLS + c]) {
+ ctx.fillRect(BUNKER_X[b] + c * BUNKER_CELL, BUNKER_Y + r * BUNKER_CELL, BUNKER_CELL, BUNKER_CELL);
+ }
+ }
+ }
+ }
+
+ if (state.phase === "dying") {
+ // The wreck smoulders between two frames; under reduced motion it holds still.
+ ctx.fillStyle = "#63f3ff";
+ drawSprite(ctx, WRECK_SPRITES[info.reduced ? 0 : Math.floor(info.time * 6) % 2], state.px, PLAYER_Y);
+ } else if (state.phase !== "over") {
+ ctx.fillStyle = "#63f3ff";
+ drawSprite(ctx, PLAYER_SPRITE, state.px, PLAYER_Y);
+ }
+
+ ctx.fillStyle = "#ffffff";
+ for (const shot of state.shots) if (shot.active) ctx.fillRect(shot.x, Math.round(shot.y), 1, 5);
+ for (const b of state.bombs) {
+ if (!b.active) continue;
+ const y = Math.round(b.y);
+ if (b.kind === 1) {
+ ctx.fillStyle = "#ffd35a";
+ const phase = Math.floor(y / 3) % 2;
+ for (let i = 0; i < 7; i += 1) ctx.fillRect(b.x - 1 + ((i + phase) % 2) * 2, y + i, 1, 1);
+ } else if (b.kind === 2) {
+ ctx.fillStyle = "#ff7a5a";
+ ctx.fillRect(b.x, y, 1, 7);
+ ctx.fillRect(b.x - 1, y + 4, 3, 1);
+ } else {
+ ctx.fillStyle = "#f0e6ff";
+ ctx.fillRect(b.x, y, 1, 6);
+ ctx.fillRect(b.x - 1, y + 1 + (Math.floor(y / 4) % 2) * 3, 3, 1);
+ }
+ }
+ drawParticles(ctx, state.particles);
+ ctx.restore();
+
+ // Ground, score, wave and spare cannons.
+ ctx.fillStyle = "#5c3dff";
+ ctx.fillRect(0, GROUND_Y, WIDTH, 1);
+ ctx.fillStyle = "#e9e4ff";
+ drawNumber(ctx, state.score, 6, 5, 2);
+ ctx.fillStyle = "#c58bff";
+ drawNumber(ctx, state.wave, WIDTH - 6, 5, 2, "right");
+ ctx.fillStyle = "#63f3ff";
+ for (let i = 0; i < Math.min(state.lives, MAX_LIVES); i += 1) drawSprite(ctx, LIFE_SPRITE, 6 + i * 10, GROUND_Y + 10);
+
+ if (state.phase === "clear") {
+ // The coming wave's number, large, while the field resets.
+ ctx.fillStyle = "#c58bff";
+ drawNumber(ctx, state.wave + 1, WIDTH / 2, 110, 5, "center");
+ }
+}
+
+const pixelRaiders: RetroGame<RaidersState> = {
+ id: "pixel-raiders",
+ width: WIDTH,
+ height: HEIGHT,
+ create,
+ step,
+ draw,
+ status,
+};
+
+export default pixelRaiders;
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/roadHopper.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/roadHopper.test.ts
new file mode 100644
index 0000000000..37b39c9423
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/roadHopper.test.ts
@@ -0,0 +1,263 @@
+import { describe, expect, it } from "vitest";
+import { idleInput, RETRO_STEP, seededRandom, type RetroButtons, type RetroInput } from "../retroGame";
+import game, {
+ BAY_X, CELL, HOME_ROW, LANES, LIFE_TIME, START_ROW, START_X,
+ diveState, itemX, levelFactor, platformAt, vehicleAt, type HopperState,
+} from "./roadHopper";
+
+const rnd = seededRandom(11);
+const run = (s: HopperState, input: RetroInput, seconds: number) => {
+ for (let t = 0; t < seconds; t += RETRO_STEP) game.step(s, input, RETRO_STEP, rnd);
+};
+/** One frame with `dir` going down (an edge), as the overlay reports a fresh key press. */
+const press = (dir: keyof RetroButtons): RetroInput => {
+ const input = idleInput();
+ input[dir] = true;
+ input.pressed[dir] = true;
+ return input;
+};
+const hold = (dir: keyof RetroButtons): RetroInput => ({ ...idleInput(), [dir]: true });
+const laneOf = (row: number) => LANES.findIndex((l) => l.row === row);
+/** Scroll lane `lane` so its first item's left edge sits at `x`, and return that item's length. */
+const parkItem = (s: HopperState, lane: number, x: number): number => {
+ let shift = 0;
+ while (Math.round(itemX(lane, 0, shift)) !== x) shift += 1;
+ s.shifts[lane] = shift;
+ return LANES[lane].lens[0];
+};
+const fresh = (): HopperState => {
+ const s = game.create(seededRandom(5));
+ s.flyTimer = 999;
+ return s;
+};
+
+function fakeContext(): { ctx: CanvasRenderingContext2D; depth: () => number; rects: () => number } {
+ let depth = 0, rects = 0;
+ const finite = (...v: number[]) => {
+ if (!v.every(Number.isFinite)) throw new Error(`non-finite draw arguments ${v.join(",")}`);
+ };
+ const noop = () => {};
+ const ctx = {
+ fillStyle: "", strokeStyle: "", lineWidth: 1, globalAlpha: 1, lineCap: "butt",
+ fillRect: (x: number, y: number, w: number, h: number) => { finite(x, y, w, h); rects += 1; },
+ strokeRect: (x: number, y: number, w: number, h: number) => finite(x, y, w, h),
+ beginPath: noop, closePath: noop, fill: noop, stroke: noop,
+ moveTo: (x: number, y: number) => finite(x, y),
+ lineTo: (x: number, y: number) => finite(x, y),
+ arc: (x: number, y: number, r: number) => { finite(x, y, r); if (r < 0) throw new Error("negative radius"); },
+ translate: (x: number, y: number) => finite(x, y),
+ save: () => { depth += 1; },
+ restore: () => { depth -= 1; },
+ };
+ return { ctx: ctx as unknown as CanvasRenderingContext2D, depth: () => depth, rects: () => rects };
+}
+
+describe("road hopper", () => {
+ it("starts on the bottom bank with three lives and a full clock", () => {
+ const s = fresh();
+ expect(game.status(s)).toEqual({ score: 0, lives: 3, level: 1, over: false });
+ expect([s.x, s.row, s.timeLeft]).toEqual([START_X, START_ROW, LIFE_TIME]);
+ expect(Array.from(s.bays)).toEqual([0, 0, 0, 0, 0]);
+ });
+
+ it("hops one cell per press; holding the key does not keep hopping", () => {
+ const s = fresh();
+ game.step(s, press("left"), RETRO_STEP, rnd);
+ run(s, hold("left"), 1);
+ expect(s.x).toBe(START_X - CELL);
+ run(s, hold("right"), 1);
+ expect(s.x).toBe(START_X - CELL);
+ expect(s.row).toBe(START_ROW);
+ });
+
+ it("animates a hop and takes a press made mid-hop right after landing", () => {
+ const s = fresh();
+ game.step(s, press("right"), RETRO_STEP, rnd);
+ expect(s.hop.active).toBe(true);
+ game.step(s, idleInput(), RETRO_STEP, rnd);
+ game.step(s, press("right"), RETRO_STEP, rnd);
+ run(s, idleInput(), 0.5);
+ expect(s.x).toBe(START_X + 2 * CELL);
+ });
+
+ it("a vehicle squashes the frog", () => {
+ const s = fresh();
+ const row = 10, lane = laneOf(row);
+ parkItem(s, lane, 100);
+ s.row = row;
+ s.x = 108;
+ expect(vehicleAt(s, row, s.x)).toBe(true);
+ game.step(s, idleInput(), RETRO_STEP, rnd);
+ expect(s.phase).toBe("dying");
+ expect(s.deathKind).toBe("splat");
+ expect(s.lives).toBe(2);
+ run(s, idleInput(), 1.5);
+ expect([s.phase, s.row, s.x]).toEqual(["play", START_ROW, START_X]);
+ });
+
+ it("a log carries the frog along", () => {
+ const s = fresh();
+ const row = 4, lane = laneOf(row);
+ const len = parkItem(s, lane, 60);
+ s.row = row;
+ s.x = 60 + len / 2;
+ run(s, idleInput(), 0.5);
+ expect(s.phase).toBe("play");
+ // Half a second of drift, give or take the last frame.
+ expect(Math.abs(s.x - (60 + len / 2) - LANES[lane].speed * 0.5)).toBeLessThan(2);
+ });
+
+ it("open water drowns the frog", () => {
+ const s = fresh();
+ const row = 2;
+ let x = 20;
+ while (platformAt(s, row, x)) x += 4;
+ s.row = row;
+ s.x = x;
+ game.step(s, idleInput(), RETRO_STEP, rnd);
+ expect(s.phase).toBe("dying");
+ expect(s.deathKind).toBe("splash");
+ });
+
+ it("a diving turtle drops the frog in the water", () => {
+ const s = fresh();
+ const row = 3, lane = laneOf(row);
+ // Group 1 of this lane dives; find a moment it is under.
+ let clock = 0;
+ while (diveState(lane, 1, clock) !== 2) clock += 0.1;
+ s.diveClock = clock;
+ s.row = row;
+ const x0 = itemX(lane, 1, s.shifts[lane]);
+ s.x = x0 + 16;
+ game.step(s, idleInput(), RETRO_STEP, rnd);
+ expect(s.phase).toBe("dying");
+ });
+
+ it("being carried off the edge costs a life", () => {
+ const s = fresh();
+ const row = 2, lane = laneOf(row);
+ parkItem(s, lane, 180);
+ s.row = row;
+ s.x = 214;
+ run(s, idleInput(), 1);
+ expect(s.phase).toBe("dying");
+ expect(s.lives).toBe(2);
+ });
+
+ it("filling a bay scores the time left and sends a new frog", () => {
+ const s = fresh();
+ s.row = 2;
+ s.x = BAY_X[0];
+ game.step(s, press("up"), RETRO_STEP, rnd);
+ run(s, idleInput(), 0.2);
+ expect(s.bays[0]).toBe(1);
+ expect(s.score).toBeGreaterThanOrEqual(50 + 10 * 29);
+ expect([s.row, s.x, s.phase]).toEqual([START_ROW, START_X, "play"]);
+ });
+
+ it("the hedge between bays and a filled bay both kill", () => {
+ const s = fresh();
+ s.row = 2;
+ s.x = (BAY_X[0] + BAY_X[1]) / 2;
+ game.step(s, press("up"), RETRO_STEP, rnd);
+ run(s, idleInput(), 0.2);
+ expect(s.phase).toBe("dying");
+ expect(s.row).toBe(HOME_ROW);
+
+ const t = fresh();
+ t.bays[2] = 1;
+ t.row = 2;
+ t.x = BAY_X[2];
+ game.step(t, press("up"), RETRO_STEP, rnd);
+ run(t, idleInput(), 0.2);
+ expect(t.phase).toBe("dying");
+ });
+
+ it("a fly in a bay is worth a bonus", () => {
+ const s = fresh();
+ s.flyBay = 1;
+ s.flyLeft = 5;
+ s.row = 2;
+ s.x = BAY_X[1];
+ game.step(s, press("up"), RETRO_STEP, rnd);
+ run(s, idleInput(), 0.2);
+ expect(s.score).toBeGreaterThanOrEqual(50 + 200 + 10 * 29);
+ expect(s.flyBay).toBe(-1);
+ });
+
+ it("filling all five bays starts a faster level", () => {
+ const s = fresh();
+ s.bays.set([1, 1, 1, 1, 0]);
+ s.row = 2;
+ s.x = BAY_X[4];
+ game.step(s, press("up"), RETRO_STEP, rnd);
+ run(s, idleInput(), 0.2);
+ expect(s.phase).toBe("levelup");
+ expect(s.score).toBeGreaterThanOrEqual(1000);
+ run(s, idleInput(), 2.5);
+ expect(game.status(s).level).toBe(2);
+ expect(Array.from(s.bays)).toEqual([0, 0, 0, 0, 0]);
+ expect(levelFactor(2)).toBeGreaterThan(levelFactor(1));
+ });
+
+ it("the clock running out costs a life", () => {
+ const s = fresh();
+ run(s, idleInput(), LIFE_TIME - 1);
+ expect(s.phase).toBe("play");
+ run(s, idleInput(), 1.5);
+ expect(s.phase).toBe("dying");
+ expect(s.deathKind).toBe("time");
+ expect(s.lives).toBe(2);
+ });
+
+ it("the last life ends the run", () => {
+ const s = fresh();
+ s.lives = 1;
+ run(s, idleInput(), LIFE_TIME + 2);
+ expect(game.status(s)).toMatchObject({ lives: 0, over: true });
+ });
+
+ it("forward hops score once per new row", () => {
+ const s = fresh();
+ s.row = 7; // the middle bank
+ s.bestRow = 7;
+ game.step(s, press("down"), RETRO_STEP, rnd);
+ run(s, idleInput(), 0.15);
+ expect(s.score).toBe(0);
+
+ const t = fresh();
+ game.step(t, press("up"), RETRO_STEP, rnd);
+ run(t, idleInput(), 0.15);
+ expect(t.score).toBe(10);
+ });
+
+ it("draws every phase without throwing, idle and reduced included", () => {
+ const s = game.create(seededRandom(9));
+ for (const info of [
+ { time: 0, reduced: false, idle: true },
+ { time: 4.2, reduced: true, idle: true },
+ { time: 1, reduced: false, idle: false },
+ ]) {
+ const fake = fakeContext();
+ game.draw(fake.ctx, s, info);
+ expect(fake.depth()).toBe(0);
+ expect(fake.rects()).toBeGreaterThan(100);
+ }
+ s.bays.set([1, 0, 1, 0, 0]);
+ s.flyBay = 3;
+ game.step(s, press("left"), RETRO_STEP, rnd);
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: false, idle: false });
+ s.timeLeft = 3;
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: true, idle: false });
+ for (const kind of ["splat", "splash", "time"] as const) {
+ s.phase = "dying";
+ s.deathKind = kind;
+ s.timer = 0.5;
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: false, idle: false });
+ }
+ s.phase = "levelup";
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: false, idle: false });
+ s.phase = "over";
+ game.draw(fakeContext().ctx, s, { time: 2, reduced: true, idle: false });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/games/roadHopper.ts b/jarvis/ui/web/frontend/src/components/society/arcade/games/roadHopper.ts
new file mode 100644
index 0000000000..6decb5e52f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/games/roadHopper.ts
@@ -0,0 +1,639 @@
+/**
+ * "Road Hopper": hop a little frog across five lanes of traffic and a river
+ * to the five home bays in the hedge at the top. One hop per press (holding a
+ * direction does not keep hopping). On the river only logs and turtles carry
+ * you; the water, a diving turtle or being carried off the edge cost a life,
+ * and so does the clock running out. Filling all five bays starts the next
+ * level with faster lanes.
+ *
+ * The lanes never store moving objects: each lane is a fixed pattern of
+ * items plus one scrolling `shift`, so the world costs no allocations.
+ */
+import type { RetroDrawInfo, RetroGame, RetroInput, RetroStatus } from "../retroGame";
+import {
+ clamp, drawNumber, drawParticles, drawSprite, emitBurst, makeParticles, sprite, stepParticles,
+ type Particle, type PixelSprite,
+} from "./games3Kit";
+
+export const WIDTH = 224;
+export const HEIGHT = 256;
+export const CELL = 16;
+
+export const HOME_ROW = 1;
+export const START_ROW = 13;
+export const START_X = WIDTH / 2;
+/** Rows 2–6 are river, row 7 the middle bank, rows 8–12 road. */
+export const RIVER_TOP = 2;
+export const RIVER_BOTTOM = 6;
+export const ROAD_TOP = 8;
+export const ROAD_BOTTOM = 12;
+
+export const HOP_S = 0.1;
+export const LIFE_TIME = 30;
+const DEATH_S = 1.2;
+const LEVEL_S = 2;
+/** Half the frog's width for traffic; a river platform must hold its centre. */
+const FROG_HALF = 6;
+export const BAY_X: readonly number[] = [24, 68, 112, 156, 200];
+/** How far off a bay's centre a landing still counts. */
+const BAY_CATCH = 9;
+const FLY_BONUS = 200;
+const BAY_POINTS = 50;
+const LEVEL_POINTS = 1000;
+/** Items are placed so they start fully off the left edge; any item is at most this long. */
+const MARGIN = 96;
+
+export type LaneKind = "log" | "turtle" | "truck" | "car" | "racer" | "dozer";
+
+export interface LaneDef {
+ row: number;
+ kind: LaneKind;
+ /** Pixels per second at level 1; positive moves right. */
+ speed: number;
+ /** Length of one repeat of the pattern; must be at least WIDTH + MARGIN. */
+ period: number;
+ offsets: readonly number[];
+ lens: readonly number[];
+ /** Turtle groups that dive now and then. */
+ dives?: readonly boolean[];
+}
+
+export const LANES: readonly LaneDef[] = [
+ { row: 2, kind: "log", speed: 34, period: 336, offsets: [0, 112, 224], lens: [64, 64, 64] },
+ { row: 3, kind: "turtle", speed: -40, period: 320, offsets: [0, 80, 160, 240], lens: [32, 32, 32, 32], dives: [false, true, false, false] },
+ { row: 4, kind: "log", speed: 52, period: 400, offsets: [0, 200], lens: [96, 96] },
+ { row: 5, kind: "log", speed: 28, period: 336, offsets: [0, 112, 224], lens: [48, 48, 48] },
+ { row: 6, kind: "turtle", speed: -32, period: 336, offsets: [0, 112, 224], lens: [48, 48, 48], dives: [false, false, true] },
+ { row: 8, kind: "truck", speed: -30, period: 336, offsets: [0, 168], lens: [32, 32] },
+ { row: 9, kind: "racer", speed: 72, period: 336, offsets: [0, 168], lens: [16, 16] },
+ { row: 10, kind: "car", speed: -40, period: 336, offsets: [0, 112, 224], lens: [16, 16, 16] },
+ { row: 11, kind: "dozer", speed: 28, period: 336, offsets: [0, 112, 224], lens: [16, 16, 16] },
+ { row: 12, kind: "car", speed: -34, period: 320, offsets: [0, 80, 160, 240], lens: [16, 16, 16, 16] },
+];
+const LANE_OF_ROW: readonly number[] = Array.from({ length: 16 }, (_, row) => LANES.findIndex((l) => l.row === row));
+
+/** Turtle dive cycle in seconds, and when (within it) a diving group sinks, is under, and comes back. */
+const DIVE_CYCLE = 5;
+const DIVE_SINK = 3;
+const DIVE_UNDER = 3.6;
+const DIVE_RISE = 4.8;
+
+export type HopperPhase = "play" | "dying" | "levelup" | "over";
+export type Direction = 0 | 1 | 2 | 3; // up, right, down, left
+export type DeathKind = "splat" | "splash" | "time";
+
+export interface Hop { active: boolean; t: number; fromX: number; fromRow: number; toX: number; toRow: number }
+interface Popup { active: boolean; x: number; y: number; t: number; value: number }
+
+export interface HopperState {
+ phase: HopperPhase;
+ timer: number;
+ /** Total seconds simulated; zero means the run has not started (attract screen). */
+ elapsed: number;
+ score: number;
+ lives: number;
+ level: number;
+ /** The frog's centre x in pixels and its row. */
+ x: number;
+ row: number;
+ facing: Direction;
+ hop: Hop;
+ /** A direction pressed during a hop, taken as soon as the frog lands; -1 for none. */
+ queued: number;
+ /** The highest row (smallest index) reached by this frog; new rows score. */
+ bestRow: number;
+ timeLeft: number;
+ bays: Uint8Array;
+ flyBay: number;
+ flyLeft: number;
+ flyTimer: number;
+ /** Scroll of each lane's pattern, parallel to LANES. */
+ shifts: number[];
+ diveClock: number;
+ deathKind: DeathKind;
+ particles: Particle[];
+ popups: Popup[];
+}
+
+/** Lane speeds grow 20 % per level, up to a little over double. */
+export function levelFactor(level: number): number {
+ return Math.min(2.2, 1 + 0.2 * (level - 1));
+}
+
+function mod(a: number, m: number): number {
+ return ((a % m) + m) % m;
+}
+
+/** Left edge of item `i` of lane `lane` for a given scroll. */
+export function itemX(lane: number, i: number, shift: number): number {
+ const def = LANES[lane];
+ return mod(def.offsets[i] + shift, def.period) - MARGIN;
+}
+
+/** 0 surfaced, 1 sinking or rising (still rideable), 2 under water. */
+export function diveState(lane: number, i: number, clock: number): 0 | 1 | 2 {
+ if (!LANES[lane].dives?.[i]) return 0;
+ const t = mod(clock + i * 1.3, DIVE_CYCLE);
+ return t < DIVE_SINK ? 0 : t < DIVE_UNDER ? 1 : t < DIVE_RISE ? 2 : 1;
+}
+
+/** Whether a frog centred at x on a river row stands on something that floats. */
+export function platformAt(state: HopperState, row: number, x: number): boolean {
+ const lane = LANE_OF_ROW[row];
+ if (lane < 0) return false;
+ const def = LANES[lane];
+ for (let i = 0; i < def.offsets.length; i += 1) {
+ const x0 = itemX(lane, i, state.shifts[lane]);
+ if (x >= x0 + 1 && x <= x0 + def.lens[i] - 1 && diveState(lane, i, state.diveClock) !== 2) return true;
+ }
+ return false;
+}
+
+/** Whether a frog centred at x on a road row touches a vehicle. */
+export function vehicleAt(state: HopperState, row: number, x: number): boolean {
+ const lane = LANE_OF_ROW[row];
+ if (lane < 0) return false;
+ const def = LANES[lane];
+ for (let i = 0; i < def.offsets.length; i += 1) {
+ const x0 = itemX(lane, i, state.shifts[lane]);
+ if (x + FROG_HALF > x0 + 1 && x - FROG_HALF < x0 + def.lens[i] - 1) return true;
+ }
+ return false;
+}
+
+export function isRiver(row: number): boolean {
+ return row >= RIVER_TOP && row <= RIVER_BOTTOM;
+}
+
+function isRoad(row: number): boolean {
+ return row >= ROAD_TOP && row <= ROAD_BOTTOM;
+}
+
+function respawn(state: HopperState): void {
+ state.phase = "play";
+ state.x = START_X;
+ state.row = START_ROW;
+ state.facing = 0;
+ state.hop.active = false;
+ state.queued = -1;
+ state.bestRow = START_ROW;
+ state.timeLeft = LIFE_TIME;
+}
+
+function create(random: () => number): HopperState {
+ const state: HopperState = {
+ phase: "play", timer: 0, elapsed: 0, score: 0, lives: 3, level: 1,
+ x: START_X, row: START_ROW, facing: 0,
+ hop: { active: false, t: 0, fromX: 0, fromRow: 0, toX: 0, toRow: 0 },
+ queued: -1, bestRow: START_ROW, timeLeft: LIFE_TIME,
+ bays: new Uint8Array(5), flyBay: -1, flyLeft: 0, flyTimer: 6 + random() * 5,
+ shifts: LANES.map((l) => Math.floor(random() * l.period)),
+ diveClock: 0, deathKind: "splat",
+ particles: makeParticles(80),
+ popups: Array.from({ length: 3 }, () => ({ active: false, x: 0, y: 0, t: 0, value: 0 })),
+ };
+ respawn(state);
+ return state;
+}
+
+function popup(state: HopperState, x: number, y: number, value: number): void {
+ const p = state.popups.find((q) => !q.active) ?? state.popups[0];
+ p.active = true; p.x = x; p.y = y; p.t = 1.2; p.value = value;
+}
+
+function die(state: HopperState, kind: DeathKind, random: () => number): void {
+ state.phase = "dying";
+ state.timer = DEATH_S;
+ state.deathKind = kind;
+ state.lives = Math.max(0, state.lives - 1);
+ state.hop.active = false;
+ state.queued = -1;
+ const cy = state.row * CELL + CELL / 2;
+ if (kind === "splash") emitBurst(state.particles, state.x, cy, 16, 50, "#9fd8ff", random, 0.7);
+ else emitBurst(state.particles, state.x, cy, 14, 45, "#7ed957", random, 0.6);
+}
+
+function startHop(state: HopperState, dir: Direction): void {
+ state.facing = dir;
+ let toRow = state.row, toX = state.x;
+ if (dir === 0) toRow = Math.max(HOME_ROW, state.row - 1);
+ else if (dir === 2) toRow = Math.min(START_ROW, state.row + 1);
+ else toX = state.x + (dir === 1 ? CELL : -CELL);
+ // On land the frog stays on screen; on the river the current may carry it off.
+ if (!isRiver(state.row)) toX = clamp(toX, CELL / 2, WIDTH - CELL / 2);
+ if (toRow === state.row && toX === state.x) return;
+ const h = state.hop;
+ h.active = true; h.t = 0; h.fromX = state.x; h.fromRow = state.row; h.toX = toX; h.toRow = toRow;
+}
+
+function pressedDirection(input: RetroInput): number {
+ const p = input.pressed;
+ return p.up ? 0 : p.right ? 1 : p.down ? 2 : p.left ? 3 : -1;
+}
+
+/** Arrive in a bay: fill it (with any fly bonus), or die against the hedge or a full bay. */
+function reachHome(state: HopperState, random: () => number): void {
+ const bay = BAY_X.findIndex((bx) => Math.abs(state.x - bx) <= BAY_CATCH);
+ if (bay < 0 || state.bays[bay]) {
+ die(state, "splat", random);
+ return;
+ }
+ state.bays[bay] = 1;
+ let points = BAY_POINTS + 10 * Math.floor(state.timeLeft);
+ if (state.flyBay === bay) {
+ points += FLY_BONUS;
+ state.flyBay = -1;
+ state.flyTimer = 6 + random() * 6;
+ }
+ state.score += points;
+ popup(state, BAY_X[bay], HOME_ROW * CELL + 2, points);
+ emitBurst(state.particles, BAY_X[bay], HOME_ROW * CELL + 8, 12, 40, "#ffe66b", random, 0.6);
+ if (state.bays.every((b) => b === 1)) {
+ state.score += LEVEL_POINTS;
+ state.phase = "levelup";
+ state.timer = LEVEL_S;
+ state.hop.active = false;
+ state.flyBay = -1;
+ } else {
+ respawn(state);
+ }
+}
+
+/** The frog sits on `row` at `x`: is it alive? Returns false after killing it. */
+function survives(state: HopperState, random: () => number): boolean {
+ if (isRoad(state.row) && vehicleAt(state, state.row, state.x)) {
+ die(state, "splat", random);
+ return false;
+ }
+ if (isRiver(state.row)) {
+ if (state.x < 2 || state.x > WIDTH - 2) {
+ die(state, "splash", random);
+ return false;
+ }
+ if (!platformAt(state, state.row, state.x)) {
+ die(state, "splash", random);
+ return false;
+ }
+ }
+ return true;
+}
+
+function land(state: HopperState, random: () => number): void {
+ const h = state.hop;
+ h.active = false;
+ state.x = h.toX;
+ state.row = h.toRow;
+ if (state.row < state.bestRow) {
+ state.score += 10 * (state.bestRow - state.row);
+ state.bestRow = state.row;
+ }
+ if (state.row === HOME_ROW) {
+ reachHome(state, random);
+ return;
+ }
+ if (!survives(state, random)) return;
+ if (state.queued >= 0) {
+ const dir = state.queued as Direction;
+ state.queued = -1;
+ startHop(state, dir);
+ }
+}
+
+function laneSpeed(lane: number, level: number): number {
+ return LANES[lane].speed * levelFactor(level);
+}
+
+function step(state: HopperState, input: RetroInput, dt: number, random: () => number): void {
+ stepParticles(state.particles, dt, 30);
+ if (state.phase === "over") return;
+ state.elapsed += dt;
+ state.diveClock += dt;
+ for (let i = 0; i < LANES.length; i += 1) state.shifts[i] = mod(state.shifts[i] + laneSpeed(i, state.level) * dt, LANES[i].period);
+ for (const p of state.popups) if (p.active && (p.t -= dt) <= 0) p.active = false;
+
+ if (state.phase === "dying") {
+ state.timer -= dt;
+ if (state.timer <= 0) {
+ if (state.lives <= 0) state.phase = "over";
+ else respawn(state);
+ }
+ return;
+ }
+ if (state.phase === "levelup") {
+ state.timer -= dt;
+ if (state.timer <= 0) {
+ state.level += 1;
+ state.bays.fill(0);
+ state.flyTimer = 6 + random() * 5;
+ respawn(state);
+ }
+ return;
+ }
+
+ // The fly visits empty bays now and then.
+ if (state.flyBay >= 0) {
+ state.flyLeft -= dt;
+ if (state.flyLeft <= 0) {
+ state.flyBay = -1;
+ state.flyTimer = 6 + random() * 6;
+ }
+ } else if ((state.flyTimer -= dt) <= 0) {
+ let empty = 0;
+ for (const b of state.bays) if (!b) empty += 1;
+ let pick = Math.floor(random() * empty);
+ for (let i = 0; i < 5 && empty > 0; i += 1) {
+ if (!state.bays[i] && pick-- === 0) { state.flyBay = i; state.flyLeft = 4.5; }
+ }
+ state.flyTimer = 6 + random() * 6;
+ }
+
+ state.timeLeft -= dt;
+ if (state.timeLeft <= 0) {
+ state.timeLeft = 0;
+ die(state, "time", random);
+ return;
+ }
+
+ const dir = pressedDirection(input);
+ const h = state.hop;
+ if (h.active) {
+ if (dir >= 0) state.queued = dir;
+ // A hop that starts on the river keeps drifting with what it left.
+ if (isRiver(h.fromRow)) {
+ const drift = laneSpeed(LANE_OF_ROW[h.fromRow], state.level) * dt;
+ h.fromX += drift;
+ h.toX += drift;
+ }
+ h.t += dt;
+ if (h.t >= HOP_S) land(state, random);
+ return;
+ }
+ if (dir >= 0) {
+ startHop(state, dir as Direction);
+ if (h.active) return;
+ }
+ // Sitting still: the river carries the frog; traffic or water may end it.
+ if (isRiver(state.row)) state.x += laneSpeed(LANE_OF_ROW[state.row], state.level) * dt;
+ survives(state, random);
+}
+
+function status(state: HopperState): RetroStatus {
+ return { score: state.score, lives: state.lives, level: state.level, over: state.phase === "over" };
+}
+
+// ---- Drawing --------------------------------------------------------------
+
+/** Rotate a square bitmap a quarter turn clockwise `turns` times. */
+function rotateRows(rows: readonly string[], turns: number): string[] {
+ let out = rows.slice();
+ for (let t = 0; t < turns; t += 1) {
+ const n = out.length;
+ const next: string[] = [];
+ for (let y = 0; y < n; y += 1) {
+ let line = "";
+ for (let x = 0; x < n; x += 1) line += out[n - 1 - x][y];
+ next.push(line);
+ }
+ out = next;
+ }
+ return out;
+}
+
+const FROG_SIT = [
+ ".###....###.",
+ ".#.#....#.#.",
+ "..########..",
+ ".##########.",
+ "#.########.#",
+ "#.########.#",
+ "##.######.##",
+ "..########..",
+ ".##.####.##.",
+ "##........##",
+ "#..........#",
+ "............",
+];
+const FROG_LEAP = [
+ "#.###..###.#",
+ "#.#.#..#.#.#",
+ ".#.######.#.",
+ "..########..",
+ "..########..",
+ "...######...",
+ "...######...",
+ "..########..",
+ "..##.##.##..",
+ ".##......##.",
+ ".#........#.",
+ "#..........#",
+];
+/** [direction][0 sitting, 1 leaping]. */
+const FROG: readonly (readonly [PixelSprite, PixelSprite])[] = [0, 1, 2, 3].map(
+ (turns) => [sprite(rotateRows(FROG_SIT, turns)), sprite(rotateRows(FROG_LEAP, turns))] as const,
+);
+const SPLAT = sprite(["#...#..#...#", ".#..####..#.", "..########..", ".##.####.##.", "#.########.#", "..##.##.##..", ".#..#..#..#.", "#..........#"]);
+const FLY = sprite([".#.#.", "#####", ".###.", "..#.."]);
+const CAR = sprite(["..########......", ".##########.....", "################", "################", ".##########.....", "..########......"]);
+const RACER = sprite(["....######......", "..##########....", "################", "################", "..##########....", "....######......"]);
+const DOZER = sprite(["#..#########....", "#.###########...", "#.############..", "#.############..", "#.###########...", "#..#########...."]);
+const LIFE_ICON = sprite([".#..#.", "######", "######", "#....#"]);
+
+const BANK_ROWS = [7, START_ROW] as const;
+const LANE_COLOR: Partial<Record<LaneKind, string>> = { car: "#4fc3ff", racer: "#ff5fb8", dozer: "#ffcc33" };
+
+/** Lane scroll used for drawing: on the attract screen the world drifts on its own. */
+function drawShift(state: HopperState, lane: number, attract: boolean, time: number): number {
+ return attract ? state.shifts[lane] + LANES[lane].speed * time : state.shifts[lane];
+}
+
+function drawVehicle(ctx: CanvasRenderingContext2D, kind: LaneKind, x: number, y: number, len: number, flip: boolean): void {
+ if (kind === "truck") {
+ ctx.fillStyle = "#d9d4c7";
+ ctx.fillRect(x + (flip ? 0 : 8), y + 2, len - 8, 12);
+ ctx.fillStyle = "#e0523d";
+ ctx.fillRect(x + (flip ? len - 8 : 0), y + 3, 8, 10);
+ ctx.fillStyle = "#0b0b12";
+ ctx.fillRect(x + (flip ? len - 5 : 1), y + 4, 3, 8);
+ ctx.fillRect(x + 4, y + 1, 4, 1);
+ ctx.fillRect(x + len - 8, y + 1, 4, 1);
+ ctx.fillRect(x + 4, y + 14, 4, 1);
+ ctx.fillRect(x + len - 8, y + 14, 4, 1);
+ return;
+ }
+ ctx.fillStyle = "#0b0b12";
+ ctx.fillRect(x + 3, y + 1, 3, 14);
+ ctx.fillRect(x + 10, y + 1, 3, 14);
+ ctx.fillStyle = LANE_COLOR[kind] ?? "#fff";
+ drawSprite(ctx, kind === "racer" ? RACER : kind === "dozer" ? DOZER : CAR, x, y + 5, 1, flip);
+ ctx.fillStyle = "#fff8d0";
+ ctx.fillRect(flip ? x : x + len - 1, y + 7, 1, 2);
+}
+
+function draw(ctx: CanvasRenderingContext2D, state: HopperState, info: RetroDrawInfo): void {
+ const attract = info.idle && state.elapsed === 0;
+ const clock = attract ? info.time : state.diveClock;
+ const motion = info.reduced ? 0 : info.time;
+
+ ctx.fillStyle = "#06070d";
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
+
+ // River with drifting ripples.
+ ctx.fillStyle = "#0b2a5c";
+ ctx.fillRect(0, RIVER_TOP * CELL, WIDTH, (RIVER_BOTTOM - RIVER_TOP + 1) * CELL);
+ ctx.fillStyle = "#1d4f96";
+ for (let row = RIVER_TOP; row <= RIVER_BOTTOM; row += 1) {
+ const drift = Math.floor(mod(motion * 6 + row * 13, 32));
+ for (let x = -32 + drift; x < WIDTH; x += 32) ctx.fillRect(x, row * CELL + 5 + (row % 2) * 6, 6, 1);
+ }
+
+ // Hedge and bays.
+ ctx.fillStyle = "#1f5e2b";
+ ctx.fillRect(0, HOME_ROW * CELL - 2, WIDTH, CELL + 2);
+ ctx.fillStyle = "#2f8a3e";
+ for (let x = 0; x < WIDTH; x += 4) ctx.fillRect(x, HOME_ROW * CELL - 2 + (x % 8 === 0 ? 0 : 1), 2, 1);
+ for (let i = 0; i < 5; i += 1) {
+ const bx = BAY_X[i] - 10;
+ ctx.fillStyle = "#0b2a5c";
+ ctx.fillRect(bx, HOME_ROW * CELL, 20, CELL);
+ if (state.bays[i]) {
+ ctx.fillStyle = "#b6f36b";
+ drawSprite(ctx, FROG[2][0], BAY_X[i] - 6, HOME_ROW * CELL + 2);
+ } else if (state.flyBay === i) {
+ ctx.fillStyle = "#ffe66b";
+ const flap = info.reduced ? 0 : Math.floor(info.time * 10) % 2;
+ drawSprite(ctx, FLY, BAY_X[i] - 2, HOME_ROW * CELL + 6 - flap);
+ }
+ }
+
+ // Banks.
+ for (const row of BANK_ROWS) {
+ ctx.fillStyle = "#3d2f6e";
+ ctx.fillRect(0, row * CELL, WIDTH, CELL);
+ ctx.fillStyle = "#56449a";
+ for (let x = 2; x < WIDTH; x += 8) ctx.fillRect(x + (row % 2) * 4, row * CELL + 4, 2, 2);
+ for (let x = 6; x < WIDTH; x += 8) ctx.fillRect(x - (row % 2) * 4, row * CELL + 11, 2, 2);
+ }
+
+ // Road with lane markings.
+ ctx.fillStyle = "#14141c";
+ ctx.fillRect(0, ROAD_TOP * CELL, WIDTH, (ROAD_BOTTOM - ROAD_TOP + 1) * CELL);
+ ctx.fillStyle = "#4b4b5c";
+ for (let row = ROAD_TOP + 1; row <= ROAD_BOTTOM; row += 1) {
+ for (let x = 4; x < WIDTH; x += 16) ctx.fillRect(x, row * CELL, 8, 1);
+ }
+
+ // Lane contents.
+ for (let lane = 0; lane < LANES.length; lane += 1) {
+ const def = LANES[lane];
+ const shift = drawShift(state, lane, attract, info.time);
+ const y = def.row * CELL;
+ for (let i = 0; i < def.offsets.length; i += 1) {
+ const x = Math.round(itemX(lane, i, shift));
+ const len = def.lens[i];
+ if (x >= WIDTH || x + len <= 0) continue;
+ if (def.kind === "log") {
+ ctx.fillStyle = "#8a5a2b";
+ ctx.fillRect(x + 1, y + 2, len - 2, 12);
+ ctx.fillStyle = "#b07a40";
+ ctx.fillRect(x + 1, y + 3, len - 2, 2);
+ ctx.fillStyle = "#5c3a1a";
+ for (let g = x + 6; g < x + len - 6; g += 11) ctx.fillRect(g, y + 8, 5, 1);
+ ctx.fillRect(x + 1, y + 2, 2, 12);
+ ctx.fillStyle = "#d9a86a";
+ ctx.fillRect(x + len - 3, y + 3, 2, 10);
+ } else if (def.kind === "turtle") {
+ const dive = diveState(lane, i, clock);
+ for (let t = 0; t < len; t += CELL) {
+ const tx = x + t;
+ if (dive === 2) {
+ ctx.fillStyle = "#1d4f96";
+ ctx.fillRect(tx + 4, y + 7, 8, 1);
+ continue;
+ }
+ ctx.fillStyle = dive === 1 ? "#6e3a2c" : "#c0463a";
+ ctx.fillRect(tx + 3, y + 3, 10, 10);
+ ctx.fillRect(tx + 2, y + 5, 12, 6);
+ ctx.fillStyle = dive === 1 ? "#4a6a3a" : "#7ed957";
+ ctx.fillRect(def.speed < 0 ? tx : tx + 14, y + 6, 2, 4);
+ ctx.fillStyle = "#e8b04a";
+ ctx.fillRect(tx + 6, y + 6, 4, 4);
+ }
+ } else {
+ drawVehicle(ctx, def.kind, x, y, len, def.speed < 0);
+ }
+ }
+ }
+
+ // The frog, or what is left of it.
+ if (state.phase === "dying") {
+ const cy = state.row * CELL;
+ if (state.deathKind === "splash") {
+ ctx.strokeStyle = "#9fd8ff";
+ ctx.lineWidth = 1;
+ const grow = clamp(1 - state.timer / DEATH_S, 0, 1);
+ for (let ring = 0; ring < 2; ring += 1) {
+ ctx.beginPath();
+ ctx.arc(state.x, cy + CELL / 2, 2 + grow * 8 + ring * 4, 0, Math.PI * 2);
+ ctx.stroke();
+ }
+ } else {
+ ctx.fillStyle = "#7ed957";
+ drawSprite(ctx, SPLAT, state.x - 6, cy + 4);
+ }
+ } else if (state.phase === "play") {
+ const h = state.hop;
+ let fx = state.x, fy = state.row * CELL, leap = 0;
+ if (h.active) {
+ const k = clamp(h.t / HOP_S, 0, 1);
+ fx = h.fromX + (h.toX - h.fromX) * k;
+ fy = (h.fromRow + (h.toRow - h.fromRow) * k) * CELL - (info.reduced ? 0 : Math.sin(k * Math.PI) * 3);
+ leap = 1;
+ }
+ ctx.fillStyle = "#0a1a0a";
+ ctx.fillRect(Math.round(fx) - 4, state.row * CELL + 13, 8, 1);
+ ctx.fillStyle = "#7ed957";
+ drawSprite(ctx, FROG[state.facing][leap], fx - 6, fy + 2);
+ }
+ drawParticles(ctx, state.particles);
+
+ ctx.fillStyle = "#ffe66b";
+ for (const p of state.popups) {
+ if (p.active) drawNumber(ctx, p.value, p.x, p.y - (info.reduced ? 0 : (1.2 - p.t) * 6), 1, "center");
+ }
+
+ // Top: score and level. Bottom: lives and the clock.
+ ctx.fillStyle = "#e9ffe0";
+ drawNumber(ctx, state.score, 6, 4, 2);
+ ctx.fillStyle = "#b6f36b";
+ drawNumber(ctx, state.level, WIDTH - 6, 4, 2, "right");
+ ctx.fillStyle = "#7ed957";
+ for (let i = 0; i < Math.min(state.lives, 6); i += 1) drawSprite(ctx, LIFE_ICON, 6 + i * 9, 14 * CELL + 6);
+ const frac = clamp(state.timeLeft / LIFE_TIME, 0, 1);
+ const low = state.timeLeft < 8;
+ ctx.fillStyle = "#1c2a1c";
+ ctx.fillRect(40, 15 * CELL + 5, WIDTH - 46, 6);
+ // The bar turns red when time runs low; it pulses only without reduced motion.
+ ctx.globalAlpha = low && !info.reduced && state.phase === "play" ? 0.65 + 0.35 * Math.sin(info.time * 6) : 1;
+ ctx.fillStyle = low ? "#ff5a4a" : "#7ed957";
+ ctx.fillRect(WIDTH - 6 - Math.round((WIDTH - 46) * frac), 15 * CELL + 5, Math.round((WIDTH - 46) * frac), 6);
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = low ? "#ff5a4a" : "#b6f36b";
+ drawNumber(ctx, Math.ceil(state.timeLeft), 6, 15 * CELL + 4, 2);
+
+ if (state.phase === "levelup") {
+ ctx.fillStyle = "#ffe66b";
+ drawNumber(ctx, state.level + 1, WIDTH / 2, 7 * CELL + 1, 3, "center");
+ }
+}
+
+const roadHopper: RetroGame<HopperState> = {
+ id: "road-hopper",
+ width: WIDTH,
+ height: HEIGHT,
+ create,
+ step,
+ draw,
+ status,
+};
+
+export default roadHopper;
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/retroArcade.css b/jarvis/ui/web/frontend/src/components/society/arcade/retroArcade.css
new file mode 100644
index 0000000000..6884d8cdb4
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/retroArcade.css
@@ -0,0 +1,124 @@
+/* The retro cabinet overlay (RetroArcadeOverlay). The cabinet wears its game's
+ own colours (--cab-*, from the registry look) in both app themes, like a real
+ machine; only the dimmed room behind it follows the theme. Nothing here
+ animates except the "press start" pulse, and that only when motion is welcome. */
+.retro-cab-backdrop { position:absolute; inset:0; z-index:70; display:flex; align-items:center; justify-content:center; padding:16px; background:hsl(var(--background) / .72); backdrop-filter:blur(6px); }
+.retro-cab {
+ position:relative; display:flex; flex-direction:column; width:min(1180px, 100%); height:100%; max-height:980px; padding:0 14px 14px; outline:none;
+ border-radius:22px 22px 14px 14px;
+ background:linear-gradient(180deg, color-mix(in srgb, var(--cab-body) 86%, #fff) 0%, var(--cab-body) 16%, color-mix(in srgb, var(--cab-body) 80%, #000) 100%);
+ box-shadow:0 0 0 1px hsl(var(--border)), 0 24px 80px rgb(0 0 0 / .5), inset 0 0 0 1px rgb(255 255 255 / .06);
+ font-family:'Pixelify Sans', ui-monospace, monospace;
+}
+/* Neon side stripes, lit but steady. */
+.retro-cab::before, .retro-cab::after { content:""; position:absolute; top:84px; bottom:24px; width:3px; border-radius:2px; background:var(--cab-accent); box-shadow:0 0 10px var(--cab-accent); opacity:.85; pointer-events:none; }
+.retro-cab::before { left:5px; }
+.retro-cab::after { right:5px; }
+
+.retro-cab-marquee {
+ position:relative; margin:0 -14px 12px; padding:14px 60px; border-radius:22px 22px 0 0; text-align:center;
+ background:radial-gradient(ellipse at 50% 0%, color-mix(in srgb, var(--cab-marquee-text) 24%, var(--cab-marquee)) 0%, var(--cab-marquee) 72%);
+ border-bottom:3px solid var(--cab-accent);
+}
+.retro-cab-marquee h2 {
+ margin:0; font-size:clamp(20px, 3.4vw, 40px); font-weight:600; line-height:1.1; letter-spacing:.08em; text-transform:uppercase; color:var(--cab-marquee-text);
+ text-shadow:0 0 6px color-mix(in srgb, var(--cab-marquee-text) 70%, transparent), 0 0 20px color-mix(in srgb, var(--cab-marquee-text) 40%, transparent);
+}
+.retro-cab-close {
+ position:absolute; right:12px; top:50%; transform:translateY(-50%); width:34px; height:34px; border-radius:8px; cursor:pointer;
+ border:1px solid color-mix(in srgb, var(--cab-marquee-text) 35%, transparent); background:rgb(0 0 0 / .28); color:var(--cab-marquee-text); font-size:20px; line-height:1;
+}
+.retro-cab-close:hover { background:rgb(0 0 0 / .45); }
+
+.retro-cab-bezel { flex:1; min-height:0; display:flex; flex-direction:column; gap:10px; padding:12px; border-radius:14px; background:var(--cab-trim); box-shadow:inset 0 2px 12px rgb(0 0 0 / .65), 0 0 0 1px rgb(255 255 255 / .05); }
+.retro-cab-hud { display:flex; flex-wrap:wrap; justify-content:center; gap:4px 24px; font-size:15px; letter-spacing:.08em; text-transform:uppercase; color:rgb(230 235 255 / .7); font-variant-numeric:tabular-nums; }
+.retro-cab-hud b { font-weight:600; color:var(--cab-marquee-text); }
+
+/* The stage takes the room that is left; the screen inside is sized in JS to a crisp scale. */
+.retro-cab-stage { flex:1; min-height:0; min-width:0; display:flex; align-items:center; justify-content:center; overflow:hidden; }
+.retro-cab-screen { position:relative; flex:none; overflow:hidden; border-radius:6px; background:#000; box-shadow:0 0 0 3px rgb(0 0 0 / .85), 0 0 44px color-mix(in srgb, var(--cab-accent) 24%, transparent); }
+.retro-cab-screen canvas { display:block; width:100%; height:100%; image-rendering:crisp-edges; image-rendering:pixelated; }
+.retro-cab-screen canvas[data-pointer="true"] { cursor:crosshair; touch-action:none; }
+
+/* Static CRT: a vignette always, scanlines (one per game pixel row) when pixels are big enough to carry them. */
+.retro-cab-crt { position:absolute; inset:0; pointer-events:none; background:radial-gradient(ellipse at center, transparent 60%, rgb(0 0 0 / .42) 100%); }
+.retro-cab-screen[data-scan="on"] .retro-cab-crt {
+ background:
+ radial-gradient(ellipse at center, transparent 60%, rgb(0 0 0 / .42) 100%),
+ repeating-linear-gradient(to bottom, transparent 0, transparent calc(var(--retro-px) * .6), rgb(0 0 0 / .2) calc(var(--retro-px) * .6), rgb(0 0 0 / .2) var(--retro-px));
+}
+
+.retro-cab-card {
+ position:absolute; left:50%; top:50%; transform:translate(-50%, -50%); display:flex; flex-direction:column; align-items:center; gap:8px;
+ width:max-content; max-width:calc(100% - 24px); max-height:calc(100% - 16px); overflow:auto; padding:16px 24px;
+ border:2px solid var(--cab-accent); border-radius:4px; background:rgb(6 6 12 / .84); box-shadow:0 0 0 4px rgb(0 0 0 / .5);
+ color:#e8ecff; font:inherit; font-size:14px; text-align:center;
+}
+button.retro-cab-card { cursor:pointer; }
+.retro-cab-card strong { font-size:clamp(18px, 3vw, 32px); font-weight:600; letter-spacing:.1em; text-transform:uppercase; color:var(--cab-marquee-text); }
+.retro-cab-card b { font-weight:600; color:var(--cab-marquee-text); }
+.retro-cab-tagline { font-size:15px; }
+.retro-cab-how { max-width:46ch; font-size:12px; color:rgb(232 236 255 / .72); }
+.retro-cab-blink { font-size:14px; letter-spacing:.08em; text-transform:uppercase; color:var(--cab-accent); }
+.retro-cab-newbest { padding:2px 8px; border-radius:3px; background:#facc15; color:#1a1405; font-size:13px; letter-spacing:.08em; text-transform:uppercase; }
+.retro-cab-retry { margin-top:4px; padding:6px 14px; border:1px solid var(--cab-accent); border-radius:4px; background:transparent; color:#e8ecff; font:inherit; cursor:pointer; }
+.retro-cab-retry:hover { background:rgb(255 255 255 / .08); }
+@media (prefers-reduced-motion: no-preference) {
+ .retro-cab[data-reduced="false"] .retro-cab-blink { animation:retro-cab-pulse 1.4s ease-in-out infinite; }
+}
+@keyframes retro-cab-pulse { 50% { opacity:.45; } }
+
+.retro-cab-keys { margin:0; text-align:center; font-size:12px; letter-spacing:.1em; text-transform:uppercase; color:rgb(230 235 255 / .5); }
+
+/* Touch controls: d-pad left, B / A right, like the panel of a real cabinet. */
+.retro-cab-touch { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:2px 6px; touch-action:none; user-select:none; -webkit-user-select:none; -webkit-touch-callout:none; }
+.retro-cab-dpad { position:relative; flex:none; width:132px; height:132px; border-radius:50%; background:rgb(255 255 255 / .06); touch-action:none; }
+.retro-cab-dpad-arm { position:absolute; width:40px; height:44px; border-radius:8px; background:rgb(255 255 255 / .16); }
+.retro-cab-dpad-arm[data-dir="up"] { left:46px; top:6px; }
+.retro-cab-dpad-arm[data-dir="down"] { left:46px; bottom:6px; }
+.retro-cab-dpad-arm[data-dir="left"] { left:6px; top:46px; width:44px; height:40px; }
+.retro-cab-dpad-arm[data-dir="right"] { right:6px; top:46px; width:44px; height:40px; }
+.retro-cab-dpad-arm::after { content:""; position:absolute; left:50%; top:50%; width:0; height:0; transform:translate(-50%, -50%); border:7px solid transparent; }
+.retro-cab-dpad-arm[data-dir="up"]::after { border-bottom-color:var(--cab-accent); margin-top:-4px; }
+.retro-cab-dpad-arm[data-dir="down"]::after { border-top-color:var(--cab-accent); margin-top:4px; }
+.retro-cab-dpad-arm[data-dir="left"]::after { border-right-color:var(--cab-accent); margin-left:-4px; }
+.retro-cab-dpad-arm[data-dir="right"]::after { border-left-color:var(--cab-accent); margin-left:4px; }
+.retro-cab-buttons { display:flex; align-items:center; gap:14px; padding-bottom:14px; }
+.retro-cab-btn { width:64px; height:64px; border:0; border-radius:50%; background:var(--cab-accent); color:#0b0b12; font:inherit; font-size:22px; font-weight:600; box-shadow:0 4px 0 rgb(0 0 0 / .45); touch-action:none; cursor:pointer; }
+.retro-cab-btn[data-button="b"] { filter:brightness(.72); transform:translateY(14px); }
+.retro-cab-btn:active { box-shadow:0 1px 0 rgb(0 0 0 / .45); translate:0 3px; }
+.retro-cab-pause { flex:none; padding:8px 12px; border:1px solid rgb(255 255 255 / .2); border-radius:8px; background:rgb(0 0 0 / .3); color:#e8ecff; font-size:12px; letter-spacing:.1em; cursor:pointer; }
+
+.retro-cab-close:focus-visible, .retro-cab-card:focus-visible, .retro-cab-retry:focus-visible, .retro-cab-btn:focus-visible, .retro-cab-pause:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }
+
+@media (max-width:640px) {
+ .retro-cab-backdrop { padding:8px; }
+ .retro-cab { padding:0 8px 8px; }
+ .retro-cab-marquee { margin:0 -8px 8px; padding:10px 50px; }
+ .retro-cab-bezel { padding:8px; gap:8px; }
+ .retro-cab-hud { gap:2px 14px; font-size:12px; }
+ .retro-cab-card { padding:10px 14px; gap:6px; font-size:12px; }
+ .retro-cab-how { font-size:11px; }
+ .retro-cab-dpad { width:116px; height:116px; }
+ .retro-cab-dpad-arm { width:34px; height:38px; }
+ .retro-cab-dpad-arm[data-dir="up"], .retro-cab-dpad-arm[data-dir="down"] { left:41px; }
+ .retro-cab-dpad-arm[data-dir="left"], .retro-cab-dpad-arm[data-dir="right"] { top:41px; width:38px; height:34px; }
+ .retro-cab-btn { width:56px; height:56px; font-size:19px; }
+}
+
+/* A phone on its side: the controls flank the screen instead of eating its height. */
+@media (orientation: landscape) and (max-height: 540px) and (pointer: coarse) {
+ .retro-cab-marquee { padding-block:6px; margin-bottom:6px; }
+ .retro-cab-marquee h2 { font-size:18px; }
+ .retro-cab::before, .retro-cab::after { top:48px; }
+ .retro-cab-bezel {
+ display:grid; gap:6px 12px; grid-template-columns:auto minmax(0, 1fr) auto; grid-template-rows:auto minmax(0, 1fr) auto;
+ grid-template-areas:"hud hud hud" "dpad stage btns" "pause stage .";
+ }
+ .retro-cab-hud { grid-area:hud; font-size:12px; }
+ .retro-cab-stage { grid-area:stage; }
+ .retro-cab-touch { display:contents; }
+ .retro-cab-dpad { grid-area:dpad; align-self:center; }
+ .retro-cab-buttons { grid-area:btns; align-self:center; }
+ .retro-cab-pause { grid-area:pause; justify-self:center; }
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/retroGame.ts b/jarvis/ui/web/frontend/src/components/society/arcade/retroGame.ts
new file mode 100644
index 0000000000..398c093ff0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/retroGame.ts
@@ -0,0 +1,106 @@
+/**
+ * The contract every retro game on the arcade floor implements.
+ *
+ * A game is pure state plus three functions: `create` a fresh run, `step` it
+ * at a fixed rate with the buttons the player holds, and `draw` it onto a
+ * small logical canvas (the cabinet overlay scales that up crisply). The
+ * overlay (RetroArcadeOverlay) owns everything around the game: the keyboard
+ * and gamepad, start / pause / game over, the best score, leaving the game.
+ * So a game never touches the DOM, the clock or `Math.random` directly, and
+ * its rules are unit-testable without a browser.
+ */
+
+/** The fixed simulation step in seconds; the overlay calls `step` this often. */
+export const RETRO_STEP = 1 / 60;
+
+/** The six buttons of the cabinet's control panel. */
+export interface RetroButtons {
+ left: boolean;
+ right: boolean;
+ up: boolean;
+ down: boolean;
+ /** Primary action: Space, J or gamepad A (fire, jump, launch, rotate). */
+ a: boolean;
+ /** Secondary action: Shift, K or gamepad B/X (bomb, hard drop, hold, boost). */
+ b: boolean;
+}
+
+export interface RetroPointer {
+ /** Position in logical canvas pixels. */
+ x: number;
+ y: number;
+ /** The primary button is held. */
+ down: boolean;
+ /** It went down since the previous step (edge). */
+ clicked: boolean;
+}
+
+export interface RetroInput extends RetroButtons {
+ /** Buttons that went down since the previous step (edges); use these for one-shot actions like rotate or jump. */
+ pressed: RetroButtons;
+ /** The mouse / touch over the screen, for games that set `pointer: true`; null otherwise or when it is off-screen. */
+ pointer: RetroPointer | null;
+}
+
+export interface RetroStatus {
+ score: number;
+ /** Lives or tries left, when the game has them. */
+ lives?: number;
+ level?: number;
+ /** The run has ended (out of lives, crashed, topped out). The overlay shows game over and stores the best score. */
+ over: boolean;
+ /** The run ended by winning (the overlay says so instead of "game over"). */
+ won?: boolean;
+}
+
+/** What `draw` may know besides the state. */
+export interface RetroDrawInfo {
+ /** Seconds since the overlay opened; for blinking and idle animation only, never for rules. */
+ time: number;
+ /** The person prefers reduced motion: no screen shake, no strobing, no flashing. */
+ reduced: boolean;
+ /** The run has not started yet (title screen) or is paused; the overlay draws its own text over it. */
+ idle: boolean;
+}
+
+export interface RetroGame<S> {
+ id: string;
+ /** Logical canvas size in pixels (e.g. 320 × 240). Draw only inside it; the overlay scales it to fit. */
+ width: number;
+ height: number;
+ /** A fresh run. `random` returns [0, 1); use it for every random choice so runs are reproducible in tests. */
+ create(random: () => number): S;
+ /** Advance by `dt` seconds (always RETRO_STEP from the overlay). Mutating `state` in place is expected. */
+ step(state: S, input: RetroInput, dt: number, random: () => number): void;
+ /** Paint the whole frame (clear it first). Canvas 2D only; no images, no external assets. */
+ draw(ctx: CanvasRenderingContext2D, state: S, info: RetroDrawInfo): void;
+ status(state: S): RetroStatus;
+ /** The game reads `input.pointer` (mouse aim, clicks). */
+ pointer?: boolean;
+}
+
+/** No button held, nothing pressed. */
+export function idleInput(): RetroInput {
+ const off = (): RetroButtons => ({ left: false, right: false, up: false, down: false, a: false, b: false });
+ return { ...off(), pressed: off(), pointer: null };
+}
+
+/** The pixel face loaded app-wide (index.css); every game writes its text in it. */
+export const RETRO_FONT = "'Pixelify Sans', ui-monospace, monospace";
+
+/** A canvas font string in the arcade face, e.g. `retroFont(8)` or `retroFont(16, 600)`. */
+export function retroFont(px: number, weight = 400): string {
+ return `${weight} ${px}px ${RETRO_FONT}`;
+}
+
+/** A small seeded PRNG (mulberry32) for tests and attract screens; the overlay uses Math.random. */
+export function seededRandom(seed: number): () => number {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/retroInput.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/retroInput.test.ts
new file mode 100644
index 0000000000..cfd34d78c2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/retroInput.test.ts
@@ -0,0 +1,210 @@
+import { describe, expect, it } from "vitest";
+import {
+ STICK_DEAD_ZONE, clearEdges, createInputTracker, dpadDirections, firstGamepad, hasStartGesture, keyButton, leavePointer, pressKey,
+ readGamepad, releaseAll, releaseKey, screenScale, setPointer, setTouch, takeInput, toLogical, type GamepadLike,
+} from "./retroInput";
+
+function pad(buttons: number[] = [], axes: number[] = [0, 0]): GamepadLike {
+ return { axes, buttons: Array.from({ length: 17 }, (_, i) => ({ pressed: buttons.includes(i) })) };
+}
+
+describe("retro keyboard mapping", () => {
+ it("maps arrows/WASD, Space/J/Z and Shift/K/X", () => {
+ expect(["ArrowLeft", "KeyA"].map(keyButton)).toEqual(["left", "left"]);
+ expect(["ArrowRight", "KeyD", "ArrowUp", "KeyW", "ArrowDown", "KeyS"].map(keyButton)).toEqual(["right", "right", "up", "up", "down", "down"]);
+ expect(["Space", "KeyJ", "KeyZ"].map(keyButton)).toEqual(["a", "a", "a"]);
+ expect(["ShiftLeft", "ShiftRight", "KeyK", "KeyX"].map(keyButton)).toEqual(["b", "b", "b", "b"]);
+ expect(keyButton("KeyP")).toBeNull();
+ expect(keyButton("Enter")).toBeNull();
+ });
+
+ it("delivers a press to exactly one step and keeps the hold", () => {
+ const t = createInputTracker();
+ expect(pressKey(t, "Space")).toBe(true);
+ const first = takeInput(t, false);
+ expect(first.a).toBe(true);
+ expect(first.pressed.a).toBe(true);
+ const second = takeInput(t, false);
+ expect(second.a).toBe(true);
+ expect(second.pressed.a).toBe(false);
+ releaseKey(t, "Space");
+ expect(takeInput(t, false).a).toBe(false);
+ });
+
+ it("keeps a tap shorter than a frame", () => {
+ const t = createInputTracker();
+ pressKey(t, "KeyJ");
+ releaseKey(t, "KeyJ");
+ const input = takeInput(t, false);
+ expect(input.a).toBe(false);
+ expect(input.pressed.a).toBe(true);
+ });
+
+ it("never counts auto-repeat as a new press", () => {
+ const t = createInputTracker();
+ pressKey(t, "ArrowUp");
+ takeInput(t, false);
+ pressKey(t, "ArrowUp", true);
+ expect(takeInput(t, false).pressed.up).toBe(false);
+ // After a blur forgot the held key, a repeat holds it again but is still no press.
+ releaseAll(t);
+ pressKey(t, "ArrowUp", true);
+ const input = takeInput(t, false);
+ expect(input.up).toBe(true);
+ expect(input.pressed.up).toBe(false);
+ });
+
+ it("does not release a button still held on another source", () => {
+ const t = createInputTracker();
+ pressKey(t, "KeyX");
+ setTouch(t, "b", true);
+ takeInput(t, false);
+ releaseKey(t, "KeyX");
+ expect(takeInput(t, false).b).toBe(true);
+ setTouch(t, "b", false);
+ expect(takeInput(t, false).b).toBe(false);
+ });
+
+ it("counts a second source joining a held button as no new press", () => {
+ const t = createInputTracker();
+ pressKey(t, "KeyZ");
+ takeInput(t, false);
+ setTouch(t, "a", true);
+ expect(takeInput(t, false).pressed.a).toBe(false);
+ });
+
+ it("forgets keyboard and touch on release-all, and pending edges with them", () => {
+ const t = createInputTracker();
+ pressKey(t, "ArrowLeft");
+ setTouch(t, "a", true);
+ releaseAll(t);
+ const input = takeInput(t, false);
+ expect(input.left || input.a || input.pressed.left || input.pressed.a).toBe(false);
+ });
+
+ it("clears pending edges but keeps holds", () => {
+ const t = createInputTracker();
+ pressKey(t, "Space");
+ expect(hasStartGesture(t)).toBe(true);
+ clearEdges(t);
+ expect(hasStartGesture(t)).toBe(false);
+ const input = takeInput(t, false);
+ expect(input.a).toBe(true);
+ expect(input.pressed.a).toBe(false);
+ });
+
+ it("reuses one input object between steps", () => {
+ const t = createInputTracker();
+ expect(takeInput(t, false)).toBe(takeInput(t, false));
+ });
+});
+
+describe("retro gamepad mapping", () => {
+ it("reads the d-pad, A and both B buttons", () => {
+ const t = createInputTracker();
+ readGamepad(t, pad([12, 15, 0]));
+ let input = takeInput(t, false);
+ expect([input.up, input.right, input.a, input.down, input.left, input.b]).toEqual([true, true, true, false, false, false]);
+ expect(input.pressed.a).toBe(true);
+ readGamepad(t, pad([2]));
+ input = takeInput(t, false);
+ expect([input.up, input.a, input.b]).toEqual([false, false, true]);
+ readGamepad(t, pad([1]));
+ expect(takeInput(t, false).pressed.b).toBe(false);
+ });
+
+ it("steers with the left stick outside its dead zone", () => {
+ const t = createInputTracker();
+ readGamepad(t, pad([], [STICK_DEAD_ZONE * 0.9, -STICK_DEAD_ZONE * 0.9]));
+ let input = takeInput(t, false);
+ expect(input.right || input.up).toBe(false);
+ readGamepad(t, pad([], [-0.8, 0.9]));
+ input = takeInput(t, false);
+ expect([input.left, input.down, input.right, input.up]).toEqual([true, true, false, false]);
+ });
+
+ it("reports Start once per press", () => {
+ const t = createInputTracker();
+ expect(readGamepad(t, pad([9]))).toBe(true);
+ expect(readGamepad(t, pad([9]))).toBe(false);
+ expect(readGamepad(t, pad([]))).toBe(false);
+ expect(readGamepad(t, pad([9]))).toBe(true);
+ });
+
+ it("releases everything when the pad disconnects", () => {
+ const t = createInputTracker();
+ readGamepad(t, pad([0, 14]));
+ readGamepad(t, null);
+ const input = takeInput(t, false);
+ expect(input.a || input.left).toBe(false);
+ });
+
+ it("picks the first connected pad from the browser's list", () => {
+ const one = { ...pad(), connected: false };
+ const two = { ...pad([0]), connected: true };
+ expect(firstGamepad([null, one, two])).toBe(two);
+ expect(firstGamepad([])).toBeNull();
+ expect(firstGamepad(null)).toBeNull();
+ });
+});
+
+describe("retro pointer and touch", () => {
+ it("delivers a click once and the pointer only to pointer games", () => {
+ const t = createInputTracker();
+ setPointer(t, 10, 20, true);
+ expect(takeInput(t, false).pointer).toBeNull();
+ setPointer(t, 12, 20, false);
+ setPointer(t, 12, 21, true);
+ const first = takeInput(t, true);
+ expect(first.pointer).toEqual({ x: 12, y: 21, down: true, clicked: true });
+ expect(takeInput(t, true).pointer?.clicked).toBe(false);
+ });
+
+ it("still delivers a click that left the screen before the step", () => {
+ const t = createInputTracker();
+ setPointer(t, 5, 5, true);
+ leavePointer(t);
+ expect(takeInput(t, true).pointer?.clicked).toBe(true);
+ expect(takeInput(t, true).pointer).toBeNull();
+ });
+
+ it("maps client positions through the CSS scale", () => {
+ const rect = { left: 100, top: 50, width: 960, height: 720 };
+ expect(toLogical(100, 50, rect, 320, 240)).toEqual({ x: 0, y: 0 });
+ expect(toLogical(580, 410, rect, 320, 240)).toEqual({ x: 160, y: 120 });
+ expect(toLogical(99, 60, rect, 320, 240)).toBeNull();
+ expect(toLogical(200, 60, { ...rect, width: 0 }, 320, 240)).toBeNull();
+ const edge = toLogical(1060, 770, rect, 320, 240);
+ expect(edge && edge.x < 320 && edge.y < 240).toBe(true);
+ });
+
+ it("splits the d-pad into 8 directions with a quiet middle", () => {
+ expect(dpadDirections(2, 2, 40)).toEqual({ left: false, right: false, up: false, down: false });
+ expect(dpadDirections(30, 3, 40)).toEqual({ left: false, right: true, up: false, down: false });
+ expect(dpadDirections(-3, -30, 40)).toEqual({ left: false, right: false, up: true, down: false });
+ expect(dpadDirections(-20, 20, 40)).toEqual({ left: true, right: false, up: false, down: true });
+ });
+});
+
+describe("retro screen scale", () => {
+ it("picks the largest whole factor that fits", () => {
+ expect(screenScale(1000, 800, 320, 240)).toBe(3);
+ expect(screenScale(640, 480, 320, 240)).toBe(2);
+ });
+
+ it("counts whole device pixels on dense displays", () => {
+ expect(screenScale(1000, 800, 320, 240, 2)).toBe(3);
+ expect(screenScale(700, 500, 320, 240, 1.5)).toBe(2);
+ expect(screenScale(700, 500, 320, 240, 1.25)).toBe(1.6);
+ expect(screenScale(500, 400, 320, 240, 1.25)).toBeCloseTo(1.5625);
+ });
+
+ it("falls back to a fractional fit on tiny screens", () => {
+ expect(screenScale(480, 400, 320, 240)).toBeCloseTo(1.5);
+ expect(screenScale(160, 400, 320, 240)).toBeCloseTo(0.5);
+ });
+
+ it("survives an unmeasured box", () => {
+ expect(screenScale(0, 0, 320, 240)).toBe(1);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/retroInput.ts b/jarvis/ui/web/frontend/src/components/society/arcade/retroInput.ts
new file mode 100644
index 0000000000..607c17f6ab
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/retroInput.ts
@@ -0,0 +1,262 @@
+/**
+ * The cabinet's control panel: keyboard, gamepad, touch pad and pointer,
+ * folded into the one RetroInput a game steps with.
+ *
+ * Every source keeps its own held buttons, so letting go of a key never
+ * releases the same button still held on the gamepad. A press is latched as
+ * an edge when a button goes from up (on all sources) to down, and
+ * `takeInput` hands each edge to exactly one game step, then forgets it; a
+ * tap shorter than a frame is therefore never lost and never seen twice.
+ * Pure state and functions: no DOM, so all of it is unit-tested.
+ */
+import type { RetroButtons, RetroInput, RetroPointer } from "./retroGame";
+
+export type RetroButton = keyof RetroButtons;
+
+export const RETRO_BUTTONS: readonly RetroButton[] = ["left", "right", "up", "down", "a", "b"];
+
+/** Keyboard codes (layout-independent `event.code`) of the six buttons. */
+const KEY_BUTTONS: Readonly<Record<string, RetroButton>> = {
+ ArrowLeft: "left", KeyA: "left",
+ ArrowRight: "right", KeyD: "right",
+ ArrowUp: "up", KeyW: "up",
+ ArrowDown: "down", KeyS: "down",
+ Space: "a", KeyJ: "a", KeyZ: "a",
+ ShiftLeft: "b", ShiftRight: "b", KeyK: "b", KeyX: "b",
+};
+
+/** The button a key code drives, or null for keys the cabinet ignores. */
+export function keyButton(code: string): RetroButton | null {
+ return KEY_BUTTONS[code] ?? null;
+}
+
+/** The part of the Gamepad API the cabinet reads; a real `Gamepad` fits. */
+export interface GamepadLike {
+ axes: readonly number[];
+ buttons: readonly { pressed: boolean }[];
+}
+
+/** The left stick ignores this much travel, so a worn stick does not drift. */
+export const STICK_DEAD_ZONE = 0.35;
+
+/** Standard-mapping button indices. */
+const PAD_A = 0;
+const PAD_B = [1, 2] as const;
+const PAD_START = 9;
+const PAD_UP = 12;
+const PAD_DOWN = 13;
+const PAD_LEFT = 14;
+const PAD_RIGHT = 15;
+
+export interface InputTracker {
+ keys: RetroButtons;
+ touch: RetroButtons;
+ pad: RetroButtons;
+ /** Rising edges latched since the last `takeInput`. */
+ edges: RetroButtons;
+ /** Gamepad Start is held (its edge is reported by `readGamepad`). */
+ padStart: boolean;
+ /** The pointer in logical pixels; `clicked` is latched like an edge. */
+ pointer: RetroPointer;
+ /** The pointer is over the screen. */
+ pointerOn: boolean;
+ /** The object `takeInput` fills and returns; reused so the loop allocates nothing. */
+ input: RetroInput;
+ /** The pointer copy handed to a step (reused like `input`). */
+ stepPointer: RetroPointer;
+}
+
+function noButtons(): RetroButtons {
+ return { left: false, right: false, up: false, down: false, a: false, b: false };
+}
+
+export function createInputTracker(): InputTracker {
+ return {
+ keys: noButtons(), touch: noButtons(), pad: noButtons(), edges: noButtons(),
+ padStart: false,
+ pointer: { x: 0, y: 0, down: false, clicked: false },
+ pointerOn: false,
+ input: { ...noButtons(), pressed: noButtons(), pointer: null },
+ stepPointer: { x: 0, y: 0, down: false, clicked: false },
+ };
+}
+
+/** The button is held on any source. */
+export function isHeld(t: InputTracker, b: RetroButton): boolean {
+ return t.keys[b] || t.touch[b] || t.pad[b];
+}
+
+function setHeld(t: InputTracker, source: RetroButtons, b: RetroButton, down: boolean): void {
+ if (source[b] === down) return;
+ const before = isHeld(t, b);
+ source[b] = down;
+ if (down && !before) t.edges[b] = true;
+}
+
+/**
+ * A key went down. Auto-repeat never counts as a new press, but it does mark
+ * the button held again (after `releaseAll` while the key stayed down).
+ * Returns whether the key belongs to the cabinet.
+ */
+export function pressKey(t: InputTracker, code: string, repeat = false): boolean {
+ const b = keyButton(code);
+ if (!b) return false;
+ if (repeat) t.keys[b] = true;
+ else setHeld(t, t.keys, b, true);
+ return true;
+}
+
+export function releaseKey(t: InputTracker, code: string): boolean {
+ const b = keyButton(code);
+ if (!b) return false;
+ t.keys[b] = false;
+ return true;
+}
+
+/** A button of the on-screen touch pad. */
+export function setTouch(t: InputTracker, b: RetroButton, down: boolean): void {
+ setHeld(t, t.touch, b, down);
+}
+
+function padPressed(pad: GamepadLike, index: number): boolean {
+ return !!pad.buttons[index]?.pressed;
+}
+
+/**
+ * Read one gamepad snapshot (or null when none is connected): d-pad and left
+ * stick steer, button 0 is A, 1 or 2 is B. Returns true when Start went down
+ * since the previous read; the overlay turns that into start or pause.
+ */
+export function readGamepad(t: InputTracker, pad: GamepadLike | null): boolean {
+ if (!pad) {
+ for (const b of RETRO_BUTTONS) t.pad[b] = false;
+ t.padStart = false;
+ return false;
+ }
+ const x = pad.axes[0] ?? 0;
+ const y = pad.axes[1] ?? 0;
+ setHeld(t, t.pad, "left", padPressed(pad, PAD_LEFT) || x < -STICK_DEAD_ZONE);
+ setHeld(t, t.pad, "right", padPressed(pad, PAD_RIGHT) || x > STICK_DEAD_ZONE);
+ setHeld(t, t.pad, "up", padPressed(pad, PAD_UP) || y < -STICK_DEAD_ZONE);
+ setHeld(t, t.pad, "down", padPressed(pad, PAD_DOWN) || y > STICK_DEAD_ZONE);
+ setHeld(t, t.pad, "a", padPressed(pad, PAD_A));
+ setHeld(t, t.pad, "b", padPressed(pad, PAD_B[0]) || padPressed(pad, PAD_B[1]));
+ const start = padPressed(pad, PAD_START);
+ const edge = start && !t.padStart;
+ t.padStart = start;
+ return edge;
+}
+
+/** The first connected pad in a `navigator.getGamepads()` list. */
+export function firstGamepad(pads: readonly (GamepadLike | null)[] | null | undefined): GamepadLike | null {
+ if (!pads) return null;
+ for (const pad of pads) if (pad && (pad as { connected?: boolean }).connected !== false) return pad;
+ return null;
+}
+
+/** The pointer moved or its button changed, in logical canvas pixels. */
+export function setPointer(t: InputTracker, x: number, y: number, down: boolean): void {
+ if (down && !t.pointer.down) t.pointer.clicked = true;
+ t.pointer.x = x;
+ t.pointer.y = y;
+ t.pointer.down = down;
+ t.pointerOn = true;
+}
+
+/** The pointer left the screen; a pending click is still delivered. */
+export function leavePointer(t: InputTracker): void {
+ t.pointer.down = false;
+ t.pointerOn = false;
+}
+
+/** Forget pending presses (e.g. the key that started the run). Held buttons stay held. */
+export function clearEdges(t: InputTracker): void {
+ for (const b of RETRO_BUTTONS) t.edges[b] = false;
+ t.pointer.clicked = false;
+}
+
+/** A pending press of A, or a click: the "start the game" gesture on title screens. */
+export function hasStartGesture(t: InputTracker): boolean {
+ return t.edges.a || t.pointer.clicked;
+}
+
+/**
+ * Forget everything held on the keyboard and touch pad (window blur, pause):
+ * their release events may never arrive. The gamepad is polled, so it heals
+ * by itself on the next read.
+ */
+export function releaseAll(t: InputTracker): void {
+ for (const b of RETRO_BUTTONS) { t.keys[b] = false; t.touch[b] = false; }
+ t.pointer.down = false;
+ clearEdges(t);
+}
+
+/**
+ * The input for exactly one game step. Pending edges go into `pressed` and
+ * are cleared, so the next step only sees new presses. The returned object is
+ * reused by the next call.
+ */
+export function takeInput(t: InputTracker, withPointer: boolean): RetroInput {
+ const input = t.input;
+ for (const b of RETRO_BUTTONS) {
+ input[b] = isHeld(t, b);
+ input.pressed[b] = t.edges[b];
+ t.edges[b] = false;
+ }
+ if (withPointer && (t.pointerOn || t.pointer.clicked)) {
+ const p = t.stepPointer;
+ p.x = t.pointer.x; p.y = t.pointer.y; p.down = t.pointer.down; p.clicked = t.pointer.clicked;
+ input.pointer = p;
+ } else {
+ input.pointer = null;
+ }
+ t.pointer.clicked = false;
+ return input;
+}
+
+/**
+ * The 8-way direction of a touch on the d-pad, from its offset to the pad's
+ * centre. A small middle zone means "no direction"; a diagonal needs both
+ * axes within 22.5 degrees of it.
+ */
+export function dpadDirections(dx: number, dy: number, radius: number): Pick<RetroButtons, "left" | "right" | "up" | "down"> {
+ const off = { left: false, right: false, up: false, down: false };
+ if (!(radius > 0) || Math.hypot(dx, dy) < radius * 0.25) return off;
+ const tan = Math.tan(Math.PI / 8); // 22.5 degrees
+ const ax = Math.abs(dx);
+ const ay = Math.abs(dy);
+ if (ax > ay * tan) { off.left = dx < 0; off.right = dx > 0; }
+ if (ay > ax * tan) { off.up = dy < 0; off.down = dy > 0; }
+ return off;
+}
+
+export interface ScreenRect {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+}
+
+/** A client position over the scaled canvas in logical pixels, or null when it is outside. */
+export function toLogical(clientX: number, clientY: number, rect: ScreenRect, width: number, height: number): { x: number; y: number } | null {
+ if (!(rect.width > 0) || !(rect.height > 0)) return null;
+ const x = ((clientX - rect.left) / rect.width) * width;
+ const y = ((clientY - rect.top) / rect.height) * height;
+ if (x < 0 || y < 0 || x > width || y > height) return null;
+ return { x: Math.min(x, width - 1e-6), y: Math.min(y, height - 1e-6) };
+}
+
+/**
+ * The CSS scale that shows a `width` x `height` game in the available box:
+ * the largest whole number of DEVICE pixels per game pixel (so every game
+ * pixel is equally sharp on any display density). Below two device pixels per
+ * game pixel a whole factor would waste too much room, so tiny windows get the
+ * exact fractional fit instead.
+ */
+export function screenScale(availWidth: number, availHeight: number, width: number, height: number, dpr = 1): number {
+ if (!(availWidth > 0) || !(availHeight > 0) || !(width > 0) || !(height > 0)) return 1;
+ const ratio = dpr > 0 && Number.isFinite(dpr) ? dpr : 1;
+ const fit = Math.min(availWidth / width, availHeight / height);
+ const whole = Math.floor(fit * ratio + 1e-6);
+ return whole >= 2 ? whole / ratio : fit;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/retroLoop.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/retroLoop.test.ts
new file mode 100644
index 0000000000..cf72b0485f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/retroLoop.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+import { RETRO_STEP } from "./retroGame";
+import { MAX_STEPS_PER_FRAME, createRetroClock, resetClock, stepsDue } from "./retroLoop";
+
+describe("retro fixed-step clock", () => {
+ it("runs one step per 60 Hz frame without drifting", () => {
+ const clock = createRetroClock();
+ let total = 0;
+ for (let i = 0; i < 600; i++) total += stepsDue(clock, RETRO_STEP);
+ expect(total).toBe(600);
+ });
+
+ it("runs every other frame on a 120 Hz display", () => {
+ const clock = createRetroClock();
+ const steps = Array.from({ length: 8 }, () => stepsDue(clock, RETRO_STEP / 2));
+ expect(steps.reduce((a, b) => a + b, 0)).toBe(4);
+ expect(Math.max(...steps)).toBe(1);
+ });
+
+ it("catches up after a short hitch", () => {
+ const clock = createRetroClock();
+ expect(stepsDue(clock, RETRO_STEP * 3)).toBe(3);
+ expect(stepsDue(clock, RETRO_STEP)).toBe(1);
+ });
+
+ it("drops the backlog after a long stall instead of fast-forwarding", () => {
+ const clock = createRetroClock();
+ expect(stepsDue(clock, 2)).toBe(MAX_STEPS_PER_FRAME);
+ expect(clock.acc).toBe(0);
+ expect(stepsDue(clock, RETRO_STEP)).toBe(1);
+ });
+
+ it("ignores negative and non-finite time", () => {
+ const clock = createRetroClock();
+ expect(stepsDue(clock, -1)).toBe(0);
+ expect(stepsDue(clock, Number.NaN)).toBe(0);
+ expect(stepsDue(clock, Number.POSITIVE_INFINITY)).toBe(0);
+ expect(clock.acc).toBe(0);
+ });
+
+ it("forgets collected time on reset", () => {
+ const clock = createRetroClock();
+ stepsDue(clock, RETRO_STEP * 0.9);
+ resetClock(clock);
+ expect(stepsDue(clock, RETRO_STEP * 0.5)).toBe(0);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/retroLoop.ts b/jarvis/ui/web/frontend/src/components/society/arcade/retroLoop.ts
new file mode 100644
index 0000000000..8c78acba4a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/retroLoop.ts
@@ -0,0 +1,43 @@
+/**
+ * The fixed-step clock behind the cabinet overlay.
+ *
+ * Animation frames arrive at whatever rate the display runs (60, 120, 144 Hz,
+ * or a stutter after a busy moment), but a retro game's rules must advance in
+ * equal steps so it plays the same everywhere. The accumulator collects real
+ * time and hands out whole steps; after a long stall (a hidden window, a GC
+ * pause) it drops the backlog instead of fast-forwarding the game.
+ */
+import { RETRO_STEP } from "./retroGame";
+
+/** At most this many steps per animation frame; anything beyond is a stall and is dropped. */
+export const MAX_STEPS_PER_FRAME = 5;
+
+export interface RetroClock {
+ /** Real seconds collected but not yet spent on a step. */
+ acc: number;
+}
+
+export function createRetroClock(): RetroClock {
+ return { acc: 0 };
+}
+
+/**
+ * Add `elapsed` real seconds and return how many fixed steps to run now.
+ * Negative or non-finite time (a clock jump) counts as nothing.
+ */
+export function stepsDue(clock: RetroClock, elapsed: number, step = RETRO_STEP, maxSteps = MAX_STEPS_PER_FRAME): number {
+ if (Number.isFinite(elapsed) && elapsed > 0) clock.acc += elapsed;
+ // A hair of tolerance so 1/60 s frames never alternate between 0 and 2 steps from rounding.
+ const due = Math.floor((clock.acc + 1e-9) / step);
+ if (due > maxSteps) {
+ clock.acc = 0;
+ return maxSteps;
+ }
+ clock.acc = Math.max(0, clock.acc - due * step);
+ return due;
+}
+
+/** Forget collected time, e.g. when a run starts or resumes, so it does not begin with a burst. */
+export function resetClock(clock: RetroClock): void {
+ clock.acc = 0;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/retroScores.test.ts b/jarvis/ui/web/frontend/src/components/society/arcade/retroScores.test.ts
new file mode 100644
index 0000000000..ba6ee331e7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/retroScores.test.ts
@@ -0,0 +1,51 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { bestKey, clearBestMemory, readBest, saveBest, type ScoreStorage } from "./retroScores";
+
+/** A plain in-memory Storage stand-in. */
+function memoryStorage(): ScoreStorage & { data: Map<string, string> } {
+ const data = new Map<string, string>();
+ return { data, getItem: (k) => data.get(k) ?? null, setItem: (k, v) => { data.set(k, v); } };
+}
+
+/** Storage that throws on every call, like blocked site data. */
+const throwing: ScoreStorage = {
+ getItem: () => { throw new Error("blocked"); },
+ setItem: () => { throw new Error("blocked"); },
+};
+
+beforeEach(() => clearBestMemory());
+
+describe("retro best scores", () => {
+ it("uses the documented key per game", () => {
+ expect(bestKey("neon-snake")).toBe("jarvis.office.arcade.neon-snake.best");
+ });
+
+ it("starts at zero and keeps only a higher score", () => {
+ const store = memoryStorage();
+ expect(readBest("neon-snake", store)).toBe(0);
+ expect(saveBest("neon-snake", 120, store)).toBe(true);
+ expect(store.data.get(bestKey("neon-snake"))).toBe("120");
+ expect(saveBest("neon-snake", 80, store)).toBe(false);
+ expect(saveBest("neon-snake", 120, store)).toBe(false);
+ expect(readBest("neon-snake", store)).toBe(120);
+ expect(readBest("block-drop", store)).toBe(0);
+ });
+
+ it("ignores garbage in storage and in scores", () => {
+ const store = memoryStorage();
+ store.data.set(bestKey("road-hopper"), "not a number");
+ expect(readBest("road-hopper", store)).toBe(0);
+ expect(saveBest("road-hopper", Number.NaN, store)).toBe(false);
+ expect(saveBest("road-hopper", -5, store)).toBe(false);
+ expect(saveBest("road-hopper", 41.7, store)).toBe(true);
+ expect(readBest("road-hopper", store)).toBe(41);
+ });
+
+ it("works with storage that throws or is missing, for the rest of the session", () => {
+ expect(readBest("city-defense", throwing)).toBe(0);
+ expect(saveBest("city-defense", 300, throwing)).toBe(true);
+ expect(readBest("city-defense", throwing)).toBe(300);
+ expect(readBest("city-defense", null)).toBe(300);
+ expect(saveBest("city-defense", 200, null)).toBe(false);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/retroScores.ts b/jarvis/ui/web/frontend/src/components/society/arcade/retroScores.ts
new file mode 100644
index 0000000000..70f298c8ef
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/arcade/retroScores.ts
@@ -0,0 +1,68 @@
+/**
+ * Best scores per retro game, kept in the browser's localStorage.
+ *
+ * Storage is a nicety, never a requirement: a private window, blocked site
+ * data or a thumbnail renderer makes the storage accessor itself throw. Then
+ * the best score lives in memory for the rest of the session instead.
+ */
+
+/** The localStorage key of a game's best score. */
+export function bestKey(gameId: string): string {
+ return `jarvis.office.arcade.${gameId}.best`;
+}
+
+export type ScoreStorage = Pick<Storage, "getItem" | "setItem">;
+
+/** Fallback when the browser keeps nothing: the best scores of this session. */
+const memory = new Map<string, number>();
+
+function browserStorage(): ScoreStorage | null {
+ try {
+ return typeof window === "undefined" ? null : window.localStorage;
+ } catch {
+ // Blocked site data throws on access; the in-memory fallback takes over.
+ return null;
+ }
+}
+
+function clean(score: number): number {
+ return Number.isFinite(score) && score > 0 ? Math.floor(score) : 0;
+}
+
+/** The stored best score of a game, 0 when there is none. */
+export function readBest(gameId: string, storage: ScoreStorage | null = browserStorage()): number {
+ const key = bestKey(gameId);
+ let stored = 0;
+ if (storage) {
+ try {
+ stored = clean(Number(storage.getItem(key)));
+ } catch {
+ // Reading can throw like writing; fall back to the session's memory.
+ }
+ }
+ return Math.max(stored, memory.get(key) ?? 0);
+}
+
+/**
+ * Keep `score` if it beats the stored best. Returns true when it is a new
+ * best (even if only memory could hold it).
+ */
+export function saveBest(gameId: string, score: number, storage: ScoreStorage | null = browserStorage()): boolean {
+ const value = clean(score);
+ if (value <= readBest(gameId, storage)) return false;
+ const key = bestKey(gameId);
+ memory.set(key, value);
+ if (storage) {
+ try {
+ storage.setItem(key, String(value));
+ } catch {
+ // Quota or blocked storage: memory keeps it for this session.
+ }
+ }
+ return true;
+}
+
+/** Test helper: forget the in-memory fallback. */
+export function clearBestMemory(): void {
+ memory.clear();
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsx b/jarvis/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsx
index 0ee85ded15..66fbc1f95e 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsx
@@ -2,11 +2,11 @@
* The elevator's call button, on the shaft to the right of the doors.
*
* Riding needs a press of this button: a click on it (or E while standing at
- * the elevator) lights it, then the doors close. On the agents floor it
- * shows an up arrow, on the coding floor a down arrow. While the person
- * stands at the elevator it breathes softly and a pill above it says where it
- * goes; clicking it from afar only walks the character over (see
- * `elevatorCall.ts`).
+ * the elevator) opens the floor picker; picking a floor lights it, then the
+ * doors close. The ground floor shows an up arrow, the top floor a down
+ * arrow, the floors between both. While the person stands at the elevator it
+ * breathes softly and a pill above it invites a press; clicking it from afar
+ * only walks the character over (see `elevatorCall.ts`).
*/
import { useEffect, useMemo, useRef } from "react";
import { Html } from "@react-three/drei";
@@ -16,48 +16,60 @@ import { useT } from "@/i18n";
import { cachedCanvasTexture } from "./canvasMaterials";
import { callButtonPose } from "./elevatorCall";
import type { Furniture } from "./officeLayout";
-import type { OfficeFloor } from "./officeStore";
+import { floorLevel, OFFICE_FLOORS, type OfficeFloor } from "./officeStore";
const BUTTON_RADIUS = 0.09;
const IDLE = "#3b3f48";
const LIT = "#f5b83d";
-/** A white arrow on a transparent square; "up" points to +y. */
-function arrowTexture(direction: "up" | "down") {
+type ArrowDirection = "up" | "down" | "both";
+
+/** Which way the elevator can go from `floor`: up from the bottom, down from the top, both in between. */
+export function callDirection(floor: OfficeFloor): ArrowDirection {
+ const level = floorLevel(floor);
+ return level <= 0 ? "up" : level >= OFFICE_FLOORS.length - 1 ? "down" : "both";
+}
+
+/** White arrows on a transparent square; "up" points to +y, "both" stacks a small up and down arrow. */
+function arrowTexture(direction: ArrowDirection) {
return cachedCanvasTexture(`elevator-arrow:${direction}`, 128, 128, (ctx, w, h) => {
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "#ffffff";
- ctx.beginPath();
- const tip = direction === "up" ? h * 0.24 : h * 0.76;
- const base = direction === "up" ? h * 0.7 : h * 0.3;
- ctx.moveTo(w / 2, tip);
- ctx.lineTo(w * 0.24, base);
- ctx.lineTo(w * 0.76, base);
- ctx.closePath();
- ctx.fill();
+ const arrow = (up: boolean, top: number, bottom: number, half: number) => {
+ ctx.beginPath();
+ ctx.moveTo(w / 2, up ? top : bottom);
+ ctx.lineTo(w / 2 - half, up ? bottom : top);
+ ctx.lineTo(w / 2 + half, up ? bottom : top);
+ ctx.closePath();
+ ctx.fill();
+ };
+ if (direction === "both") {
+ arrow(true, h * 0.14, h * 0.44, w * 0.22);
+ arrow(false, h * 0.56, h * 0.86, w * 0.22);
+ } else {
+ arrow(direction === "up", h * 0.24, h * 0.76, w * 0.26);
+ }
});
}
-export function ElevatorCallButton({ shaft, floor, near, lit, count, animate, onPress }: {
+export function ElevatorCallButton({ shaft, floor, near, lit, animate, onPress }: {
shaft: Furniture;
floor: OfficeFloor;
/** The person stands at the elevator: the button invites a press. */
near: boolean;
/** Pressed: glowing until the ride starts. */
lit: boolean;
- /** How many work on the other floor; null while unknown. */
- count: number | null;
animate: boolean;
onPress: () => void;
}) {
const t = useT();
const pose = callButtonPose(shaft);
- const up = floor === "agents";
+ const direction = callDirection(floor);
const button = useMemo(() => new MeshStandardMaterial({ color: IDLE, roughness: 0.35, metalness: 0.3, emissive: LIT, emissiveIntensity: 0 }), []);
const arrow = useMemo(() => new MeshStandardMaterial({
- map: arrowTexture(up ? "up" : "down"), transparent: true, depthWrite: false, roughness: 0.5,
+ map: arrowTexture(direction), transparent: true, depthWrite: false, roughness: 0.5,
emissive: "#ffffff", emissiveIntensity: 0.25,
- }), [up]);
+ }), [direction]);
useEffect(() => () => button.dispose(), [button]);
useEffect(() => () => arrow.dispose(), [arrow]);
useEffect(() => () => { document.body.style.cursor = ""; }, []);
@@ -80,9 +92,6 @@ export function ElevatorCallButton({ shaft, floor, near, lit, count, animate, on
event.stopPropagation();
onPress();
};
- const label = t(up ? "society.office.floor_up" : "society.office.floor_down");
- const countText = count === null ? null
- : t(up ? "society.office.elevator_up_count" : "society.office.elevator_down_count").replace("{0}", String(count));
return (
<group position={[pose.x, pose.y, pose.z]} rotation={[0, pose.rotationY, 0]} name="elevator-call-button">
@@ -100,8 +109,8 @@ export function ElevatorCallButton({ shaft, floor, near, lit, count, animate, on
{near && !lit && (
<Html center position={[0, 0.62, 0.05]} zIndexRange={[24, 0]} pointerEvents="none">
<span className="office-call-pill" data-office-ui>
- <b>{label}</b>
- <small>{t("society.office.elevator_press")}{countText ? ` · ${countText}` : ""}</small>
+ <b>{t("society.office.elevator_choose")}</b>
+ <small>{t("society.office.elevator_press")}</small>
</span>
</Html>
)}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/ElevatorPanel.tsx b/jarvis/ui/web/frontend/src/components/society/office/ElevatorPanel.tsx
new file mode 100644
index 0000000000..3d1b4ebfba
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/ElevatorPanel.tsx
@@ -0,0 +1,94 @@
+/**
+ * The elevator's floor picker: pressing the call button (click, or E at the
+ * doors) opens this small panel with one button per floor, top floor first
+ * like a real elevator panel. The current floor is shown but not pickable.
+ * Keys: the floor's number (0, 1, 2) picks it, arrows move between buttons,
+ * Escape closes. It is a dialog, so the character stands still while it is
+ * open (`ownsKeyboard`).
+ */
+import { useEffect, useRef } from "react";
+import { useT } from "@/i18n";
+import { floorLevel, OFFICE_FLOORS, type OfficeFloor } from "./officeStore";
+
+/** The floors as the panel lists them: top floor first. */
+export const PANEL_FLOORS: readonly OfficeFloor[] = [...OFFICE_FLOORS].reverse();
+
+/** The floor a number key picks ("0" = ground floor), or null. */
+export function floorForKey(key: string): OfficeFloor | null {
+ const level = /^[0-9]$/.test(key) ? Number(key) : -1;
+ return OFFICE_FLOORS[level] ?? null;
+}
+
+export function ElevatorPanel({ floor, counts, onPick, onClose }: {
+ floor: OfficeFloor;
+ /** A line under each floor's name (e.g. how many agents work there); null leaves it out. */
+ counts: Record<OfficeFloor, string | null>;
+ onPick: (floor: OfficeFloor) => void;
+ onClose: () => void;
+}) {
+ const t = useT();
+ const list = useRef<HTMLDivElement>(null);
+
+ // Focus the nearest floor you can go to, and give focus back to the office when the panel closes.
+ useEffect(() => {
+ const before = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ list.current?.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus({ preventScroll: true });
+ return () => { before?.focus({ preventScroll: true }); };
+ }, []);
+
+ // Capture phase: the office's own E, Escape and movement keys never see these.
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape" || event.code === "KeyE") {
+ event.preventDefault(); event.stopPropagation();
+ if (!event.repeat) onClose();
+ return;
+ }
+ // Ctrl/Alt/Cmd + a digit belongs to the browser or the app, never to the panel.
+ const picked = event.ctrlKey || event.metaKey || event.altKey ? null : floorForKey(event.key);
+ if (picked) {
+ event.preventDefault(); event.stopPropagation();
+ if (picked !== floor && !event.repeat) onPick(picked);
+ return;
+ }
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
+ event.preventDefault(); event.stopPropagation();
+ const buttons = [...(list.current?.querySelectorAll<HTMLButtonElement>("button:not(:disabled)") ?? [])];
+ if (buttons.length === 0) return;
+ const at = buttons.indexOf(document.activeElement as HTMLButtonElement);
+ const next = at < 0 ? 0 : (at + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length;
+ buttons[next].focus();
+ }
+ };
+ document.addEventListener("keydown", onKey, true);
+ return () => document.removeEventListener("keydown", onKey, true);
+ }, [floor, onClose, onPick]);
+
+ return (
+ <div className="office-lift-backdrop" data-office-ui onPointerDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>
+ <div className="office-card office-lift" role="dialog" data-state="open" aria-modal="true" aria-labelledby="office-lift-title">
+ <div className="office-lift-head">
+ <h2 id="office-lift-title">{t("society.office.elevator_choose")}</h2>
+ <button type="button" className="office-icon-button" onClick={onClose} aria-label={t("society.office.close")}>×</button>
+ </div>
+ <div ref={list} className="office-lift-floors">
+ {PANEL_FLOORS.map((target) => {
+ const here = target === floor;
+ const count = counts[target];
+ return (
+ <button key={target} type="button" className="office-lift-floor" disabled={here} aria-current={here ? "location" : undefined}
+ aria-keyshortcuts={String(floorLevel(target))} data-floor={target} onClick={() => onPick(target)}>
+ <span className="office-lift-number" aria-hidden>{floorLevel(target)}</span>
+ <span className="office-lift-text">
+ <b>{t(`society.office.floor_name_${target}`)}</b>
+ <small>{here ? t("society.office.elevator_here") : count ?? t(`society.office.floor_about_${target}`)}</small>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ <p className="office-lift-keys">{t("society.office.elevator_keys")}</p>
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx
index 8a49b513f3..a4b9f1222d 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx
@@ -123,6 +123,9 @@ function FullMapDialog({ onClose, layout, agents, selectedId }: Omit<OfficeFullM
break: t("society.office.room_break"),
command: t("society.office.room_command"),
server: t("society.office.room_server"),
+ arcade: t("society.office.room_arcade"),
+ prizes: t("society.office.room_prizes"),
+ snack: t("society.office.room_snack"),
};
const openSpace = t("society.office.open_space");
const youLabel = t("society.office.minimap_you");
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx
index 2c3f0a0a3d..3ef950cf0e 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx
@@ -230,6 +230,9 @@ export function OfficeMinimap({ layout, agents, selectedId, onOpenMap }: OfficeM
break: t("society.office.room_break"),
command: t("society.office.room_command"),
server: t("society.office.room_server"),
+ arcade: t("society.office.room_arcade"),
+ prizes: t("society.office.room_prizes"),
+ snack: t("society.office.room_snack"),
};
const youLabel = t("society.office.minimap_you");
const openSpace = t("society.office.open_space");
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
index 8e7a8266e3..012d980979 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
@@ -106,7 +106,8 @@ function nearestInteractable(layout: OfficeLayout): Selection | null {
if (d <= AGENT_TALK_RANGE && d < bestDistance) { best = { kind: "agent", id }; bestDistance = d; }
}
for (const item of layout.furniture) {
- if (item.kind !== "arcade") continue;
+ // The break room's cabinet, and every game cabinet on the arcade floor.
+ if (item.kind !== "arcade" && item.kind !== "retroCabinet") continue;
// The cabinet's screen faces its local +z; you play standing in front of it.
const fx = item.x + Math.sin(item.rotationY) * 0.85, fz = item.z + Math.cos(item.rotationY) * 0.85;
const d = Math.hypot(fx - player.x, fz - player.z);
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsx
index 4c8f6f0448..f85f546376 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeProps.tsx
@@ -19,6 +19,7 @@ import { BREAK_RENDERERS } from "./BreakLounge";
import { WARDROBE_RENDERERS } from "./WardrobeRoom";
import { LOBBY_RENDERERS } from "./LobbyDecor";
import { SPAWN_RENDERERS } from "./SpawnPoint";
+import { ARCADE_RENDERERS } from "../arcade/ArcadeHallProps";
import { MeetingChair } from "./OfficeChairs";
import { Bookshelf, Box, Couch, GEO, MAT, matte, Plant, Rounded, Rug } from "./OfficeFurniture";
import { FURNITURE_SIZE, type Furniture, type FurnitureKind } from "./officeLayout";
@@ -564,6 +565,7 @@ export const PROP_RENDERERS: Record<FurnitureKind, (props: { item: Furniture })
...WARDROBE_RENDERERS,
...LOBBY_RENDERERS,
...SPAWN_RENDERERS,
+ ...ARCADE_RENDERERS,
};
/** One furniture item, placed at (x, 0, z) and turned by `rotationY` (0 = front faces +z). */
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx
index ddef15092d..b53c7e2dcf 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeRooms.tsx
@@ -25,7 +25,7 @@ function lcg(seed: number): () => number {
}
/** Metres covered by one repeat of each floor pattern. */
-const PATTERN_METRES: Record<RoomKind, number> = { lead: 2.6, team: 2, wardrobe: 2, reception: 3.2, break: 2.4, command: 3.2, server: 2 };
+const PATTERN_METRES: Record<RoomKind, number> = { lead: 2.6, team: 2, wardrobe: 2, reception: 3.2, break: 2.4, command: 3.2, server: 2, arcade: 2.4, prizes: 2, snack: 1.6 };
function drawFloor(kind: RoomKind, ctx: CanvasRenderingContext2D, w: number, h: number): void {
const { base, accents } = ROOM_FLOOR_COLOURS[kind];
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
index 6bbfdb7035..5674c8d2a9 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
@@ -3,7 +3,8 @@
* frameless glass, walled rooms in the north and south, one rug-zoned
* department per provider family in between — and everybody in it. Each
* floor dresses the shared plan in its own look (AgentsFloorLook /
- * CodingFloorLook).
+ * CodingFloorLook). The arcade floor on top has a plan and a look of its own
+ * (ArcadeHall); the person, the elevator and the camera work the same there.
*/
import { useLayoutEffect, useMemo } from "react";
import { Stars } from "@react-three/drei";
@@ -35,6 +36,7 @@ import { SpawnFittings } from "./SpawnPoint";
import { RoomFloors, RoomSign, RoomWalls } from "./OfficeRooms";
import { CHECKPOINT_ICON, CheckpointMarker } from "./CheckpointMarker";
import { ElevatorCallButton } from "./ElevatorCallButton";
+import { ArcadeHall } from "../arcade/ArcadeHall";
import { OFFICE_FIGURE_HEIGHT_M, OfficeAgents, type WalkerContext } from "./OfficeAgents";
import { OfficePlayer } from "./OfficePlayer";
import { OfficeDog } from "./OfficeDog";
@@ -95,15 +97,77 @@ export interface OfficeSceneProps {
nearby: Selection | null;
chats: ReadonlyMap<string, DeskChat>;
onOpenScreen: (agentId: string, screen: Point & { y: number }, facing: number) => void;
- /** The elevator's call button: lit after a press, how many work on the other floor, and the press itself. */
- elevatorCall: { lit: boolean; count: number | null; onPress: () => void };
+ /** The elevator's call button: lit after a press, and the press itself. */
+ elevatorCall: { lit: boolean; onPress: () => void };
}
-export function OfficeScene({ floor, occupants, ready, layout, grid, walkers, agents, newcomers, awake, reduced, overview, player, selection, nearby, chats, onOpenScreen, elevatorCall }: OfficeSceneProps) {
+/** The checkpoints, the elevator's call button and the person: the same on every floor. */
+function SharedFloorParts({ floor, layout, grid, ready, awake, reduced, player, selection, nearby, elevatorCall }: Pick<OfficeSceneProps,
+ "floor" | "layout" | "grid" | "ready" | "awake" | "reduced" | "player" | "selection" | "nearby" | "elevatorCall">) {
const t = useT();
- const desks = useMemo(() => allDesks(layout), [layout]);
+ const select = useOfficeStore((s) => s.select);
const shaft = layout.furniture.find((f) => f.kind === "elevator");
const atLift = nearby?.kind === "checkpoint" && nearby.id === "elevator";
+ return (
+ <>
+ {/* At the elevator its call button takes over from the floating token, which would hide it. */}
+ {layout.checkpoints.filter((cp) => cp.id !== "elevator" || !atLift).map((cp) => (
+ <CheckpointMarker key={cp.id} checkpoint={cp} label={t(`society.office.cp_${cp.id}`)} icon={CHECKPOINT_ICON[cp.id]}
+ active={(nearby?.kind === "checkpoint" && nearby.id === cp.id) || (selection?.kind === "checkpoint" && selection.id === cp.id)}
+ animate={awake && !reduced} onActivate={() => select({ kind: "checkpoint", id: cp.id })} />
+ ))}
+ {shaft && (
+ <ElevatorCallButton shaft={shaft} floor={floor} lit={elevatorCall.lit} animate={awake && !reduced}
+ near={atLift} onPress={elevatorCall.onPress} />
+ )}
+ <FloorArrival floor={floor} layout={layout} grid={grid} ready={ready} />
+ <OfficePlayer layout={layout} grid={grid} look={player.look} name={player.name} awake={awake} reduced={reduced} />
+ <PlayerBubble height={OFFICE_FIGURE_HEIGHT_M + 0.49} />
+ </>
+ );
+}
+
+export function OfficeScene(props: OfficeSceneProps) {
+ const { floor, layout, grid, walkers, agents, newcomers, awake, reduced, selection, nearby, chats, overview } = props;
+ const arcade = floor === "arcade";
+ const select = useOfficeStore((s) => s.select);
+ const desks = useMemo(() => allDesks(layout), [layout]);
+ const dogBeds = useMemo(() => layout.furniture.filter((f) => f.kind === "dogBed"), [layout]);
+ const treatJar = layout.furniture.find((f) => f.kind === "treatJar") ?? null;
+ const onFloorClick = (event: ThreeEvent<MouseEvent>) => {
+ // A drag that ends on the floor rotated the camera; only a real click walks.
+ if (event.delta > 6) return;
+ event.stopPropagation();
+ useOfficeStore.getState().requestWalk({ x: event.point.x, z: event.point.z });
+ };
+ // One tree for every floor (the dressing swaps, the person and the camera stay mounted), in the order the frame loop needs:
+ // the floor, the person, then whoever walks around them, the camera last.
+ return (
+ <>
+ {arcade
+ // While a cabinet is being played its screen in the hall rests: the live preview would only draw behind the overlay.
+ ? <ArcadeHall layout={layout} onFloorClick={onFloorClick} awake={awake} reduced={reduced}
+ nearCabinet={nearby?.kind === "arcade" && selection?.kind !== "arcade" ? nearby.id : null} />
+ : <OfficeFloorDressing {...props} desks={desks} onFloorClick={onFloorClick} />}
+ <SharedFloorParts {...props} />
+ {dogBeds.length > 0 && <OfficeDog beds={dogBeds} rooms={layout.rooms} jar={treatJar} grid={grid} awake={awake} reduced={reduced} />}
+ {!arcade && (
+ <OfficeAgents desks={desks} agents={agents} ctx={walkers} newcomers={newcomers} awake={awake} reduced={reduced} chats={chats}
+ selectedId={selection?.kind === "agent" ? selection.id : null} onSelect={(id) => select({ kind: "agent", id })} />
+ )}
+ {/* Upstairs the person's pet comes along: to the coding floor and to play in the arcade. */}
+ {floor !== "agents" && <GigiCompanion grid={grid} awake={awake} reduced={reduced} />}
+ <OfficeCameraRig layout={layout} overview={overview} />
+ </>
+ );
+}
+
+/** Everything that dresses the agents and coding floors: slab, rooms, departments, desks, monitors, furniture. */
+function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awake, reduced, chats, onOpenScreen, desks, onFloorClick }: OfficeSceneProps & {
+ desks: ReturnType<typeof allDesks>;
+ onFloorClick: (event: ThreeEvent<MouseEvent>) => void;
+}) {
+ const t = useT();
// Lead desks carry their own size and are built as executive desks, not bench instances.
const benchDesks = useMemo(() => desks.filter((d) => !d.size), [desks]);
// Each desk takes its department's zone colour for the felt screen and the seat fabric.
@@ -111,26 +175,17 @@ export function OfficeScene({ floor, occupants, ready, layout, grid, walkers, ag
const leadRoom = layout.rooms.find((r) => r.kind === "lead");
const teamRoom = layout.rooms.find((r) => r.kind === "team");
const breakRoom = layout.rooms.find((r) => r.kind === "break");
- const dogBeds = useMemo(() => layout.furniture.filter((f) => f.kind === "dogBed"), [layout]);
- const treatJar = layout.furniture.find((f) => f.kind === "treatJar") ?? null;
const coding = floor === "coding";
// The coding floor floats in a violet night of its own, so a glance tells the floors apart.
const space = coding ? CODING_SCENE.space : OFFICE.space;
const background = useMemo(() => new Color(space), [space]);
const { minX, maxX, minZ, maxZ } = layout.bounds;
const span = Math.max(maxX - minX, maxZ - minZ);
- const select = useOfficeStore((s) => s.select);
const table = layout.furniture.find((f) => f.kind === "meetingTable");
const board = layout.furniture.find((f) => f.kind === "teamBoard");
const wardrobeRug = layout.furniture.find((f) => f.kind === "roundRug" && f.room === "wardrobe");
const lobbyLamp = layout.furniture.find((f) => f.kind === "lobbyLamp");
const spawnTerminal = layout.furniture.find((f) => f.kind === "spawnTerminal");
- const onFloorClick = (event: ThreeEvent<MouseEvent>) => {
- // A drag that ends on the floor rotated the camera; only a real click walks.
- if (event.delta > 6) return;
- event.stopPropagation();
- useOfficeStore.getState().requestWalk({ x: event.point.x, z: event.point.z });
- };
return (
<>
<primitive attach="background" object={background} />
@@ -170,24 +225,6 @@ export function OfficeScene({ floor, occupants, ready, layout, grid, walkers, ag
{wardrobeRug && <WardrobeFittings rug={wardrobeRug} />}
{lobbyLamp && <LobbyFittings lamp={lobbyLamp} />}
{spawnTerminal && <SpawnFittings terminal={spawnTerminal} arrival={layout.arrival} floor={floor} newcomers={newcomers} animate={awake && !reduced} />}
- {/* At the elevator its call button takes over from the floating token, which would hide it. */}
- {layout.checkpoints.filter((cp) => cp.id !== "elevator" || !atLift).map((cp) => (
- <CheckpointMarker key={cp.id} checkpoint={cp} label={t(`society.office.cp_${cp.id}`)} icon={CHECKPOINT_ICON[cp.id]}
- active={(nearby?.kind === "checkpoint" && nearby.id === cp.id) || (selection?.kind === "checkpoint" && selection.id === cp.id)}
- animate={awake && !reduced} onActivate={() => select({ kind: "checkpoint", id: cp.id })} />
- ))}
- {shaft && (
- <ElevatorCallButton shaft={shaft} floor={floor} lit={elevatorCall.lit} count={elevatorCall.count} animate={awake && !reduced}
- near={atLift} onPress={elevatorCall.onPress} />
- )}
- <FloorArrival floor={floor} layout={layout} grid={grid} ready={ready} />
- <OfficePlayer layout={layout} grid={grid} look={player.look} name={player.name} awake={awake} reduced={reduced} />
- {dogBeds.length > 0 && <OfficeDog beds={dogBeds} rooms={layout.rooms} jar={treatJar} grid={grid} awake={awake} reduced={reduced} />}
- <PlayerBubble height={OFFICE_FIGURE_HEIGHT_M + 0.49} />
- <OfficeAgents desks={desks} agents={agents} ctx={walkers} newcomers={newcomers} awake={awake} reduced={reduced} chats={chats}
- selectedId={selection?.kind === "agent" ? selection.id : null} onSelect={(id) => select({ kind: "agent", id })} />
- {floor === "coding" && <GigiCompanion grid={grid} awake={awake} reduced={reduced} />}
- <OfficeCameraRig layout={layout} overview={overview} />
</>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
index 5813894317..166e08dfa3 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
@@ -4,7 +4,8 @@
* real run state, and checkpoints turn rooms into actions: create, manage,
* team up, dress up, talk to the lead, call a coffee break. One elevator ride
* up is the coding floor: a figure per IDE coding session, its terminal live
- * on the monitor, and Gigi flying along with the person.
+ * on the monitor, and Gigi flying along with the person. The top floor is the
+ * arcade: a hall of retro cabinets, every one of them playable.
*/
import { Component, lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
@@ -25,7 +26,7 @@ import { CAMERA_FOV } from "./officeCamera";
import { ZOOM_SECONDS } from "./OfficeCameraRig";
import { useDeskChats } from "./useDeskChats";
import type { Point } from "./officeLayout";
-import { otherFloor, player, switchFloor, useOfficeStore, type OfficeFloor } from "./officeStore";
+import { floorLevel, player, switchFloor, useOfficeStore, type OfficeFloor } from "./officeStore";
import { agentPositions, seatedAtDesk } from "./walkerRegistry";
import { useCodingFloorOccupants, type PaneOccupant } from "./codingFloor";
import { openPaneSession } from "./codingNavigate";
@@ -38,6 +39,9 @@ import { PaneCommandPanel } from "./PaneCommandPanel";
import type { WalkerContext } from "./OfficeAgents";
import { ownsKeyboard } from "./OfficePlayer";
import { ArcadeCabinet } from "./ArcadeCabinet";
+import { ElevatorPanel } from "./ElevatorPanel";
+import { buildArcadeLayout } from "../arcade/arcadeFloorLayout";
+import { ARCADE_GAMES, gameForCabinet, type RetroGameId } from "../arcade/arcadeGames";
import { useOfficeSettings, useReceptionTab } from "./officeSettings";
import "./office.css";
import "./officeHud.css";
@@ -50,6 +54,8 @@ import { OfficeFrameDriver } from "./OfficeFrameDriver";
// Only loaded when a host without its own create dialog (the IDE's side panel) spawns an agent.
const CreateAgentDialog = lazy(() => import("../create/CreateAgentDialog").then((m) => ({ default: m.CreateAgentDialog })));
+// Only loaded when someone plays a retro cabinet on the arcade floor.
+const RetroArcadeOverlay = lazy(() => import("../arcade/RetroArcadeOverlay").then((m) => ({ default: m.RetroArcadeOverlay })));
// Dev-only handles for runtime checks of walking and panels.
if (import.meta.env.DEV && typeof window !== "undefined") Object.assign(window, { __officeStore: useOfficeStore, __officePlayer: player, __officeAgents: agentPositions, __officeSeated: seatedAtDesk,
@@ -131,8 +137,10 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
useState(() => { if (initialFloor) switchFloor(initialFloor, false); return null; });
const floor = useOfficeStore((s) => s.floor);
const coding = floor === "coding";
+ // The arcade floor has no agents: no roster, desks or chats, just the cabinets.
+ const arcade = floor === "arcade";
const roster = useSocietyRoster();
- useRosterRefresh(awake && !coding);
+ useRosterRefresh(awake && floor === "agents");
// Jarvis keeps the person company as the pet chosen in My Pets.
useSyncCompanionPet();
const [overview, setOverview] = useState(0);
@@ -148,8 +156,8 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
const codingFloor = useCodingFloorOccupants(coding || atLift);
const jarvisAgents = useMemo(() => (roster.data?.agents ?? []).filter((a) => a.lifecycle !== "archived"), [roster.data]);
const codingAgents = useMemo(() => codingFloor.occupants.map((o) => o.agent), [codingFloor.occupants]);
- const active = coding ? codingAgents : jarvisAgents;
- const ready = coding ? codingFloor.loaded : !!roster.data;
+ const active = useMemo(() => (arcade ? [] : coding ? codingAgents : jarvisAgents), [arcade, coding, codingAgents, jarvisAgents]);
+ const ready = arcade ? true : coding ? codingFloor.loaded : !!roster.data;
const occupants = useMemo(() => (coding ? codingFloor.byAgentId : EMPTY_OCCUPANTS), [coding, codingFloor.byAgentId]);
const occupantsRef = useRef(occupants);
occupantsRef.current = occupants;
@@ -158,7 +166,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
// The floor plan depends on who works where, never on run state: a status
// refresh changes monitors and behaviour without re-seating anyone.
const seatingKey = floor + ":" + active.map((a) => `${a.agentId}|${a.tier}|${a.providerLabel}|${a.createdMs}`).join(",");
- const layout = useMemo(() => buildOfficeLayout(active, { variant: floor }),
+ const layout = useMemo(() => (floor === "arcade" ? buildArcadeLayout() : buildOfficeLayout(active, { variant: floor })),
// eslint-disable-next-line react-hooks/exhaustive-deps
[seatingKey]);
const grid = useMemo(() => buildNavGrid(layout), [layout]);
@@ -179,7 +187,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
// Coding sessions have no desk chat; their monitors poll the terminal instead.
const sessions = useMemo(() => new Map(active.filter((a) => a.chatSessionId).map((a) => [a.agentId, a.chatSessionId as string])), [active]);
- const chats = useDeskChats(sessions, awake && !coding);
+ const chats = useDeskChats(sessions, awake && floor === "agents");
// Opening someone: a coding agent opens its IDE pane; a Jarvis agent its chat
// (a host without an agent view, like the IDE tab, goes to the Agents section).
const openAgent = useCallback((agentId: string) => {
@@ -225,24 +233,29 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
// The elevator: doors close, the floor switches behind them, doors open once
// the new floor has loaded (capped). Reduced motion switches at once.
- const [ride, setRide] = useState<{ to: OfficeFloor; phase: "closing" | "riding" | "opening" } | null>(null);
+ const [ride, setRide] = useState<{ to: OfficeFloor; up: boolean; phase: "closing" | "riding" | "opening" } | null>(null);
const rideTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => () => clearTimeout(rideTimer.current), []);
const takeElevator = useCallback((to: OfficeFloor) => {
- if (ride || to === useOfficeStore.getState().floor) return;
+ const from = useOfficeStore.getState().floor;
+ if (ride || to === from) return;
if (reduced) { switchFloor(to, true); return; }
useOfficeStore.getState().select(null);
- setRide({ to, phase: "closing" });
+ const up = floorLevel(to) > floorLevel(from);
+ setRide({ to, up, phase: "closing" });
rideTimer.current = setTimeout(() => {
switchFloor(to, true);
- setRide({ to, phase: "riding" });
- rideTimer.current = setTimeout(() => setRide((r) => (r?.phase === "riding" ? { to, phase: "opening" } : r)), RIDE_MAX_MS);
+ setRide({ to, up, phase: "riding" });
+ rideTimer.current = setTimeout(() => setRide((r) => (r?.phase === "riding" ? { ...r, phase: "opening" } : r)), RIDE_MAX_MS);
}, DOORS_MS);
}, [reduced, ride]);
// Riding takes a press of the call button beside the doors, standing at the
- // elevator. A press from afar (a click on the button, the floor token or E
- // anywhere) walks the character over instead; it never rides from a distance.
+ // elevator: the press opens the floor picker, picking a floor lights the
+ // button and the doors close. A press from afar (a click on the button, the
+ // floor token or E anywhere) walks the character over instead; it never
+ // rides from a distance.
const [callLit, setCallLit] = useState(false);
+ const [picking, setPicking] = useState(false);
const callTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => () => clearTimeout(callTimer.current), []);
const pressCall = useCallback(() => {
@@ -252,9 +265,17 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
if (lift) useOfficeStore.getState().requestWalk({ x: lift.x, z: lift.z });
return;
}
+ setPicking(true);
+ }, [ride, callLit, layout]);
+ const pickFloor = useCallback((to: OfficeFloor) => {
+ setPicking(false);
+ if (ride || callLit || to === useOfficeStore.getState().floor) return;
setCallLit(true);
- callTimer.current = setTimeout(() => { setCallLit(false); takeElevator(otherFloor(useOfficeStore.getState().floor)); }, CALL_PRESS_MS);
- }, [ride, callLit, layout, takeElevator]);
+ callTimer.current = setTimeout(() => { setCallLit(false); takeElevator(to); }, CALL_PRESS_MS);
+ }, [ride, callLit, takeElevator]);
+ const closePicker = useCallback(() => setPicking(false), []);
+ // The picker belongs to the floor it was opened on.
+ useEffect(() => { setPicking(false); }, [floor]);
// E at the elevator, or a click on its floor token, presses the button instead of opening a panel.
useEffect(() => {
if (selection?.kind !== "checkpoint" || selection.id !== "elevator") return;
@@ -264,7 +285,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
useEffect(() => {
if (ride?.phase === "riding" && floor === ride.to && ready) {
clearTimeout(rideTimer.current);
- rideTimer.current = setTimeout(() => setRide({ to: ride.to, phase: "opening" }), 160);
+ rideTimer.current = setTimeout(() => setRide({ ...ride, phase: "opening" }), 160);
}
if (ride?.phase === "opening") {
clearTimeout(rideTimer.current);
@@ -339,14 +360,26 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
const selectedAgent = selection?.kind === "agent" ? agents.get(selection.id) ?? null : null;
const selectedPane = selectedAgent ? occupants.get(selectedAgent.agentId) ?? null : null;
+ const nearbyGame = nearby?.kind === "arcade" ? gameForCabinet(nearby.id) : null;
const nearbyLabel = nearby
? nearby.kind === "agent"
? t(coding ? "society.office.prompt_pane" : "society.office.prompt_agent").replace("{0}", agents.get(nearby.id)?.name ?? "")
: nearby.kind === "arcade"
- ? t("society.office.arcade_prompt")
+ ? nearbyGame ? t("society.arcade.play_prompt").replace("{0}", nearbyGame.title) : t("society.office.arcade_prompt")
: t(`society.office.cp_${nearby.id}_hint`)
: null;
- const titleKey = coding ? "society.office.coding_title" : "society.office.title";
+ // Standing at a retro cabinet fetches its overlay, so pressing E opens it at once instead of after a chunk load.
+ const nearbyRetro = nearbyGame?.kind === "retro";
+ useEffect(() => { if (nearbyRetro) void import("../arcade/RetroArcadeOverlay"); }, [nearbyRetro]);
+ // The cabinet being played: the break room's (and the hall's Asteroid Run) open the 3D game, the others a retro game.
+ const playing = selection?.kind === "arcade" ? gameForCabinet(selection.id) : null;
+ const playsAsteroids = selection?.kind === "arcade" && (!playing || playing.kind === "asteroid3d");
+ const titleKey = arcade ? "society.office.arcade_floor_title" : coding ? "society.office.coding_title" : "society.office.title";
+ const floorCounts = useMemo<Record<OfficeFloor, string | null>>(() => ({
+ agents: roster.data ? t("society.office.subtitle").replace("{0}", String(jarvisAgents.length)) : null,
+ coding: codingFloor.loaded ? t("society.office.coding_subtitle").replace("{0}", String(codingFloor.occupants.length)) : null,
+ arcade: t("society.office.arcade_floor_subtitle").replace("{0}", String(ARCADE_GAMES.length)),
+ }), [t, roster.data, jarvisAgents.length, codingFloor.loaded, codingFloor.occupants.length]);
const playerName = profile.name.trim() || t("society.office.you");
const showHintBar = useOfficeSettings((s) => s.showHintBar);
const receptionOpen = selection?.kind === "checkpoint" && selection.id === "create";
@@ -371,8 +404,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
<OfficeScene floor={floor} occupants={occupants} ready={ready} layout={layout} grid={grid} walkers={walkers} agents={agents} newcomers={newcomers}
awake={awake} reduced={reduced} overview={overview} player={{ look: playerLook(profile), name: playerName }}
selection={selection} nearby={nearby} chats={chats} onOpenScreen={openScreen}
- elevatorCall={{ lit: callLit, onPress: pressCall,
- count: coding ? jarvisAgents.length : codingFloor.loaded ? codingFloor.occupants.length : null }} />
+ elevatorCall={{ lit: callLit, onPress: pressCall }} />
</Canvas>
</Suspense>
</RenderBoundary>
@@ -382,14 +414,17 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
<div className="office-hud office-hud-left" data-office-ui>
<div className="office-card office-title">
<strong>{t(titleKey)}</strong>
- <span>{t(coding ? "society.office.coding_subtitle" : "society.office.subtitle").replace("{0}", String(active.length))}</span>
+ <span>{arcade
+ ? t("society.office.arcade_floor_subtitle").replace("{0}", String(ARCADE_GAMES.length))
+ : t(coding ? "society.office.coding_subtitle" : "society.office.subtitle").replace("{0}", String(active.length))}</span>
</div>
- <div className="office-card office-counts" role="status" aria-live="polite">
+ {arcade && <p className="office-card office-note">{t("society.office.arcade_floor_hint")}</p>}
+ {!arcade && <div className="office-card office-counts" role="status" aria-live="polite">
<span data-tone="working"><i aria-hidden />{t("society.office.count_working").replace("{0}", String(counts.working))}</span>
<span data-tone="waiting"><i aria-hidden />{t("society.office.count_waiting").replace("{0}", String(counts.waiting))}</span>
<span data-tone="idle"><i aria-hidden />{t("society.office.count_idle").replace("{0}", String(counts.idle))}</span>
{counts.paused > 0 && <span data-tone="paused"><i aria-hidden />{t("society.office.count_paused").replace("{0}", String(counts.paused))}</span>}
- </div>
+ </div>}
{!coding && roster.data?.sample && <p className="office-card office-note">{t("society.office.sample")}</p>}
{coding && codingFloor.loaded && active.length === 0 && <p className="office-card office-note">{t("society.office.coding_empty")}</p>}
{active.length > MAX_SEATED && <p className="office-card office-note">{t("society.office.overflow").replace("{0}", String(MAX_SEATED))}</p>}
@@ -403,14 +438,20 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
onClick={toggleGuide}>
{t("society.office.guide.hud_button")}
</button>
- {(!coding || !compact || onOpenLedger) && (
+ {!arcade && (!coding || !compact || onOpenLedger) && (
<button type="button" className="office-button" onClick={openList}>
{t(coding ? (compact ? "society.office.ledger_coding" : "society.office.open_ide") : "society.office.ledger")}
</button>
)}
</div>
- {selection?.kind === "arcade" && <ArcadeCabinet onClose={() => select(null)} />}
+ {playsAsteroids && <ArcadeCabinet onClose={() => select(null)} />}
+ {playing && playing.kind === "retro" && (
+ <Suspense fallback={null}>
+ <RetroArcadeOverlay gameId={playing.id as RetroGameId} onClose={() => select(null)} />
+ </Suspense>
+ )}
+ {picking && !ride && <ElevatorPanel floor={floor} counts={floorCounts} onPick={pickFloor} onClose={closePicker} />}
{/* A coding session is a window of its own on the stage, not a panel in the corner slot. */}
{selection?.kind === "agent" && selectedPane && (
<PaneCommandPanel occupant={selectedPane} compact={compact} onOpen={() => openPaneSession(selectedPane.pane)} onClose={() => select(null)} />
@@ -425,7 +466,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
</div>
)}
- {nearbyLabel && !selection && (
+ {nearbyLabel && !selection && !picking && (
<button type="button" className="office-hud office-prompt" data-office-ui onClick={() => nearby && select(nearby)}>
<kbd>E</kbd>{nearbyLabel}
</button>
@@ -436,7 +477,9 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
<div className="office-elevator" data-phase={ride.phase} role="status" aria-live="polite">
<i className="office-elevator-door" data-side="left" aria-hidden />
<i className="office-elevator-door" data-side="right" aria-hidden />
- <span className="office-elevator-sign">{t(ride.to === "coding" ? "society.office.riding_up" : "society.office.riding_down")}</span>
+ <span className="office-elevator-sign">
+ {t(ride.up ? "society.office.riding_up_to" : "society.office.riding_down_to").replace("{0}", t(`society.office.floor_name_${ride.to}`))}
+ </span>
</div>
)}
{!compact && <OfficeMinimap layout={layout} agents={agents} selectedId={selection?.kind === "agent" ? selection.id : null}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/SpawnPoint.tsx b/jarvis/ui/web/frontend/src/components/society/office/SpawnPoint.tsx
index da95ea93b1..80138dab56 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/SpawnPoint.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/SpawnPoint.tsx
@@ -44,7 +44,10 @@ interface SpawnLook {
pad: string; speck: readonly string[]; padEdge: string; padBand: string;
}
-/** Downstairs the agents' Scandinavian oak, sage and bronze; upstairs the coding floor's walnut, plum and amber. */
+/**
+ * Downstairs the agents' Scandinavian oak, sage and bronze; upstairs the coding floor's walnut, plum and amber.
+ * The arcade floor has no spawn point; its entry only keeps the table complete (neon violet and cyan).
+ */
export const SPAWN_LOOKS: Record<OfficeFloor, SpawnLook> = {
agents: {
body: "#dcc49c", plinth: "#a88660", metal: "#c7a15e", bezel: "#23262b", glow: "#b8f0cf",
@@ -56,6 +59,11 @@ export const SPAWN_LOOKS: Record<OfficeFloor, SpawnLook> = {
screenTop: "#271b40", screenBottom: "#0f0a1d", text: "#fff1de", accent: "#f3b16b", accentDeep: "#241a3b",
pad: "#2e2638", speck: ["#3b3246", "#251f2e", "#c9a24a"], padEdge: "#c9a24a", padBand: "#f3b16b",
},
+ arcade: {
+ body: "#2a2348", plinth: "#15112a", metal: "#9b8cff", bezel: "#0e0c1f", glow: "#7df9ff",
+ screenTop: "#1c1540", screenBottom: "#0b0918", text: "#f4f1ff", accent: "#ff5fa2", accentDeep: "#1a1236",
+ pad: "#1a1430", speck: ["#2a1f4a", "#151027", "#7df9ff"], padEdge: "#9b8cff", padBand: "#ff5fa2",
+ },
};
interface SpawnMaterials {
diff --git a/jarvis/ui/web/frontend/src/components/society/office/minimap.ts b/jarvis/ui/web/frontend/src/components/society/office/minimap.ts
index d6e35b9c38..616be162ca 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/minimap.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/minimap.ts
@@ -324,6 +324,8 @@ const FURNITURE_PAINT: Partial<Record<FurnitureKind, string>> = {
brandWall: "#d2b286", agentTotem: "#2b2f33", lobbySofa: "#efe9de", lobbyArmchair: "#a8653a", lobbyTable: "#e7ddcc",
sideTable: "#f1eeea", lobbyLamp: "#c7a15e", oliveTree: MAP_PAINT.plant, awardCase: "#d2b286", entranceMat: "#3b3a37", lobbyRug: "#e8dfcf",
spawnPad: "#d8c08c", spawnTerminal: "#2b2f33",
+ retroCabinet: "#7c5cff", prizeCounter: "#d6457f", tokenMachine: "#e0b23a", clawMachine: "#ff5fa2", airHockey: "#3d8bff",
+ pinball: "#9b5cff", snackCounter: "#c47a3a",
};
export const STATE_RING: Record<MinimapAgentState, string> = {
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeControls.ts b/jarvis/ui/web/frontend/src/components/society/office/officeControls.ts
index 3e8cfa0ea1..03a4f03394 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeControls.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeControls.ts
@@ -7,6 +7,8 @@
* drawn as arrows; every other cap is printed as is.
*/
+import type { OfficeFloor } from "./officeStore";
+
export type ControlGroup = "move" | "camera" | "interact" | "map" | "arcade";
export interface OfficeControl {
@@ -35,11 +37,16 @@ export const OFFICE_CONTROLS: readonly OfficeControl[] = [
{ id: "sit", group: "interact", keys: [["E"]], agentsOnly: true },
{ id: "screen", group: "interact", keys: [["mouse:click"]] },
{ id: "close", group: "interact", keys: [["Esc"]] },
+ { id: "elevator_floor", group: "interact", keys: [["0", "1", "2"]] },
{ id: "map", group: "map", keys: [["M"]] },
{ id: "guide", group: "map", keys: [["H"]] },
{ id: "minimap_focus", group: "map", keys: [["mouse:click"]] },
{ id: "minimap_walk", group: "map", keys: [["mouse:double"]] },
{ id: "minimap_zoom", group: "map", keys: [["mouse:wheel"]] },
+ { id: "arcade_play", group: "arcade", keys: [["E"]] },
+ { id: "arcade_start", group: "arcade", keys: [["Enter"], ["Space"]] },
+ { id: "arcade_action", group: "arcade", keys: [["Space"], ["J"]] },
+ { id: "arcade_action_b", group: "arcade", keys: [["Shift"], ["K"]] },
{ id: "arcade_fly", group: "arcade", keys: [["W", "A", "S", "D"], ["ArrowUp", "ArrowLeft", "ArrowDown", "ArrowRight"]] },
{ id: "arcade_shoot", group: "arcade", keys: [["Space"]] },
{ id: "arcade_pause", group: "arcade", keys: [["P"]] },
@@ -60,6 +67,6 @@ export function arrowCap(cap: string): ArrowKey | null {
}
/** The controls of one group that apply on this floor. */
-export function controlsFor(group: ControlGroup, floor: "agents" | "coding"): OfficeControl[] {
+export function controlsFor(group: ControlGroup, floor: OfficeFloor): OfficeControl[] {
return OFFICE_CONTROLS.filter((c) => c.group === group && (!c.agentsOnly || floor === "agents"));
}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeFloors.css b/jarvis/ui/web/frontend/src/components/society/office/officeFloors.css
index 5ae5919512..0f8e153a8e 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeFloors.css
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeFloors.css
@@ -40,3 +40,20 @@
.office-stage-compact .office-panel-slot { top:auto; bottom:48px; right:8px; width:calc(100% - 16px); max-height:62%; }
.office-stage-compact .office-prompt { bottom:48px; max-width:calc(100% - 16px); font-size:12px; }
.office-stage-compact .office-note { font-size:11px; }
+
+/* The elevator's floor picker: a small panel in the middle of the stage, top floor first. */
+.office-lift-backdrop { position:absolute; inset:0; z-index:64; display:flex; align-items:center; justify-content:center; padding:16px; background:hsl(var(--background) / .35); }
+.office-lift { width:min(320px, 100%); padding:10px; display:flex; flex-direction:column; gap:8px; }
+.office-lift-head { display:flex; align-items:center; justify-content:space-between; gap:8px; padding:2px 2px 0 4px; }
+.office-lift-head h2 { margin:0; font-size:14px; font-weight:700; }
+.office-lift-floors { display:flex; flex-direction:column; gap:6px; }
+.office-lift-floor { display:flex; align-items:center; gap:10px; width:100%; padding:8px 10px; border:1px solid hsl(var(--border)); border-radius:10px; background:hsl(var(--background) / .6); color:inherit; text-align:left; cursor:pointer; }
+.office-lift-floor:hover:not(:disabled) { background:hsl(var(--accent)); color:hsl(var(--accent-foreground)); }
+.office-lift-floor:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }
+.office-lift-floor:disabled { cursor:default; opacity:.7; }
+.office-lift-number { flex:none; display:inline-flex; align-items:center; justify-content:center; width:30px; height:30px; border-radius:999px; border:2px solid hsl(var(--border)); font-weight:700; font-variant-numeric:tabular-nums; }
+.office-lift-floor:disabled .office-lift-number { border-color:#f5b83d; color:#f5b83d; box-shadow:0 0 8px rgb(245 184 61 / .45); }
+.office-lift-text { display:flex; flex-direction:column; min-width:0; }
+.office-lift-text b { font-size:13px; }
+.office-lift-text small { font-size:11px; color:hsl(var(--muted-foreground)); }
+.office-lift-keys { margin:0; padding:0 4px 2px; font-size:10px; color:hsl(var(--muted-foreground)); }
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeFloors.test.ts b/jarvis/ui/web/frontend/src/components/society/office/officeFloors.test.ts
index 7931b31f77..5a4ab41ef3 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeFloors.test.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeFloors.test.ts
@@ -2,7 +2,10 @@ import { afterEach, describe, expect, it } from "vitest";
import { buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";
import { buildNavGrid, isWalkable } from "./officeNav";
import { arrivalPose, knownOnFloor, noteArrivals } from "./officeFloors";
-import { officeSession, otherFloor, player, switchFloor, useOfficeStore } from "./officeStore";
+import { floorLevel, OFFICE_FLOORS, officeSession, player, switchFloor, useOfficeStore } from "./officeStore";
+import { floorForKey, PANEL_FLOORS } from "./ElevatorPanel";
+import { callDirection } from "./ElevatorCallButton";
+import { buildArcadeLayout } from "../arcade/arcadeFloorLayout";
const AGENTS: OfficeAgentInput[] = [
{ agentId: "a1", name: "One", tier: "specialist", providerLabel: "Codex", state: "working", createdMs: 1 },
@@ -20,14 +23,27 @@ function resetBuilding() {
afterEach(resetBuilding);
describe("floors", () => {
- it("names the other floor", () => {
- expect(otherFloor("agents")).toBe("coding");
- expect(otherFloor("coding")).toBe("agents");
+ it("stacks the floors bottom to top, and the elevator panel lists them top first", () => {
+ expect(OFFICE_FLOORS).toEqual(["agents", "coding", "arcade"]);
+ expect(OFFICE_FLOORS.map(floorLevel)).toEqual([0, 1, 2]);
+ expect(PANEL_FLOORS).toEqual(["arcade", "coding", "agents"]);
+ expect(callDirection("agents")).toBe("up");
+ expect(callDirection("coding")).toBe("both");
+ expect(callDirection("arcade")).toBe("down");
});
- it("steps out of the elevator onto walkable floor, facing away from the doors, on both floors", () => {
- for (const variant of ["agents", "coding"] as const) {
- const layout = buildOfficeLayout(AGENTS, { variant });
+ it("picks a floor by its number key", () => {
+ expect(floorForKey("0")).toBe("agents");
+ expect(floorForKey("1")).toBe("coding");
+ expect(floorForKey("2")).toBe("arcade");
+ expect(floorForKey("3")).toBeNull();
+ expect(floorForKey("e")).toBeNull();
+ expect(floorForKey("12")).toBeNull();
+ });
+
+ it("steps out of the elevator onto walkable floor, facing away from the doors, on every floor", () => {
+ for (const variant of ["agents", "coding", "arcade"] as const) {
+ const layout = variant === "arcade" ? buildArcadeLayout() : buildOfficeLayout(AGENTS, { variant });
const stop = layout.checkpoints.find((cp) => cp.id === "elevator");
expect(stop, variant).toBeDefined();
const pose = arrivalPose(layout, "elevator");
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeFloors.ts b/jarvis/ui/web/frontend/src/components/society/office/officeFloors.ts
index 098f4814ed..5859b7096f 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeFloors.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeFloors.ts
@@ -1,7 +1,8 @@
/**
- * The building has two floors joined by an elevator: the Jarvis agents office
- * and, one ride up, the coding floor with a figure per IDE coding session.
- * Pure helpers for what differs per floor; the stage wires them.
+ * The building has three floors joined by an elevator: the Jarvis agents
+ * office, one ride up the coding floor with a figure per IDE coding session,
+ * and on top the arcade hall. Pure helpers for what differs per floor; the
+ * stage wires them.
*/
import type { OfficeLayout } from "./officeLayout";
import type { OfficeFloor } from "./officeStore";
@@ -27,8 +28,9 @@ export function arrivalPose(layout: OfficeLayout, at: "elevator" | "remembered",
/** Agent ids each floor has already seen; a newcomer on that floor arrives by the elevator. */
const codingKnown = new Set<string>();
+const arcadeKnown = new Set<string>();
export function knownOnFloor(floor: OfficeFloor): Set<string> {
- return floor === "agents" ? knownAgents : codingKnown;
+ return floor === "agents" ? knownAgents : floor === "coding" ? codingKnown : arcadeKnown;
}
/**
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts b/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts
index a2023fc786..bef5188cbd 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeLayout.ts
@@ -64,11 +64,14 @@ export interface Department extends Rect {
tint: number;
}
-/** "command" (Mission Control) and "server" only exist on the coding floor, in place of the lead office and the wardrobe. */
-export type RoomKind = "lead" | "team" | "wardrobe" | "reception" | "break" | "command" | "server";
+/**
+ * "command" (Mission Control) and "server" only exist on the coding floor, in place of the lead office and the wardrobe.
+ * "arcade" (the main hall), "prizes" (the prize counter corner) and "snack" (the snack bar) only exist on the arcade floor.
+ */
+export type RoomKind = "lead" | "team" | "wardrobe" | "reception" | "break" | "command" | "server" | "arcade" | "prizes" | "snack";
-/** Which floor a layout draws: the society agents' office, or the coding agents' floor above it. */
-export type OfficeVariant = "agents" | "coding";
+/** Which floor a layout draws: the society agents' office, the coding agents' floor above it, or the arcade floor on top. */
+export type OfficeVariant = "agents" | "coding" | "arcade";
export interface Door { side: "north" | "south" | "east" | "west"; /** Centre of the gap along the wall. */ at: number; width: number }
@@ -128,7 +131,10 @@ export type FurnitureKind =
| "brandWall" | "agentTotem" | "lobbySofa" | "lobbyArmchair" | "lobbyTable" | "sideTable" | "lobbyLamp" | "oliveTree"
| "awardCase" | "entranceMat" | "lobbyRug"
// The spawn point in the middle of both floors: the flat pad and the terminal standing on it.
- | "spawnPad" | "spawnTerminal";
+ | "spawnPad" | "spawnTerminal"
+ // Arcade floor: the playable game cabinets (id `cabinet-<gameId>`, see arcade/arcadeGames.ts), the prize
+ // counter, the token changer, a claw machine, an air-hockey table, a pinball machine and a snack-bar counter.
+ | "retroCabinet" | "prizeCounter" | "tokenMachine" | "clawMachine" | "airHockey" | "pinball" | "snackCounter";
/**
* Footprint (x-extent × z-extent before rotation) and height of each piece.
@@ -217,6 +223,14 @@ export const FURNITURE_SIZE: Record<FurnitureKind, { w: number; d: number; h: nu
// tops out at 2.2 m). The pad fits the 3.2 m aisle crossing with a margin to every department.
spawnPad: { w: 2 * 1.42, d: 2 * 1.42, h: 0.02, solid: false },
spawnTerminal: { w: 1.2, d: 0.7, h: 2.2, solid: true },
+ // Arcade floor. A cabinet's screen and controls face its local +z; the person plays standing in front of it.
+ retroCabinet: { w: 0.8, d: 0.8, h: 1.95, solid: true },
+ prizeCounter: { w: 3.4, d: 0.9, h: 2.2, solid: true },
+ tokenMachine: { w: 0.6, d: 0.5, h: 1.7, solid: true },
+ clawMachine: { w: 1.0, d: 1.0, h: 2.0, solid: true },
+ airHockey: { w: 2.1, d: 1.2, h: 0.95, solid: true },
+ pinball: { w: 0.75, d: 1.45, h: 1.9, solid: true },
+ snackCounter: { w: 2.6, d: 0.8, h: 1.1, solid: true },
};
/**
@@ -457,7 +471,7 @@ export function footprint(item: Pick<Furniture, "x" | "z" | "kind" | "rotationY"
return { minX: item.x - w / 2, maxX: item.x + w / 2, minZ: item.z - d / 2, maxZ: item.z + d / 2 };
}
-function wallsOf(room: Room): WallSegment[] {
+export function wallsOf(room: Room): WallSegment[] {
if (!room.walled) return [];
const sides: { side: Door["side"]; a: Point; b: Point }[] = [
{ side: "north", a: { x: room.minX, z: room.minZ }, b: { x: room.maxX, z: room.minZ } },
@@ -495,7 +509,7 @@ export function archPosts(room: Rect): Point[] {
return [{ x: cx - ARCH.halfSpan, z }, { x: cx + ARCH.halfSpan, z }];
}
-function wallRect(w: WallSegment): Rect {
+export function wallRect(w: WallSegment): Rect {
const t = WALL_THICKNESS / 2;
return { minX: Math.min(w.x1, w.x2) - t, maxX: Math.max(w.x1, w.x2) + t, minZ: Math.min(w.z1, w.z2) - t, maxZ: Math.max(w.z1, w.z2) + t };
}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officePalette.ts b/jarvis/ui/web/frontend/src/components/society/office/officePalette.ts
index 08522a0c53..93edc87c0d 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officePalette.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officePalette.ts
@@ -170,6 +170,10 @@ export const ROOM_FLOOR_COLOURS = {
// Mission Control: dark graphite microcement.
command: { base: "#454b54", accents: ["#3e444c", "#4d535c", "#41474f", "#51575f"] },
server: { base: "#c3c8cf", accents: ["#c9ced4", "#bcc2c9"] },
+ // Arcade floor: the hall's midnight carpet, the prize corner's plum, the snack bar's checker red.
+ arcade: { base: "#1a1430", accents: ["#211a3d", "#151027", "#2a1f4a"] },
+ prizes: { base: "#3a1838", accents: ["#431c41", "#33152f"] },
+ snack: { base: "#5a1e22", accents: ["#e9e2d6", "#4c191c"] },
} as const;
/** Checkpoint gold: floor ring, hexagon token and the label badge. */
diff --git a/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts b/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts
index 08d1f2cb40..a067de3ae7 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts
+++ b/jarvis/ui/web/frontend/src/components/society/office/officeStore.ts
@@ -11,13 +11,17 @@ import type { CheckpointKind, Point } from "./officeLayout";
/** `arcade` is a playable arcade cabinet, by furniture id. */
export type Selection = { kind: "agent"; id: string } | { kind: "checkpoint"; id: CheckpointKind } | { kind: "arcade"; id: string };
-/** The two floors of the building: the Jarvis agents office and, one elevator ride up, the coding agents. */
-export type OfficeFloor = "agents" | "coding";
+/**
+ * The floors of the building, bottom to top: the Jarvis agents office, the
+ * coding agents one elevator ride up, and the arcade hall on the top floor.
+ */
+export type OfficeFloor = "agents" | "coding" | "arcade";
-export const OFFICE_FLOORS: readonly OfficeFloor[] = ["agents", "coding"];
+export const OFFICE_FLOORS: readonly OfficeFloor[] = ["agents", "coding", "arcade"];
-export function otherFloor(floor: OfficeFloor): OfficeFloor {
- return floor === "agents" ? "coding" : "agents";
+/** The floor number shown in the elevator (0 = ground floor). */
+export function floorLevel(floor: OfficeFloor): number {
+ return OFFICE_FLOORS.indexOf(floor);
}
export interface PlayerBody { x: number; z: number; heading: number; path: Point[]; moving: boolean }
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
index b8e72e7765..cd745c68d9 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
@@ -818,6 +818,20 @@
"cp_break_hint": "Kaffeepause ausrufen",
"cp_elevator": "Aufzug",
"cp_elevator_hint": "Den Ruf-Knopf neben den Türen drücken",
+ "elevator_choose": "Etage wählen",
+ "elevator_here": "Du bist hier",
+ "elevator_keys": "0–2 wählt die Etage · ↑/↓ wechseln · Esc schließt",
+ "floor_name_agents": "Agenten-Etage",
+ "floor_name_coding": "Coding-Etage",
+ "floor_name_arcade": "Arcade-Etage",
+ "floor_about_agents": "Deine Jarvis-Agenten bei der Arbeit",
+ "floor_about_coding": "Coding-Sessions aus der IDE",
+ "floor_about_arcade": "Retro-Automaten zum Spielen",
+ "riding_up_to": "Aufwärts · {0}",
+ "riding_down_to": "Abwärts · {0}",
+ "arcade_floor_title": "Arcade-Etage",
+ "arcade_floor_subtitle": "Spielbare Automaten: {0}",
+ "arcade_floor_hint": "Geh zu einem Automaten und drück E zum Spielen",
"cp_spawn": "Spawn-Punkt",
"cp_spawn_hint": "Einen neuen Jarvis-Agenten spawnen",
"cp_launch": "Spawn-Punkt",
@@ -861,6 +875,7 @@
"ctl_sit": "Auf den Chefsessel setzen; E noch einmal steht auf",
"ctl_screen": "Monitor anklicken öffnet den Chat dieses Agenten",
"ctl_close": "Panel oder Karte schließen",
+ "ctl_elevator_floor": "Etage im Aufzug wählen",
"ctl_map": "Große Karte öffnen oder schließen",
"ctl_guide": "Diese Hilfe öffnen oder schließen",
"ctl_minimap_focus": "Minikarte anklicken, um dorthin zu schauen",
@@ -870,6 +885,10 @@
"ctl_arcade_shoot": "Schießen oder Runde starten",
"ctl_arcade_pause": "Pause",
"ctl_arcade_leave": "Arcade verlassen",
+ "ctl_arcade_play": "Den Automaten vor dir spielen",
+ "ctl_arcade_start": "Spiel starten oder neu starten",
+ "ctl_arcade_action": "Hauptknopf: feuern, springen, drehen",
+ "ctl_arcade_action_b": "Zweiter Knopf: fallen lassen, Bombe, wechseln",
"mouse_click": "Klick",
"mouse_double": "Doppelklick",
"mouse_drag": "Ziehen",
@@ -894,12 +913,8 @@
"coding_title": "Coding-Etage",
"coding_subtitle": "Coding-Sessions auf der Etage: {0}",
"coding_empty": "Kein Coding-Agent läuft. Starte einen in der IDE, dann bekommt er hier einen Schreibtisch.",
- "floor_up": "Hoch zur Coding-Etage",
- "floor_down": "Runter zur Agenten-Etage",
"ledger_coding": "Session-Liste",
"open_ide": "IDE öffnen",
- "riding_up": "Fahrt hoch zur Coding-Etage",
- "riding_down": "Fahrt runter zur Agenten-Etage",
"prompt_pane": "Nach {0} sehen",
"since_now": "gerade eben",
"since_minutes": "seit {0} Min.",
@@ -1007,8 +1022,6 @@
"fleet_result": "{0} von {1} erreicht.",
"fleet_result_missed": "Nicht erreicht: {0}",
"elevator_press": "Knopf anklicken",
- "elevator_up_count": "Gerade oben: {0}",
- "elevator_down_count": "Gerade unten: {0}",
"arcade_prompt": "Asteroid Run spielen",
"arcade_title": "Asteroid Run",
"arcade_score": "Punkte",
@@ -1028,6 +1041,9 @@
"room_reception": "Empfang",
"room_break": "Pausenraum",
"room_server": "Serverraum",
+ "room_arcade": "Spielhalle",
+ "room_prizes": "Preistheke",
+ "room_snack": "Snackbar",
"dog_treat": "Knochen geben",
"dog_take_bone": "Leckerli nehmen",
"dog_pet": "Hund streicheln",
@@ -1167,6 +1183,74 @@
"errand_flying": "Bringt {0} eine Aufgabe",
"errand_task": "Hier ist eine neue Aufgabe für dich.",
"errand_ack": "Verstanden, bin dran!"
+ },
+ "arcade": {
+ "play_prompt": "{0} spielen",
+ "score": "Punkte",
+ "best": "Rekord",
+ "lives": "Leben",
+ "level": "Level",
+ "loading": "Spiel wird geladen …",
+ "load_failed": "Dieses Spiel konnte nicht geladen werden.",
+ "retry": "Erneut versuchen",
+ "press_start": "Leertaste oder Enter zum Starten",
+ "tap_start": "Tippe auf A zum Starten",
+ "paused": "Pause",
+ "resume_hint": "P oder Leertaste zum Weiterspielen",
+ "tap_resume": "Tippe auf A zum Weiterspielen",
+ "game_over": "Game over",
+ "you_win": "Gewonnen!",
+ "new_best": "Neuer Rekord!",
+ "play_again": "Leertaste oder Enter für eine neue Runde",
+ "tap_again": "Tippe auf A für eine neue Runde",
+ "keys_hint": "Enter Start · P Pause · Esc / E verlassen",
+ "pause": "Pause",
+ "pad_up": "Hoch",
+ "pad_down": "Runter",
+ "pad_left": "Links",
+ "pad_right": "Rechts",
+ "games": {
+ "asteroid_run": {
+ "tagline": "Flieg durchs Asteroidenfeld und schieß dir den Weg frei.",
+ "how": "WASD/Pfeile lenken · Leertaste Laser · Klick auf einen Felsen: Rakete · Shift Boost · P Pause · Esc verlassen"
+ },
+ "neon_snake": {
+ "tagline": "Fressen, wachsen und nie in den eigenen Schwanz beißen.",
+ "how": "Pfeile/WASD lenken · P Pause · Esc verlassen"
+ },
+ "brick_breaker": {
+ "tagline": "Zerschlag jeden Stein, fang die Extras.",
+ "how": "←/→ oder Maus bewegen · Leertaste/Klick abschießen · P Pause · Esc verlassen"
+ },
+ "paddle_duel": {
+ "tagline": "Wer zuerst sieben hat, schlägt die Maschine.",
+ "how": "↑/↓ oder Maus bewegen · Leertaste aufschlagen · P Pause · Esc verlassen"
+ },
+ "block_drop": {
+ "tagline": "Stapel die fallenden Blöcke und räume volle Reihen ab.",
+ "how": "←/→ bewegen · ↑/Leertaste drehen · ↓ schneller fallen · Shift sofort ablegen · P Pause · Esc verlassen"
+ },
+ "maze_muncher": {
+ "tagline": "Futtere jeden Punkt und überliste vier Glitch-Käfer.",
+ "how": "Pfeiltasten lenken (Abbiegen wird vorgemerkt) · Kraftkugeln machen die Käfer essbar · P Pause · Esc verlassen"
+ },
+ "desert_dash": {
+ "tagline": "Sprinte über die Dünen: spring über Kakteen, duck dich vor Vögeln.",
+ "how": "↑/Leertaste springen (halten für höher) · ↓ ducken / schneller landen · P Pause · Esc verlassen"
+ },
+ "pixel_raiders": {
+ "tagline": "Halte die Stellung gegen eine marschierende Alien-Flotte.",
+ "how": "←/→ bewegen · Leertaste feuern · P Pause · Esc verlassen"
+ },
+ "road_hopper": {
+ "tagline": "Hüpf über Straße und Fluss nach Hause.",
+ "how": "Pfeiltasten hüpfen · P Pause · Esc verlassen"
+ },
+ "city_defense": {
+ "tagline": "Schieß die Sprengköpfe ab, bevor sie deine Städte treffen.",
+ "how": "Maus zielen + Klick feuern · Pfeiltasten zielen · Leertaste feuern · Shift Batterie wählen · P Pause · Esc verlassen"
+ }
+ }
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
index 60fc39fa7d..0ebdaa64df 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
@@ -818,6 +818,20 @@
"cp_break_hint": "Call a coffee break",
"cp_elevator": "Elevator",
"cp_elevator_hint": "Press the call button beside the doors",
+ "elevator_choose": "Choose a floor",
+ "elevator_here": "You are here",
+ "elevator_keys": "0–2 picks a floor · ↑/↓ move · Esc closes",
+ "floor_name_agents": "Agents floor",
+ "floor_name_coding": "Coding floor",
+ "floor_name_arcade": "Arcade floor",
+ "floor_about_agents": "Your Jarvis agents at work",
+ "floor_about_coding": "Coding sessions from the IDE",
+ "floor_about_arcade": "Retro cabinets to play",
+ "riding_up_to": "Going up · {0}",
+ "riding_down_to": "Going down · {0}",
+ "arcade_floor_title": "Arcade floor",
+ "arcade_floor_subtitle": "Playable cabinets: {0}",
+ "arcade_floor_hint": "Walk up to a cabinet and press E to play",
"cp_spawn": "Spawn point",
"cp_spawn_hint": "Spawn a new Jarvis agent",
"cp_launch": "Spawn point",
@@ -861,6 +875,7 @@
"ctl_sit": "Sit in the lead chair; E again stands up",
"ctl_screen": "Click a monitor to open that agent's chat",
"ctl_close": "Close a panel or the map",
+ "ctl_elevator_floor": "Pick a floor in the elevator",
"ctl_map": "Open or close the big map",
"ctl_guide": "Open or close this help",
"ctl_minimap_focus": "Click the minimap to look there",
@@ -870,6 +885,10 @@
"ctl_arcade_shoot": "Shoot, or start a round",
"ctl_arcade_pause": "Pause",
"ctl_arcade_leave": "Leave the arcade",
+ "ctl_arcade_play": "Play the cabinet in front of you",
+ "ctl_arcade_start": "Start or restart a game",
+ "ctl_arcade_action": "Main button: fire, jump, rotate",
+ "ctl_arcade_action_b": "Second button: drop, bomb, switch",
"mouse_click": "Click",
"mouse_double": "Double-click",
"mouse_drag": "Drag",
@@ -894,12 +913,8 @@
"coding_title": "Coding floor",
"coding_subtitle": "Coding sessions on the floor: {0}",
"coding_empty": "No coding agent is running. Start one in the IDE and it takes a desk here.",
- "floor_up": "Up to the coding floor",
- "floor_down": "Down to the agents floor",
"ledger_coding": "Sessions list",
"open_ide": "Open the IDE",
- "riding_up": "Going up to the coding floor",
- "riding_down": "Going down to the agents floor",
"prompt_pane": "Check on {0}",
"since_now": "just now",
"since_minutes": "for {0} min",
@@ -1007,8 +1022,6 @@
"fleet_result": "Reached {0} of {1}.",
"fleet_result_missed": "Not reached: {0}",
"elevator_press": "Click the button",
- "elevator_up_count": "Upstairs right now: {0}",
- "elevator_down_count": "Downstairs right now: {0}",
"arcade_prompt": "Play Asteroid Run",
"arcade_title": "Asteroid Run",
"arcade_score": "Score",
@@ -1028,6 +1041,9 @@
"room_reception": "Reception",
"room_break": "Break room",
"room_server": "Server room",
+ "room_arcade": "Arcade hall",
+ "room_prizes": "Prize counter",
+ "room_snack": "Snack bar",
"dog_treat": "Give the bone",
"dog_take_bone": "Take a dog treat",
"dog_pet": "Pet the dog",
@@ -1167,6 +1183,74 @@
"errand_flying": "Taking {0} a task",
"errand_task": "Here is a new task for you.",
"errand_ack": "Got it, on it!"
+ },
+ "arcade": {
+ "play_prompt": "Play {0}",
+ "score": "Score",
+ "best": "Best",
+ "lives": "Lives",
+ "level": "Level",
+ "loading": "Loading game…",
+ "load_failed": "This game could not be loaded.",
+ "retry": "Try again",
+ "press_start": "Press Space or Enter to start",
+ "tap_start": "Tap A to start",
+ "paused": "Paused",
+ "resume_hint": "Press P or Space to resume",
+ "tap_resume": "Tap A to resume",
+ "game_over": "Game over",
+ "you_win": "You win!",
+ "new_best": "New best!",
+ "play_again": "Press Space or Enter to play again",
+ "tap_again": "Tap A to play again",
+ "keys_hint": "Enter start · P pause · Esc / E leave",
+ "pause": "Pause",
+ "pad_up": "Up",
+ "pad_down": "Down",
+ "pad_left": "Left",
+ "pad_right": "Right",
+ "games": {
+ "asteroid_run": {
+ "tagline": "Fly through the asteroid field and blast your way out.",
+ "how": "WASD/arrows steer · Space lasers · Click a rock: missile · Shift boost · P pause · Esc leave"
+ },
+ "neon_snake": {
+ "tagline": "Eat, grow, and never bite your own tail.",
+ "how": "Arrows/WASD steer · P pause · Esc leave"
+ },
+ "brick_breaker": {
+ "tagline": "Smash every brick, catch the power-ups.",
+ "how": "←/→ or mouse move · Space/click launch · P pause · Esc leave"
+ },
+ "paddle_duel": {
+ "tagline": "First to seven beats the machine.",
+ "how": "↑/↓ or mouse move · Space serve · P pause · Esc leave"
+ },
+ "block_drop": {
+ "tagline": "Stack the falling blocks and clear full lines.",
+ "how": "←/→ move · ↑/Space rotate · ↓ soft drop · Shift hard drop · P pause · Esc leave"
+ },
+ "maze_muncher": {
+ "tagline": "Munch every dot and outsmart four glitch bugs.",
+ "how": "Arrows steer (turns are buffered) · power orbs make the bugs edible · P pause · Esc leave"
+ },
+ "desert_dash": {
+ "tagline": "Dash across the dunes: jump the cacti, duck the birds.",
+ "how": "↑/Space jump (hold for higher) · ↓ duck / dive · P pause · Esc leave"
+ },
+ "pixel_raiders": {
+ "tagline": "Hold the line against a marching alien fleet.",
+ "how": "←/→ move · Space fire · P pause · Esc leave"
+ },
+ "road_hopper": {
+ "tagline": "Hop across the traffic and the river to get home.",
+ "how": "Arrows hop · P pause · Esc leave"
+ },
+ "city_defense": {
+ "tagline": "Shoot down the warheads before they reach your cities.",
+ "how": "Mouse aim + click fire · Arrows aim · Space fire · Shift pick battery · P pause · Esc leave"
+ }
+ }
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
index 37f8b9b17b..b1a45cc04c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
@@ -818,6 +818,20 @@
"cp_break_hint": "Hacer una pausa de café",
"cp_elevator": "Ascensor",
"cp_elevator_hint": "Pulsa el botón de llamada junto a las puertas",
+ "elevator_choose": "Elige una planta",
+ "elevator_here": "Estás aquí",
+ "elevator_keys": "0–2 elige planta · ↑/↓ moverse · Esc cierra",
+ "floor_name_agents": "Planta de agentes",
+ "floor_name_coding": "Planta de código",
+ "floor_name_arcade": "Planta arcade",
+ "floor_about_agents": "Tus agentes de Jarvis trabajando",
+ "floor_about_coding": "Sesiones de código del IDE",
+ "floor_about_arcade": "Máquinas retro para jugar",
+ "riding_up_to": "Subiendo · {0}",
+ "riding_down_to": "Bajando · {0}",
+ "arcade_floor_title": "Planta arcade",
+ "arcade_floor_subtitle": "Máquinas jugables: {0}",
+ "arcade_floor_hint": "Acércate a una máquina y pulsa E para jugar",
"cp_spawn": "Punto de aparición",
"cp_spawn_hint": "Crea un nuevo agente de Jarvis",
"cp_launch": "Punto de aparición",
@@ -861,6 +875,7 @@
"ctl_sit": "Sentarte en la silla del líder; E otra vez te levanta",
"ctl_screen": "Haz clic en un monitor para abrir el chat de ese agente",
"ctl_close": "Cerrar un panel o el mapa",
+ "ctl_elevator_floor": "Elegir planta en el ascensor",
"ctl_map": "Abrir o cerrar el mapa grande",
"ctl_guide": "Abrir o cerrar esta ayuda",
"ctl_minimap_focus": "Haz clic en el minimapa para mirar allí",
@@ -870,6 +885,10 @@
"ctl_arcade_shoot": "Disparar o empezar una partida",
"ctl_arcade_pause": "Pausa",
"ctl_arcade_leave": "Salir del arcade",
+ "ctl_arcade_play": "Jugar a la máquina que tienes delante",
+ "ctl_arcade_start": "Empezar o reiniciar una partida",
+ "ctl_arcade_action": "Botón principal: disparar, saltar, girar",
+ "ctl_arcade_action_b": "Segundo botón: soltar, bomba, cambiar",
"mouse_click": "Clic",
"mouse_double": "Doble clic",
"mouse_drag": "Arrastrar",
@@ -894,12 +913,8 @@
"coding_title": "Planta de código",
"coding_subtitle": "Sesiones de código en la planta: {0}",
"coding_empty": "No hay ningún agente de código en marcha. Inicia uno en el IDE y ocupará un escritorio aquí.",
- "floor_up": "Subir a la planta de código",
- "floor_down": "Bajar a la planta de agentes",
"ledger_coding": "Lista de sesiones",
"open_ide": "Abrir el IDE",
- "riding_up": "Subiendo a la planta de código",
- "riding_down": "Bajando a la planta de agentes",
"prompt_pane": "Ver a {0}",
"since_now": "ahora mismo",
"since_minutes": "desde hace {0} min",
@@ -1007,8 +1022,6 @@
"fleet_result": "Alcanzados {0} de {1}.",
"fleet_result_missed": "No alcanzados: {0}",
"elevator_press": "Haz clic en el botón",
- "elevator_up_count": "Arriba ahora mismo: {0}",
- "elevator_down_count": "Abajo ahora mismo: {0}",
"arcade_prompt": "Jugar a Asteroid Run",
"arcade_title": "Asteroid Run",
"arcade_score": "Puntos",
@@ -1028,6 +1041,9 @@
"room_reception": "Recepción",
"room_break": "Sala de descanso",
"room_server": "Sala de servidores",
+ "room_arcade": "Sala arcade",
+ "room_prizes": "Mostrador de premios",
+ "room_snack": "Bar de aperitivos",
"dog_treat": "Darle el hueso",
"dog_take_bone": "Coger una golosina",
"dog_pet": "Acariciar al perro",
@@ -1167,6 +1183,74 @@
"errand_flying": "Lleva una tarea a {0}",
"errand_task": "Aquí tienes una tarea nueva.",
"errand_ack": "¡Entendido, voy!"
+ },
+ "arcade": {
+ "play_prompt": "Jugar a {0}",
+ "score": "Puntos",
+ "best": "Récord",
+ "lives": "Vidas",
+ "level": "Nivel",
+ "loading": "Cargando juego…",
+ "load_failed": "No se pudo cargar este juego.",
+ "retry": "Reintentar",
+ "press_start": "Pulsa Espacio o Intro para empezar",
+ "tap_start": "Toca A para empezar",
+ "paused": "En pausa",
+ "resume_hint": "Pulsa P o Espacio para continuar",
+ "tap_resume": "Toca A para continuar",
+ "game_over": "Fin del juego",
+ "you_win": "¡Has ganado!",
+ "new_best": "¡Nuevo récord!",
+ "play_again": "Pulsa Espacio o Intro para jugar otra vez",
+ "tap_again": "Toca A para jugar otra vez",
+ "keys_hint": "Intro empezar · P pausa · Esc / E salir",
+ "pause": "Pausa",
+ "pad_up": "Arriba",
+ "pad_down": "Abajo",
+ "pad_left": "Izquierda",
+ "pad_right": "Derecha",
+ "games": {
+ "asteroid_run": {
+ "tagline": "Vuela por el campo de asteroides y ábrete paso a disparos.",
+ "how": "WASD/flechas dirigir · Espacio láser · Clic en una roca: misil · Shift turbo · P pausa · Esc salir"
+ },
+ "neon_snake": {
+ "tagline": "Come, crece y nunca te muerdas la cola.",
+ "how": "Flechas/WASD dirigir · P pausa · Esc salir"
+ },
+ "brick_breaker": {
+ "tagline": "Rompe cada ladrillo y atrapa los potenciadores.",
+ "how": "←/→ o ratón mover · Espacio/clic lanzar · P pausa · Esc salir"
+ },
+ "paddle_duel": {
+ "tagline": "El primero en llegar a siete vence a la máquina.",
+ "how": "↑/↓ o ratón mover · Espacio sacar · P pausa · Esc salir"
+ },
+ "block_drop": {
+ "tagline": "Apila los bloques que caen y limpia las líneas completas.",
+ "how": "←/→ mover · ↑/Espacio girar · ↓ bajar rápido · Shift caída directa · P pausa · Esc salir"
+ },
+ "maze_muncher": {
+ "tagline": "Come todos los puntos y burla a cuatro bichos glitch.",
+ "how": "Flechas para girar (los giros se guardan) · los orbes de poder vuelven comestibles a los bichos · P pausa · Esc salir"
+ },
+ "desert_dash": {
+ "tagline": "Corre por las dunas: salta los cactus y agáchate ante los pájaros.",
+ "how": "↑/Espacio saltar (mantén para más altura) · ↓ agacharse / caer rápido · P pausa · Esc salir"
+ },
+ "pixel_raiders": {
+ "tagline": "Resiste a una flota alienígena en plena marcha.",
+ "how": "←/→ mover · Espacio disparar · P pausa · Esc salir"
+ },
+ "road_hopper": {
+ "tagline": "Salta entre el tráfico y el río para llegar a casa.",
+ "how": "Flechas saltar · P pausa · Esc salir"
+ },
+ "city_defense": {
+ "tagline": "Derriba las cabezas nucleares antes de que alcancen tus ciudades.",
+ "how": "Ratón apuntar + clic disparar · Flechas apuntar · Espacio disparar · Shift elegir batería · P pausa · Esc salir"
+ }
+ }
}
}
}