1
0
Fork 0
polaris-task-force/src/components/frontend/minigames/bomperator/BomperatorGame.tsx
Z8MB1E ce682becec feat(minigames): touch controls and responsive board for Bomperator
- Extract pressDir/releaseDir/stopAll edge callbacks; keyboard, D-pad and
  swipes all feed the same held-stack path (prediction, keepalives and the
  pending ledger stay input-source agnostic)
- BomperatorTouchControls: 4-way pad + stop center + plant button on coarse
  pointers, per-button pointer capture for hold-and-plant multi-touch
- Board gestures: dominant-axis swipe sets direction, quick tap stops
- Canvas scales via CSS (w-full h-auto, fixed internal buffer), so prediction
  is viewport-independent; touch-action/overscroll guards on the board
- Harness: backgrounded-tab scenario (4s rAF freeze under prod trace replay)
  proves resume never teleports (teleports=0, maxJump 0.43)
- E2E smoke at 390x844 hasTouch: page loads without horizontal overflow
2026-10-19 10:11:30 -04:00

1022 lines
39 KiB
TypeScript

"use client";
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
import { Eye, Flag, Play, Radio, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { BomperatorView, Dir, PlayerView } from "@/lib/minigames/bomperator/types";
import { BOMB_FUSE_TICKS, FLAME_LIFETIME_TICKS, GRID_H, GRID_W, MAX_SEATS, MIN_TO_START, TICK_MS, TICKS_PER_SECOND } from "@/lib/minigames/bomperator/constants";
import {
PRED_DEADZONE,
PRED_ENVELOPE_BUDGET_MS,
} from "@/lib/minigames/bomperator/prediction";
import { sendBomperatorInput } from "@/app/(frontend)/minigames/bomperator/actions";
import { BomperatorHud, seatColor } from "./BomperatorHud";
import { BomperatorTouchControls } from "./BomperatorTouchControls";
import { useBomperatorSounds } from "./sounds";
import { BomperatorSoundToggle } from "./BomperatorSoundToggle";
const CELL = 34;
const CANVAS_W = GRID_W * CELL;
const CANVAS_H = GRID_H * CELL;
const KEY_DIR: Record<string, Dir> = {
ArrowUp: "up",
KeyW: "up",
ArrowDown: "down",
KeyS: "down",
ArrowLeft: "left",
KeyA: "left",
ArrowRight: "right",
KeyD: "right",
};
/** Direction unit vectors for client-side prediction. */
const POWERUP_COLORS: Record<string, string> = {
bomb: "#f87171",
range: "#fb923c",
speed: "#38bdf8",
kick: "#a3e635",
};
const POWERUP_GLYPH: Record<string, string> = { bomb: "●", range: "✸", speed: "»", kick: "⇥" };
interface RenderPos {
x: number;
y: number;
}
/* ----- client-side prediction: replicate the engine's grid-locked movement ----- */
const PRED_DIR_VEC: Record<Dir, readonly [number, number]> = {
up: [0, -1],
down: [0, 1],
left: [-1, 0],
right: [1, 0],
};
const PRED_EPS = 1e-6;
interface PredictBomb {
id: string;
x: number;
y: number;
/** Optimistic local charge the server has not confirmed yet. Blocks movement
* like a real one but cannot be kick-pushed (the server has not placed it). */
ghost?: boolean;
}
function predCellCentered(x: number, y: number): boolean {
return Math.abs(x - Math.round(x)) < PRED_EPS && Math.abs(y - Math.round(y)) < PRED_EPS;
}
function predApproach(current: number, target: number, step: number): number {
const delta = target - current;
if (Math.abs(delta) <= step) return target;
return current + Math.sign(delta) * step;
}
function predBombAt(bombs: readonly PredictBomb[], x: number, y: number): PredictBomb | undefined {
return bombs.find((b) => b.x === x && b.y === y);
}
function predOpen(grid: readonly number[], x: number, y: number): boolean {
return x >= 0 && y >= 0 && x < GRID_W && y < GRID_H && grid[y * GRID_W + x] === 0;
}
function predCanStand(grid: readonly number[], bombs: readonly PredictBomb[], x: number, y: number): boolean {
return predOpen(grid, x, y) && !predBombAt(bombs, x, y);
}
/**
* One small advance step mirroring the engine's advancePlayer exactly: finish
* aligning the perpendicular axis first, then move toward the adjacent cell
* center; a charge blocks unless kick-capable (then it slides one cell forward,
* recorded into the mutable bombs list).
*/
function predStep(
grid: readonly number[],
bombs: PredictBomb[],
x0: number,
y0: number,
dir: Dir,
kick: boolean,
step: number,
): RenderPos {
const [dx, dy] = PRED_DIR_VEC[dir];
let x = x0;
let y = y0;
if (dx !== 0) {
if (Math.abs(y - Math.round(y)) > PRED_EPS) {
const ty = Math.round(y);
y += Math.sign(ty - y) * Math.min(Math.abs(ty - y), step);
if (Math.abs(ty - y) < PRED_EPS) y = ty;
return { x, y };
}
const cy = Math.round(y);
const entering = dx > 0 ? Math.floor(x) + 1 : Math.ceil(x) - 1;
const home = dx > 0 ? Math.floor(x + PRED_EPS) : Math.ceil(x - PRED_EPS);
const bomb = predBombAt(bombs, entering, cy);
if (bomb) {
if (kick && !bomb.ghost) {
const bx = entering + dx;
if (predOpen(grid, bx, cy) && !predBombAt(bombs, bx, cy)) {
bomb.x = bx;
bomb.y = cy;
return { x: predApproach(x, entering, step), y };
}
}
return { x: home, y };
}
if (!predCanStand(grid, bombs, entering, cy)) return { x: home, y };
return { x: predApproach(x, entering, step), y };
}
if (Math.abs(x - Math.round(x)) > PRED_EPS) {
const tx = Math.round(x);
x += Math.sign(tx - x) * Math.min(Math.abs(tx - x), step);
if (Math.abs(tx - x) < PRED_EPS) x = tx;
return { x, y };
}
const cx = Math.round(x);
const entering = dy > 0 ? Math.floor(y) + 1 : Math.ceil(y) - 1;
const home = dy > 0 ? Math.floor(y + PRED_EPS) : Math.ceil(y - PRED_EPS);
const bomb = predBombAt(bombs, cx, entering);
if (bomb) {
if (kick && !bomb.ghost) {
const by = entering + dy;
if (predOpen(grid, cx, by) && !predBombAt(bombs, cx, by)) {
bomb.x = cx;
bomb.y = by;
return { x, y: predApproach(y, entering, step) };
}
}
return { x, y: home };
}
if (!predCanStand(grid, bombs, cx, entering)) return { x, y: home };
return { x, y: predApproach(y, entering, step) };
}
/**
* Advance over `durationMs` in small slices, honoring the engine's slip-to-rest:
* with no active direction the technician keeps traveling in `facing` until it
* lands exactly on a cell center; a blocked cell settles it back to the one it
* was leaving, where it then stays.
*/
function predAdvance(
grid: readonly number[],
bombs: PredictBomb[],
start: RenderPos,
dir: Dir | null,
facing: Dir,
speed: number,
kick: boolean,
durationMs: number,
): RenderPos {
let { x, y } = start;
let remaining = Math.min(durationMs, 1500);
let guard = 0;
while (remaining > 0.5 && guard < 120) {
guard += 1;
const slice = Math.min(remaining, 16);
const step = (speed * slice) / 1000;
const effDir = dir ?? (predCellCentered(x, y) ? null : facing);
if (!effDir) break;
const res = predStep(grid, bombs, x, y, effDir, kick, step);
const moved = Math.abs(res.x - x) > 1e-9 || Math.abs(res.y - y) > 1e-9;
x = res.x;
y = res.y;
if (!moved) break; // settled against a blocked cell
remaining -= slice;
}
return { x, y };
}
/* ------------------------------------------------------------- draw helpers */
function drawFloor(ctx: CanvasRenderingContext2D) {
ctx.fillStyle = "#0b1220";
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H);
ctx.strokeStyle = "rgba(148,163,184,0.06)";
ctx.lineWidth = 1;
for (let x = 0; x <= GRID_W; x += 1) {
ctx.beginPath();
ctx.moveTo(x * CELL + 0.5, 0);
ctx.lineTo(x * CELL + 0.5, CANVAS_H);
ctx.stroke();
}
for (let y = 0; y <= GRID_H; y += 1) {
ctx.beginPath();
ctx.moveTo(0, y * CELL + 0.5);
ctx.lineTo(CANVAS_W, y * CELL + 0.5);
ctx.stroke();
}
}
function drawSolid(ctx: CanvasRenderingContext2D, cx: number, cy: number) {
const px = cx * CELL;
const py = cy * CELL;
ctx.fillStyle = "#1e293b";
ctx.fillRect(px + 1, py + 1, CELL - 2, CELL - 2);
ctx.fillStyle = "#334155";
ctx.fillRect(px + 1, py + 1, CELL - 2, 5);
ctx.strokeStyle = "rgba(2,6,23,0.6)";
ctx.strokeRect(px + 1.5, py + 1.5, CELL - 3, CELL - 3);
}
function drawCrate(ctx: CanvasRenderingContext2D, cx: number, cy: number) {
const px = cx * CELL + 3;
const py = cy * CELL + 3;
const s = CELL - 6;
ctx.fillStyle = "#a1772f"; // sand supply stack
ctx.fillRect(px, py, s, s);
ctx.fillStyle = "#c79a4b";
ctx.fillRect(px, py, s, 4);
ctx.strokeStyle = "#5c421a";
ctx.lineWidth = 2;
ctx.strokeRect(px + 1, py + 1, s - 2, s - 2);
ctx.beginPath();
ctx.moveTo(px, py + s / 2);
ctx.lineTo(px + s, py + s / 2);
ctx.moveTo(px + s / 2, py);
ctx.lineTo(px + s / 2, py + s);
ctx.stroke();
}
function drawDrop(ctx: CanvasRenderingContext2D, x: number, y: number, kind: string, t: number) {
const cxp = (x + 0.5) * CELL;
const cyp = (y + 0.5) * CELL + Math.sin(t / 300 + x + y) * 2;
ctx.fillStyle = POWERUP_COLORS[kind] ?? "#e2e8f0";
ctx.globalAlpha = 0.9;
ctx.beginPath();
ctx.arc(cxp, cyp, CELL * 0.26, 0, Math.PI * 2);
ctx.fill();
ctx.globalAlpha = 1;
ctx.fillStyle = "#0b1220";
ctx.font = `bold ${Math.round(CELL * 0.34)}px ui-monospace, monospace`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(POWERUP_GLYPH[kind] ?? "?", cxp, cyp + 1);
}
function drawBomb(ctx: CanvasRenderingContext2D, x: number, y: number, fuseTicks: number, t: number) {
const cxp = (x + 0.5) * CELL;
const cyp = (y + 0.55) * CELL;
const r = CELL * 0.3;
ctx.fillStyle = "#0f172a";
ctx.beginPath();
ctx.arc(cxp, cyp, r, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = "#475569";
ctx.lineWidth = 1.5;
ctx.stroke();
// Blinking spark: faster over the last quarter of the fuse.
const blink = fuseTicks <= BOMB_FUSE_TICKS / 4 ? Math.floor(t / 90) % 2 === 0 : Math.floor(t / 260) % 2 === 0;
if (blink) {
ctx.fillStyle = "#fbbf24";
ctx.beginPath();
ctx.arc(cxp + r * 0.5, cyp - r * 0.7, 2.6, 0, Math.PI * 2);
ctx.fill();
}
}
function drawFlame(ctx: CanvasRenderingContext2D, x: number, y: number, ticksLeft: number, t: number) {
const px = x * CELL;
const py = y * CELL;
const flicker = 0.55 + 0.35 * Math.abs(Math.sin(t / 80 + x * 2 + y));
ctx.globalAlpha = Math.min(1, ticksLeft / FLAME_LIFETIME_TICKS + 0.2) * flicker;
const grad = ctx.createRadialGradient(px + CELL / 2, py + CELL / 2, 2, px + CELL / 2, py + CELL / 2, CELL * 0.7);
grad.addColorStop(0, "#fde68a");
grad.addColorStop(0.5, "#fb923c");
grad.addColorStop(1, "rgba(239,68,68,0)");
ctx.fillStyle = grad;
ctx.fillRect(px - 2, py - 2, CELL + 4, CELL + 4);
ctx.globalAlpha = 1;
}
function drawPlayer(ctx: CanvasRenderingContext2D, pos: RenderPos, player: PlayerView, isYou: boolean) {
const cxp = (pos.x + 0.5) * CELL;
const cyp = (pos.y + 0.5) * CELL;
const color = seatColor(player.seat);
const r = CELL * 0.32;
if (!player.alive) {
ctx.globalAlpha = 0.28;
ctx.strokeStyle = "#94a3b8";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(cxp - r, cyp - r);
ctx.lineTo(cxp + r, cyp + r);
ctx.moveTo(cxp + r, cyp - r);
ctx.lineTo(cxp - r, cyp + r);
ctx.stroke();
ctx.globalAlpha = 1;
return;
}
// EOD technician: body + helmet visor.
ctx.fillStyle = color;
ctx.beginPath();
ctx.roundRect(cxp - r, cyp - r * 0.7, r * 2, r * 1.7, 4);
ctx.fill();
ctx.fillStyle = "rgba(2,6,23,0.55)";
ctx.beginPath();
ctx.roundRect(cxp - r * 0.7, cyp - r * 0.5, r * 1.4, r * 0.6, 2);
ctx.fill();
if (isYou) {
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(cxp, cyp, r + 3, 0, Math.PI * 2);
ctx.stroke();
}
if (player.invulnerable) {
ctx.strokeStyle = "rgba(125,211,252,0.9)";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(cxp, cyp, r + 5, 0, Math.PI * 2);
ctx.stroke();
}
if (!player.connected) {
ctx.fillStyle = "#fbbf24";
ctx.font = `bold ${Math.round(CELL * 0.4)}px ui-monospace, monospace`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("?", cxp, cyp - r - 6);
}
}
/* --------------------------------------------------------------- component */
export function BomperatorGame({
match,
currentUserId,
onLeave,
onEnd,
onStart,
operatorsOnline,
}: {
match: BomperatorView;
currentUserId: number | string;
onLeave: () => void;
onEnd: () => void;
onStart: () => void;
operatorsOnline: string[];
}) {
const sounds = useBomperatorSounds(match);
const { playPlace } = sounds;
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const matchRef = useRef<BomperatorView>(match);
const renderPosRef = useRef<Map<number, RenderPos>>(new Map());
const heldKeysRef = useRef<Dir[]>([]);
const [starting, setStarting] = useState(false);
/* ---- client-side prediction state (own seat only) ---- */
const predRef = useRef<RenderPos | null>(null);
const facingRef = useRef<Dir>("down");
const inputSeqRef = useRef(0);
const pendingRef = useRef<Array<{ seq: number; dir: Dir | null; sentAt: number }>>([]);
const pushOverlayRef = useRef<Map<string, { x: number; y: number; at: number }>>(new Map());
const ghostBombsRef = useRef<Array<{ x: number; y: number; placedAt: number }>>([]);
const knownBombIdsRef = useRef<Set<string>>(new Set());
const lastAckRef = useRef(0);
const lastAckedDirRef = useRef<Dir | null>(null);
const lastVersionSeenRef = useRef(-1);
const rttAvgRef = useRef(100);
useEffect(() => {
matchRef.current = match;
}, [match]);
const isHost = match.yourSeat === 0;
const me = match.yourSeat !== null ? match.players[match.yourSeat] : null;
const canControl = match.phase === "battle" && me !== null && me.alive && match.yourSeat !== null;
// The canvas only exists on the live-board branch; the render loop must (re)start
// when it mounts, so this boundary flag drives the effect's dependencies.
const hasBoard =
match.phase === "countdown" || match.phase === "battle" || match.phase === "roundEnd";
/* ---- input: hold-to-move with a keepalive, edge-triggered drop ---- */
const sendDrop = useCallback(async () => {
playPlace();
// Optimistic placement: the ghost charge appears at our cell the same instant
// space goes down. The server places the real one about one round trip later
// at its own (slightly trailing) position; the snapshot that shows our fresh
// bomb retires the ghost. Every server rejection rule is mirrored here
// against our freshest state, so a ghost almost never expires unfulfilled.
const view = matchRef.current;
const seat = view.yourSeat;
const me = seat !== null ? (view.players[seat] ?? null) : null;
if (view.phase === "battle" && me && me.alive) {
const at = predRef.current ?? { x: me.x, y: me.y };
const cx = Math.round(at.x);
const cy = Math.round(at.y);
const ghosts = ghostBombsRef.current;
const overlay = pushOverlayRef.current;
const cellTaken =
cx < 0 ||
cy < 0 ||
cx >= GRID_W ||
cy >= GRID_H ||
view.grid[cy * GRID_W + cx] !== 0 ||
view.bombs.some((b) => {
const to = overlay.get(b.id);
return (b.x === cx && b.y === cy) || (to !== undefined && to.x === cx && to.y === cy);
}) ||
ghosts.some((g) => g.x === cx && g.y === cy);
if (!cellTaken && me.bombsActive + ghosts.length < me.bombsMax && ghosts.length < 4) {
ghosts.push({ x: cx, y: cy, placedAt: performance.now() });
}
}
try {
await sendBomperatorInput(match.matchId, { drop: true });
} catch {
// Ignore transient failures.
}
}, [match.matchId, playPlace]);
/**
* Fire a direction change immediately with a monotonic seq. The server drops
* anything at or below the last applied seq, so there is no reason to queue
* behind an in-flight POST: the newest intent always wins on the wire, and a
* direction change costs one round trip instead of up to two. Human key edges
* are inherently rate-limited, so this cannot flood the way the old unbounded
* intervals did. Each send also feeds a rolling RTT estimate for prediction.
*/
const sendDir = useCallback(
(dir: Dir | null) => {
const seq = (inputSeqRef.current += 1);
const pending = pendingRef.current;
pending.push({ seq, dir, sentAt: performance.now() });
if (pending.length > 64) pending.splice(0, pending.length - 64);
const t0 = performance.now();
void sendBomperatorInput(match.matchId, { dir, seq })
.catch(() => undefined)
.finally(() => {
rttAvgRef.current = rttAvgRef.current * 0.8 + (performance.now() - t0) * 0.2;
});
},
[match.matchId],
);
/**
* Shared edge-send plumbing for EVERY input source (keyboard, D-pad, swipe).
* The held-stack owns priority (newest first); each edge sends the current
* top so the server always holds our latest intent. Touch handlers in
* BomperatorTouchControls call exactly these, keeping prediction, keepalives
* and the pending ledger source-agnostic.
*/
const pressDir = useCallback(
(dir: Dir) => {
heldKeysRef.current = [dir, ...heldKeysRef.current.filter((d) => d !== dir)];
sendDir(heldKeysRef.current[0] ?? null);
},
[sendDir],
);
const releaseDir = useCallback(
(dir: Dir) => {
heldKeysRef.current = heldKeysRef.current.filter((d) => d !== dir);
sendDir(heldKeysRef.current[0] ?? null);
},
[sendDir],
);
const stopAll = useCallback(() => {
if (heldKeysRef.current.length === 0) return;
heldKeysRef.current = [];
sendDir(null);
}, [sendDir]);
useEffect(() => {
if (!canControl) return;
// Level-triggered movement: the server keeps applying the last direction we
// sent until we send a different one, so we transmit on change (edge), plus
// a slow re-assert while a key is held to recover a lost packet.
const onKeyDown = (e: KeyboardEvent) => {
if (e.repeat) return;
if (e.code === "Space") {
e.preventDefault();
void sendDrop();
return;
}
const dir = KEY_DIR[e.code];
if (!dir) return;
e.preventDefault();
pressDir(dir);
};
const onKeyUp = (e: KeyboardEvent) => {
const dir = KEY_DIR[e.code];
if (!dir) return;
releaseDir(dir);
};
window.addEventListener("keydown", onKeyDown, { capture: true });
window.addEventListener("keyup", onKeyUp, { capture: true });
// Slow re-assert, only while actually holding a direction. An idle tab sends
// nothing, so it adds zero load.
const keepalive = window.setInterval(() => {
const held = heldKeysRef.current[0] ?? null;
if (held !== null) sendDir(held);
}, 400);
return () => {
window.removeEventListener("keydown", onKeyDown, { capture: true });
window.removeEventListener("keyup", onKeyUp, { capture: true });
window.clearInterval(keepalive);
heldKeysRef.current = [];
};
}, [canControl, match.matchId, pressDir, releaseDir, sendDir, sendDrop]);
/* ---- board swipes (touch): swipe sets direction, tap stops ---- */
const swipeRef = useRef<{ x: number; y: number; t: number; fired: boolean } | null>(null);
const onBoardPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
if (e.pointerType === "mouse" || !canControl) return;
swipeRef.current = { x: e.clientX, y: e.clientY, t: performance.now(), fired: false };
};
const onBoardPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
const s = swipeRef.current;
if (!s || s.fired) return;
const dx = e.clientX - s.x;
const dy = e.clientY - s.y;
if (Math.hypot(dx, dy) < 24) return;
s.fired = true;
// Dominant axis, cardinal only: movement is grid-locked, so one swipe
// commits one leg. The held stack keeps priority, so a swipe simply sits
// on top of whatever the D-pad holds and releases back to it.
pressDir(
Math.abs(dx) >= Math.abs(dy) ? (dx > 0 ? "right" : "left") : dy > 0 ? "down" : "up",
);
};
const onBoardPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {
const s = swipeRef.current;
swipeRef.current = null;
if (!s || s.fired || e.pointerType === "mouse") return;
// A quick tap that never crossed the swipe threshold means "stop".
if (performance.now() - s.t < 300) stopAll();
};
/* ---- render loop: predict our own seat, ease the rest toward snapshots ---- */
useEffect(() => {
if (!hasBoard) return;
const canvas = canvasRef.current;
if (!canvas) return;
const dpr = window.devicePixelRatio || 1;
canvas.width = CANVAS_W * dpr;
canvas.height = CANVAS_H * dpr;
// CSS owns the display size (responsive wrapper + h-auto keeps the
// intrinsic aspect ratio); the internal buffer stays CANVAS_* * dpr so
// rendering and prediction never depend on the viewport.
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.scale(dpr, dpr);
let raf = 0;
let last = performance.now();
const step = (now: number) => {
raf = requestAnimationFrame(step);
const rawDt = now - last;
last = now;
const dt = Math.min(rawDt / 16.6667, 3);
const dtMs = Math.min(rawDt, 100);
const view = matchRef.current;
const pos = renderPosRef.current;
const ease = Math.min(1, 0.4 * dt);
const mySeat = view.yourSeat;
const me = mySeat !== null ? (view.players[mySeat] ?? null) : null;
const overlay = pushOverlayRef.current;
// Working bomb set for prediction + drawing: server truth plus optimistic
// kick-pushes we have made that the server has not confirmed yet.
const bombsWorking: PredictBomb[] = view.bombs.map((b) => {
const to = overlay.get(b.id);
return { id: b.id, x: to?.x ?? b.x, y: to?.y ?? b.y };
});
for (const g of ghostBombsRef.current) {
bombsWorking.push({ id: `ghost:${g.placedAt}`, x: g.x, y: g.y, ghost: true });
}
/* -- local prediction: our own technician answers the keyboard immediately -- */
if (view.phase === "battle" && me && me.alive) {
if (predRef.current === null) predRef.current = { x: me.x, y: me.y };
const held = heldKeysRef.current[0] ?? null;
if (held) facingRef.current = held;
predRef.current = predAdvance(
view.grid,
bombsWorking,
predRef.current,
held,
facingRef.current,
me.speed,
me.kick,
dtMs,
);
// Record any optimistic push so collision and drawing agree next frame.
for (const b of bombsWorking) {
const orig = view.bombs.find((vb) => vb.id === b.id);
if (orig && (orig.x !== b.x || orig.y !== b.y)) overlay.set(b.id, { x: b.x, y: b.y, at: now });
}
} else {
// Not controlling (between rounds, dead, or spectating): no prediction,
// and no stale inputs may replay into the next round's spawn position.
predRef.current = null;
pendingRef.current = [];
overlay.clear();
ghostBombsRef.current = [];
}
/* -- reconcile against the server once per fresh snapshot -- */
if (view.version !== lastVersionSeenRef.current) {
lastVersionSeenRef.current = view.version;
if (me) {
const ack = me.lastInputSeq ?? 0;
if (ack < lastAckRef.current) {
// Ack moved backwards: the server rebuilt state (round reset). Snap.
pendingRef.current = [];
overlay.clear();
predRef.current = me.alive ? { x: me.x, y: me.y } : null;
facingRef.current = me.dir;
lastAckedDirRef.current = null;
} else {
// Drop acknowledged inputs; the newest one is the dir the server is
// now applying. Note a release (null) counts as a real direction.
let ackedDir = lastAckedDirRef.current;
const pending = pendingRef.current;
while (pending.length > 0) {
const head = pending[0];
if (!head || head.seq > ack) break;
ackedDir = head.dir;
pending.shift();
}
lastAckedDirRef.current = ackedDir;
// Prune optimistic pushes the server has caught up to, plus any a
// rejected push left stranded (server never agreed within 1.5s).
for (const [id, to] of overlay) {
const b = view.bombs.find((vb) => vb.id === id);
if (!b || (b.x === to.x && b.y === to.y) || now - to.at > 1500) overlay.delete(id);
}
if (me.alive && predRef.current) {
const pred = predRef.current;
// Estimate where the server really is NOW: start from its snapshot
// position and replay every input it has not yet acknowledged,
// timed by our send times plus the measured one-way latency.
const rtt = rttAvgRef.current;
const replayBombs: PredictBomb[] = view.bombs.map((b) => {
const to = overlay.get(b.id);
return { id: b.id, x: to?.x ?? b.x, y: to?.y ?? b.y };
});
let t = now - rtt / 2 - TICK_MS / 2;
let est = { x: me.x, y: me.y };
let dir = ackedDir;
let facing = me.dir;
for (const p of pending) {
const recv = p.sentAt + rtt / 2;
est = predAdvance(
view.grid, replayBombs, est, dir, facing, me.speed, me.kick,
Math.max(0, Math.min(recv - t, 1000)),
);
t = recv;
dir = p.dir;
if (p.dir) facing = p.dir;
}
est = predAdvance(
view.grid, replayBombs, est, dir, facing, me.speed, me.kick,
Math.max(0, Math.min(now - t, 1000)),
);
const gap = Math.hypot(est.x - pred.x, est.y - pred.y);
// Lead-aware correction envelope. The old policy corrected only
// once EVERY input was acked, so when the server's tick loop
// stalls (Node event-loop blocks drop setInterval callbacks and
// the sim permanently loses that wall-clock time) the gap grew
// unattended past the snap threshold and discharged as the
// reported "teleported back to where the server saw me". Now:
// gaps inside the envelope ride untouched, anything beyond is
// trimmed a little on EVERY snapshot, and even large gaps close
// at a capped rate (2.5x run speed) instead of teleporting.
// Verified against the recorded production latency trace plus
// server-stall replay in tests/int/bomperator-prediction.int.
// spec.ts: zero corrections over 1.5 cells (old policy: instant
// 2.6-cell jumps). Round resets still snap via the ack-backwards
// branch.
const envelope = Math.max(
PRED_DEADZONE,
(me.speed * (rtt / 2 + TICK_MS / 2 + PRED_ENVELOPE_BUDGET_MS)) / 1000,
);
if (gap > 2.5) {
const maxStep = (me.speed * 2.5 * dtMs) / 1000;
const easeT = Math.min(1, maxStep / gap);
pred.x += (est.x - pred.x) * easeT;
pred.y += (est.y - pred.y) * easeT;
facingRef.current = facing;
} else if (gap > envelope) {
const k = Math.min(gap - envelope, gap * 0.5) / gap;
pred.x += (est.x - pred.x) * k;
pred.y += (est.y - pred.y) * k;
}
}
}
lastAckRef.current = ack;
// Reconcile optimistic ghost charges. The server placed our drop when
// a bomb we have not seen before shows up owned by our seat (it may
// sit a cell away from the ghost: the server trails our displayed
// position), or when anything occupies the ghost's cell. A ghost
// still unmatched past the round-trip budget expired because the
// server rejected the placement; retire it silently.
const ghosts = ghostBombsRef.current;
if (ghosts.length > 0) {
let freshOwn = 0;
for (const b of view.bombs) {
if (b.ownerSeat === me.seat && !knownBombIdsRef.current.has(b.id)) freshOwn += 1;
}
for (let i = ghosts.length - 1; i >= 0; i -= 1) {
const g = ghosts[i];
const cellTaken = view.bombs.some((b) => b.x === g.x && b.y === g.y);
if (cellTaken) {
ghosts.splice(i, 1);
} else if (freshOwn > 0) {
freshOwn -= 1;
ghosts.splice(i, 1);
} else if (now - g.placedAt > 1200) {
ghosts.splice(i, 1);
}
}
}
knownBombIdsRef.current = new Set(view.bombs.map((b) => b.id));
}
}
// Ease every OTHER technician toward its authoritative server position.
// Monotonic (never overshoots a collision-valid target); a large gap snaps
// instead of sliding across the map (round resets / teleports).
for (const player of view.players) {
if (predRef.current && mySeat !== null && player.seat === mySeat) continue;
const target = { x: player.x, y: player.y };
const current = pos.get(player.seat);
if (!current) {
pos.set(player.seat, target);
continue;
}
if (Math.hypot(target.x - current.x, target.y - current.y) > 1.5) {
current.x = target.x;
current.y = target.y;
} else {
current.x += (target.x - current.x) * ease;
current.y += (target.y - current.y) * ease;
}
}
ctx.clearRect(0, 0, CANVAS_W, CANVAS_H);
drawFloor(ctx);
for (let y = 0; y < GRID_H; y += 1) {
for (let x = 0; x < GRID_W; x += 1) {
const code = view.grid[y * GRID_W + x];
if (code === 1) drawSolid(ctx, x, y);
else if (code === 2) drawCrate(ctx, x, y);
}
}
for (const drop of view.drops) drawDrop(ctx, drop.x, drop.y, drop.kind, now);
for (const bomb of view.bombs) {
const w = bombsWorking.find((wb) => wb.id === bomb.id);
drawBomb(ctx, w?.x ?? bomb.x, w?.y ?? bomb.y, bomb.fuseTicks, now);
}
// Ghost charges: optimistic placements awaiting server confirmation. The
// fuse burns on the local clock so the blink cadence matches real ones.
for (const g of ghostBombsRef.current) {
const fuse = Math.max(0, BOMB_FUSE_TICKS - (now - g.placedAt) / TICK_MS);
drawBomb(ctx, g.x, g.y, fuse, now);
}
for (const flame of view.flames) drawFlame(ctx, flame.x, flame.y, flame.ticksLeft, now);
for (const player of view.players) {
const isMe = mySeat !== null && player.seat === mySeat;
const rp =
isMe && predRef.current
? predRef.current
: (pos.get(player.seat) ?? { x: player.x, y: player.y });
drawPlayer(ctx, rp, player, String(player.userId) === String(currentUserId));
}
};
raf = requestAnimationFrame(step);
return () => cancelAnimationFrame(raf);
}, [currentUserId, hasBoard]);
/* ---- waiting room (lobby phase) ---- */
if (match.phase === "lobby") {
return (
<Card>
<CardHeader className="border-b p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<CardTitle className="flex items-center gap-2 text-sm">
<Users className="size-4 text-muted-foreground" />
{match.name ?? "Ordnance Disposal"} · waiting room
</CardTitle>
<p className="text-sm text-muted-foreground">
{match.players.length}/{MAX_SEATS} technicians · first to {match.roundTarget} rounds wins.
Share the link to invite more.
</p>
</div>
<div className="flex items-center gap-2">
<BomperatorSoundToggle
muted={sounds.muted}
musicVolume={sounds.musicVolume}
effectsVolume={sounds.effectsVolume}
onToggleMuted={sounds.toggleMuted}
onMusicVolumeChange={sounds.setMusicVolume}
onEffectsVolumeChange={sounds.setEffectsVolume}
/>
{isHost && (
<Button variant="ghost" size="sm" onClick={onEnd} title="End the drill for everyone">
<Flag /> End
</Button>
)}
<Button variant="outline" size="sm" onClick={onLeave}>
Leave
</Button>
{isHost && (
<Button
size="sm"
disabled={starting || match.players.length < MIN_TO_START}
onClick={async () => {
setStarting(true);
await onStart();
setStarting(false);
}}
>
<Play /> Start drill
</Button>
)}
</div>
</div>
</CardHeader>
<CardContent className="p-4">
<ul className="grid grid-cols-2 gap-2 sm:grid-cols-4">
{match.players.map((player) => (
<li
key={player.seat}
className="flex items-center gap-2 rounded-lg border border-border bg-background/40 px-3 py-2 text-sm"
>
<span
className="size-3 shrink-0 rounded-full"
style={{ backgroundColor: seatColor(player.seat) }}
/>
<span className="truncate">
{String(player.userId) === String(currentUserId) ? "You" : player.name}
</span>
</li>
))}
</ul>
{isHost && match.players.length < MIN_TO_START && (
<p className="mt-3 text-xs text-muted-foreground">Waiting for at least one more technician…</p>
)}
</CardContent>
</Card>
);
}
/* ---- results (complete phase) ---- */
if (match.phase === "complete") {
const winner = match.matchWinnerSeat !== null ? match.players[match.matchWinnerSeat] : null;
const youWon = winner !== null && String(winner.userId) === String(currentUserId);
return (
<Card className={youWon ? "border-emerald-500/40" : "border-border"}>
<CardHeader className="border-b p-4">
<CardTitle className="text-sm">
{winner ? `${winner.name} clears the depot` : "No decisive winner"}
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 p-4">
<ul className="grid grid-cols-1 gap-2 sm:grid-cols-2">
{[...match.players]
.sort((a, b) => b.roundsWon - a.roundsWon || b.kills - a.kills)
.map((player) => (
<li
key={player.seat}
className="flex items-center justify-between rounded-lg border border-border bg-background/40 px-3 py-2 text-sm"
>
<span className="flex items-center gap-2">
<span
className="size-3 shrink-0 rounded-full"
style={{ backgroundColor: seatColor(player.seat) }}
/>
{String(player.userId) === String(currentUserId) ? "You" : player.name}
</span>
<span className="font-mono text-xs tabular-nums text-muted-foreground">
{player.roundsWon} rounds · {player.kills} down
</span>
</li>
))}
</ul>
<p className="text-xs text-muted-foreground">Rewards are granted when the drill ends.</p>
<div>
<Button onClick={onLeave}>Return to lobby</Button>
</div>
</CardContent>
</Card>
);
}
/* ---- live board (countdown / battle / roundEnd) ---- */
const countdownSeconds = Math.ceil(match.countdownTicks / TICKS_PER_SECOND);
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="flex items-center gap-2 text-sm font-semibold">
{match.name ?? "Ordnance Disposal"}
{match.yourSeat === null && (
<span className="flex items-center gap-1 rounded-sm bg-sky-600/20 px-2 py-0.5 text-xs font-medium text-sky-300">
<Eye className="size-3" /> Spectating
</span>
)}
</h2>
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<BomperatorSoundToggle
muted={sounds.muted}
musicVolume={sounds.musicVolume}
effectsVolume={sounds.effectsVolume}
onToggleMuted={sounds.toggleMuted}
onMusicVolumeChange={sounds.setMusicVolume}
onEffectsVolumeChange={sounds.setEffectsVolume}
/>
<span className="flex items-center gap-1">
<Radio className="size-3.5" /> {operatorsOnline.length} on the net
</span>
{isHost && (
<Button variant="ghost" size="sm" onClick={onEnd} title="End the drill for everyone">
<Flag /> End
</Button>
)}
<Button variant="outline" size="sm" onClick={onLeave}>
Leave
</Button>
</div>
</div>
<BomperatorHud match={match} currentUserId={currentUserId} />
<div
className="relative mx-auto w-full max-w-[520px] touch-none select-none overscroll-contain"
onPointerDown={onBoardPointerDown}
onPointerMove={onBoardPointerMove}
onPointerUp={onBoardPointerUp}
onPointerCancel={onBoardPointerUp}
>
<canvas
ref={canvasRef}
className="block h-auto w-full rounded-xl border border-border shadow-lg"
aria-label="Ordnance Disposal arena"
/>
{match.phase === "countdown" && (
<Overlay>
<span className="text-sm uppercase tracking-widest text-white/70">Round {match.roundIndex + 1}</span>
<span className="text-6xl font-black text-white drop-shadow-lg">{countdownSeconds}</span>
<span className="text-xs text-white/70">Get ready…</span>
</Overlay>
)}
{match.phase === "roundEnd" && (
<Overlay>
<span className="text-3xl font-black uppercase tracking-widest text-amber-300 drop-shadow-lg">
{match.roundWinnerSeat !== null
? `${match.players[match.roundWinnerSeat]?.name ?? "?"} takes the round`
: "Round drawn"}
</span>
</Overlay>
)}
{canControl === false && match.phase === "battle" && me && !me.alive && (
<div className="pointer-events-none absolute inset-x-0 bottom-2 flex justify-center">
<span className="rounded-sm bg-black/60 px-3 py-1 text-xs text-white/80">
You were eliminated. Watch the fallout
</span>
</div>
)}
</div>
{canControl && (
<BomperatorTouchControls
onPress={pressDir}
onRelease={releaseDir}
onStop={stopAll}
onDrop={() => void sendDrop()}
/>
)}
<p className="text-center text-[11px] text-muted-foreground">
<span className="[@media(pointer:coarse)]:hidden">Move: WASD / arrows · Plant charge: Space</span>
<span className="hidden [@media(pointer:coarse)]:inline">
Swipe or hold the pad to move · tap board or stop key to halt · bomb button plants a charge
</span>
</p>
</div>
);
}
function Overlay({ children }: { children: React.ReactNode }) {
return (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-xl bg-black/45 text-center">
{children}
</div>
);
}