1
0
Fork 0

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
This commit is contained in:
Jason Fraley 2026-10-19 10:11:30 -04:00
parent a72f1bbe03
commit ce682becec
5 changed files with 250 additions and 11 deletions

View file

@ -1,6 +1,6 @@
"use client"; "use client";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
import { Eye, Flag, Play, Radio, Users } from "lucide-react"; import { Eye, Flag, Play, Radio, Users } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@ -12,6 +12,7 @@ import {
} from "@/lib/minigames/bomperator/prediction"; } from "@/lib/minigames/bomperator/prediction";
import { sendBomperatorInput } from "@/app/(frontend)/minigames/bomperator/actions"; import { sendBomperatorInput } from "@/app/(frontend)/minigames/bomperator/actions";
import { BomperatorHud, seatColor } from "./BomperatorHud"; import { BomperatorHud, seatColor } from "./BomperatorHud";
import { BomperatorTouchControls } from "./BomperatorTouchControls";
import { useBomperatorSounds } from "./sounds"; import { useBomperatorSounds } from "./sounds";
import { BomperatorSoundToggle } from "./BomperatorSoundToggle"; import { BomperatorSoundToggle } from "./BomperatorSoundToggle";
@ -455,6 +456,33 @@ export function BomperatorGame({
[match.matchId], [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(() => { useEffect(() => {
if (!canControl) return; if (!canControl) return;
@ -471,14 +499,12 @@ export function BomperatorGame({
const dir = KEY_DIR[e.code]; const dir = KEY_DIR[e.code];
if (!dir) return; if (!dir) return;
e.preventDefault(); e.preventDefault();
heldKeysRef.current = [dir, ...heldKeysRef.current.filter((d) => d !== dir)]; pressDir(dir);
sendDir(heldKeysRef.current[0] ?? null);
}; };
const onKeyUp = (e: KeyboardEvent) => { const onKeyUp = (e: KeyboardEvent) => {
const dir = KEY_DIR[e.code]; const dir = KEY_DIR[e.code];
if (!dir) return; if (!dir) return;
heldKeysRef.current = heldKeysRef.current.filter((d) => d !== dir); releaseDir(dir);
sendDir(heldKeysRef.current[0] ?? null);
}; };
window.addEventListener("keydown", onKeyDown, { capture: true }); window.addEventListener("keydown", onKeyDown, { capture: true });
window.addEventListener("keyup", onKeyUp, { capture: true }); window.addEventListener("keyup", onKeyUp, { capture: true });
@ -496,7 +522,36 @@ export function BomperatorGame({
window.clearInterval(keepalive); window.clearInterval(keepalive);
heldKeysRef.current = []; heldKeysRef.current = [];
}; };
}, [canControl, match.matchId, sendDrop, sendDir]); }, [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 ---- */ /* ---- render loop: predict our own seat, ease the rest toward snapshots ---- */
@ -507,8 +562,9 @@ export function BomperatorGame({
const dpr = window.devicePixelRatio || 1; const dpr = window.devicePixelRatio || 1;
canvas.width = CANVAS_W * dpr; canvas.width = CANVAS_W * dpr;
canvas.height = CANVAS_H * dpr; canvas.height = CANVAS_H * dpr;
canvas.style.width = `${CANVAS_W}px`; // CSS owns the display size (responsive wrapper + h-auto keeps the
canvas.style.height = `${CANVAS_H}px`; // intrinsic aspect ratio); the internal buffer stays CANVAS_* * dpr so
// rendering and prediction never depend on the viewport.
const ctx = canvas.getContext("2d"); const ctx = canvas.getContext("2d");
if (!ctx) return; if (!ctx) return;
ctx.scale(dpr, dpr); ctx.scale(dpr, dpr);
@ -901,10 +957,16 @@ export function BomperatorGame({
<BomperatorHud match={match} currentUserId={currentUserId} /> <BomperatorHud match={match} currentUserId={currentUserId} />
<div className="relative mx-auto w-full max-w-[520px]"> <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 <canvas
ref={canvasRef} ref={canvasRef}
className="block w-full rounded-xl border border-border shadow-lg" className="block h-auto w-full rounded-xl border border-border shadow-lg"
aria-label="Ordnance Disposal arena" aria-label="Ordnance Disposal arena"
/> />
{match.phase === "countdown" && ( {match.phase === "countdown" && (
@ -932,8 +994,20 @@ export function BomperatorGame({
)} )}
</div> </div>
{canControl && (
<BomperatorTouchControls
onPress={pressDir}
onRelease={releaseDir}
onStop={stopAll}
onDrop={() => void sendDrop()}
/>
)}
<p className="text-center text-[11px] text-muted-foreground"> <p className="text-center text-[11px] text-muted-foreground">
Move: WASD / arrows · Plant charge: Space <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> </p>
</div> </div>
); );

View file

@ -0,0 +1,106 @@
"use client";
import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
import { Button } from "@/components/ui/button";
import type { Dir } from "@/lib/minigames/bomperator/types";
import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Bomb, Square } from "lucide-react";
interface BomperatorTouchControlsProps {
onPress: (dir: Dir) => void;
onRelease: (dir: Dir) => void;
onStop: () => void;
onDrop: () => void;
}
/**
* Touch controls for Ordnance Disposal: a 4-way D-pad with a stop key under
* the left thumb, a large plant button under the right. Rendered only on
* coarse pointers (phones/tablets); keyboard users never see it.
*
* The buttons feed the SAME press/release edge path as the keyboard handlers
* (pressDir/releaseDir in BomperatorGame), so prediction, keepalives and the
* pending ledger stay input-source agnostic. Hold semantics mirror keys:
* pressing a direction moves, releasing stops at the next cell center. Each
* button captures its own pointer so holding a direction while tapping plant
* works; cancel/lost-capture release paths keep the held stack honest when an
* OS gesture steals the touch mid-hold.
*/
export function BomperatorTouchControls({
onPress,
onRelease,
onStop,
onDrop,
}: BomperatorTouchControlsProps) {
const hold = (dir: Dir) => (e: ReactPointerEvent<HTMLButtonElement>) => {
e.preventDefault();
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
// Pointer already gone; the press still counts.
}
onPress(dir);
};
const lift = (dir: Dir) => () => {
onRelease(dir);
};
const pad = (dir: Dir, label: string, icon: ReactNode) => (
<Button
key={dir}
variant="secondary"
className="size-14 rounded-lg p-0"
aria-label={label}
onPointerDown={hold(dir)}
onPointerUp={lift(dir)}
onPointerCancel={lift(dir)}
onLostPointerCapture={lift(dir)}
>
{icon}
</Button>
);
return (
<div
className="mx-auto hidden w-full max-w-[520px] touch-none select-none items-center justify-between px-4 pb-1 pt-3 [@media(pointer:coarse)]:flex"
aria-label="Touch controls"
>
<div className="grid grid-cols-3 grid-rows-3 gap-1">
<span />
{pad("up", "Move up", <ArrowUp className="size-6" />)}
<span />
{pad("left", "Move left", <ArrowLeft className="size-6" />)}
<Button
variant="outline"
className="size-14 rounded-lg p-0"
aria-label="Stop"
onPointerDown={(e) => {
e.preventDefault();
onStop();
}}
>
<Square className="size-4" />
</Button>
{pad("right", "Move right", <ArrowRight className="size-6" />)}
<span />
{pad("down", "Move down", <ArrowDown className="size-6" />)}
<span />
</div>
<Button
variant="default"
className="size-20 rounded-full p-0"
aria-label="Plant charge"
onPointerDown={(e) => {
e.preventDefault();
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
// Pointer already gone; the press still counts.
}
onDrop();
}}
>
<Bomb className="size-8" />
</Button>
</div>
);
}

View file

@ -12,6 +12,7 @@ Five XP-earning minigames under one parent: routes live at `/minigames/*` (moved
- **Call for Fire: Versus (multiplayer)**: `/minigames/call-for-fire-versus`, category `multiplayer` (out of periods). Pure engine in `src/lib/minigames/call-for-fire-versus/` (`engine.ts`, `views.ts`, `types.ts`, `constants.ts`; client-safe) plus a server-only in-memory match registry in `registry.ts` (mirrors `blackjack/tables.ts`: `globalThis`-anchored Map, lobby, per-turn timeout, expiry sweep, SINGLE-INSTANCE ONLY). Each player hides a FOB fleet, then alternates fire corrections (first shot is a grid designation, later shots adjust from the last impact). `views.ts` builds per-viewer snapshots that never serialize the opponent's fleet. Client polls `fetchVersusMatch` (the in-memory SSE bus is unreliable across dev module copies, same as blackjack). Rewards on completion via `stats.ts` (`minigame:call-for-fire-versus`, profile group `callForFireVersus`). - **Call for Fire: Versus (multiplayer)**: `/minigames/call-for-fire-versus`, category `multiplayer` (out of periods). Pure engine in `src/lib/minigames/call-for-fire-versus/` (`engine.ts`, `views.ts`, `types.ts`, `constants.ts`; client-safe) plus a server-only in-memory match registry in `registry.ts` (mirrors `blackjack/tables.ts`: `globalThis`-anchored Map, lobby, per-turn timeout, expiry sweep, SINGLE-INSTANCE ONLY). Each player hides a FOB fleet, then alternates fire corrections (first shot is a grid designation, later shots adjust from the last impact). `views.ts` builds per-viewer snapshots that never serialize the opponent's fleet. Client polls `fetchVersusMatch` (the in-memory SSE bus is unreliable across dev module copies, same as blackjack). Rewards on completion via `stats.ts` (`minigame:call-for-fire-versus`, profile group `callForFireVersus`).
- **Ordnance Disposal (multiplayer, real-time)**: `/minigames/bomperator` (internal key `bomperator`, label "Ordnance Disposal"), category `multiplayer` (out of periods), a 2-8 player free-for-all Bomberman-style charge-clearing drill. Same pure-engine + in-memory-registry split as CFF versus, but upgraded from turn-based to a **fixed ~20 Hz tick loop** (was ~10 Hz until v0.12.3; every tick-denominated constant doubles with the rate so real-world durations stay identical): `src/lib/minigames/bomperator/{constants,types,engine,views}.ts` are pure/client-safe (seeded RNG via `state.rngState`/`gridSeed`; `generateGrid`, `createMatchState`, `startRound`, `applyInput`, `tick`), and `registry.ts` runs one `setInterval(TICK_MS)` per live match (started on `startMatch`, cleared on complete/dissolve; `globalThis.__bomperatorMatches`; SINGLE-INSTANCE ONLY: a restart/redeploy kills live matches). Grid is 15x13 (border + even/even pillars + seeded crates with one hidden power-up each; four classic pickups bomb/range/speed/kick). Movement is grid-locked with sub-cell interpolation; charges fuse ~2.5s, cross-flames stop at walls, destroy crates, chain-detonate, and kick-push; round ends at <=1 alive; sudden death spawns random-cell explosions after the 150s timer, with a draw guard. FFA has no hidden info so `buildBomperatorView` serves every viewer the same board (`yourSeat: null` = spectator). Clients POST inputs (`sendBomperatorInput`, rate-limited 40/s) and poll `fetchBomperatorMatch` (~500ms fallback behind the SSE stream); a rolling event buffer (monotonic ids) drives client SFX without diffing. Disconnects hold the seat for `RECONNECT_WINDOW_MS` then eliminate; below two active seats the match dissolves. Rewards on completion via `stats.ts` (`minigame:bomperator`, profile group `bomperator`: matchesPlayed/matchWins/roundsWon/kills/xpEarned; XP win/loss base + per-kill bounty, chips auto-derived). Registry row ships `status: "upcoming"` (page renders `MinigameComingSoon` until an admin flips it active). - **Ordnance Disposal (multiplayer, real-time)**: `/minigames/bomperator` (internal key `bomperator`, label "Ordnance Disposal"), category `multiplayer` (out of periods), a 2-8 player free-for-all Bomberman-style charge-clearing drill. Same pure-engine + in-memory-registry split as CFF versus, but upgraded from turn-based to a **fixed ~20 Hz tick loop** (was ~10 Hz until v0.12.3; every tick-denominated constant doubles with the rate so real-world durations stay identical): `src/lib/minigames/bomperator/{constants,types,engine,views}.ts` are pure/client-safe (seeded RNG via `state.rngState`/`gridSeed`; `generateGrid`, `createMatchState`, `startRound`, `applyInput`, `tick`), and `registry.ts` runs one `setInterval(TICK_MS)` per live match (started on `startMatch`, cleared on complete/dissolve; `globalThis.__bomperatorMatches`; SINGLE-INSTANCE ONLY: a restart/redeploy kills live matches). Grid is 15x13 (border + even/even pillars + seeded crates with one hidden power-up each; four classic pickups bomb/range/speed/kick). Movement is grid-locked with sub-cell interpolation; charges fuse ~2.5s, cross-flames stop at walls, destroy crates, chain-detonate, and kick-push; round ends at <=1 alive; sudden death spawns random-cell explosions after the 150s timer, with a draw guard. FFA has no hidden info so `buildBomperatorView` serves every viewer the same board (`yourSeat: null` = spectator). Clients POST inputs (`sendBomperatorInput`, rate-limited 40/s) and poll `fetchBomperatorMatch` (~500ms fallback behind the SSE stream); a rolling event buffer (monotonic ids) drives client SFX without diffing. Disconnects hold the seat for `RECONNECT_WINDOW_MS` then eliminate; below two active seats the match dissolves. Rewards on completion via `stats.ts` (`minigame:bomperator`, profile group `bomperator`: matchesPlayed/matchWins/roundsWon/kills/xpEarned; XP win/loss base + per-kill bounty, chips auto-derived). Registry row ships `status: "upcoming"` (page renders `MinigameComingSoon` until an admin flips it active).
- **Client prediction & correction**: `BomperatorGame.tsx` predicts its own seat between snapshots and reconciles with a lead-aware envelope policy (helpers in `bomperator/prediction.ts`): gaps inside `max(PRED_DEADZONE, speed*(rttAvg/2 + TICK_MS/2 + PRED_ENVELOPE_BUDGET_MS)/1000)` ride untouched, anything beyond is trimmed on EVERY snapshot, and gaps past 2.5 cells ease toward the estimate at up to 2.5x run speed instead of teleporting (round resets still snap via the ack-backwards branch). Root cause of the old teleport-back: Node event-loop stalls make the server's 20Hz tick loop DROP setInterval callbacks (no catch-up), so the sim permanently lags wall clock; the old all-inputs-acked pull let that gap stack and discharge at once. `tests/int/bomperator-prediction.int.spec.ts` is an offline deterministic harness (real engine + modeled network + frame-by-frame reconcile mirror) including production-latency replay (`tests/fixtures/bomperator-prod-rtt.json`, from HAR) and a server-stall A/B proof; change client prediction in BOTH component and mirror, and run the trace scenarios before shipping. v0.12.4 lesson (reverted in v0.12.5): do not add mechanisms that trust precise latency estimates (decision nudges, projected ghost placement); real TTFB swings 31-463ms and they glitch under it. - **Client prediction & correction**: `BomperatorGame.tsx` predicts its own seat between snapshots and reconciles with a lead-aware envelope policy (helpers in `bomperator/prediction.ts`): gaps inside `max(PRED_DEADZONE, speed*(rttAvg/2 + TICK_MS/2 + PRED_ENVELOPE_BUDGET_MS)/1000)` ride untouched, anything beyond is trimmed on EVERY snapshot, and gaps past 2.5 cells ease toward the estimate at up to 2.5x run speed instead of teleporting (round resets still snap via the ack-backwards branch). Root cause of the old teleport-back: Node event-loop stalls make the server's 20Hz tick loop DROP setInterval callbacks (no catch-up), so the sim permanently lags wall clock; the old all-inputs-acked pull let that gap stack and discharge at once. `tests/int/bomperator-prediction.int.spec.ts` is an offline deterministic harness (real engine + modeled network + frame-by-frame reconcile mirror) including production-latency replay (`tests/fixtures/bomperator-prod-rtt.json`, from HAR) and a server-stall A/B proof; change client prediction in BOTH component and mirror, and run the trace scenarios before shipping. v0.12.4 lesson (reverted in v0.12.5): do not add mechanisms that trust precise latency estimates (decision nudges, projected ghost placement); real TTFB swings 31-463ms and they glitch under it.
- **Mobile / touch input**: `BomperatorTouchControls.tsx` renders a D-pad (+ stop) and plant button on coarse pointers only (`(pointer: coarse)`); the board itself accepts swipes (dominant-axis cardinal, sets direction) and taps (stop). ALL input sources feed the same `pressDir`/`releaseDir`/`stopAll` edge callbacks in `BomperatorGame.tsx` that keyboard uses, so prediction/keepalive/pending logic stays source-agnostic; held-stack priority makes D-pad + swipe coexist. Canvas is CSS-scaled (`w-full h-auto`, max 520px wrapper) with fixed internal resolution. Backgrounded-tab safety is harness-proven ("backgrounded tab" scenario: 4s rAF freeze under prod trace replay, teleports=0). E2E smoke: `tests/e2e/bomperator-mobile.e2e.spec.ts` (phone viewport, no horizontal overflow); run with `E2E_BROWSER_PATH=<playwright chromium>` when Vivaldi crashes.
- Leaderboards match active players by user id (not display name) — see commit 72715c4 if leaderboard queries look wrong. - Leaderboards match active players by user id (not display name) — see commit 72715c4 if leaderboard queries look wrong.
## Periods, achievements & the game registry ## Periods, achievements & the game registry

View file

@ -0,0 +1,37 @@
import { expect, test } from "@playwright/test";
/**
* Mobile layout smoke for Ordnance Disposal (touch-controls feature).
*
* Guards the responsive shell at phone size: login works on a coarse-pointer
* viewport, the game page renders, and nothing overflows horizontally. Real
* touch interaction (D-pad, swipes, multi-touch planting) is verified by
* manual playtest with a phone and desktop in one live match; automating the
* canvas itself would only re-test the engine, which the integration suite
* already covers deterministically.
*/
test.describe("Bomperator mobile layout", () => {
test.use({
viewport: { width: 390, height: 844 },
hasTouch: true,
isMobile: true,
});
test("game page loads at phone width without horizontal overflow", async ({ page }) => {
await page.goto("/login");
await page.getByLabel("Username").fill("dev");
await page.getByLabel("Password").fill("Test123");
await page.getByRole("button", { name: "Log in" }).click();
await page.waitForURL((url) => !url.pathname.startsWith("/login"), { timeout: 30_000 });
await page.goto("/minigames/bomperator");
await expect(
page.getByRole("heading", { name: /ordnance disposal/i }).first(),
).toBeVisible({ timeout: 60_000 });
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
);
expect(overflow).toBeLessThanOrEqual(1);
});
});

View file

@ -776,6 +776,27 @@ describe("bomperator prediction harness", () => {
expect(tel.snaps).toHaveLength(0); expect(tel.snaps).toHaveLength(0);
}); });
it("backgrounded tab: a 4s freeze every 20s resumes without teleporting", () => {
// Mobile reality: app switches stop rAF for seconds while the server keeps
// running. On resume the dt cap under-advances pred by nearly the whole
// freeze, so the gap can only close through the correction path. The
// envelope policy must reel in at the capped rate - never teleport. This
// is the guarantee the touch-controls work depends on.
const cfg: ScenarioConfig = {
...BASE,
legMs: 350,
rttTrace: loadProdTrace(),
stallEveryMs: 20000,
stallMs: 4000,
};
const tel = runScenario(cfg);
report("background-resume", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.teleports).toBe(0);
expect(tel.maxJump).toBeLessThanOrEqual(1.5);
expect(tel.completedMs).toBeGreaterThan(85_000);
});
it("prod trace: measured HAR latency replay never hard-snaps", () => { it("prod trace: measured HAR latency replay never hard-snaps", () => {
// The v0.12.4 regression shipped because every scenario here assumed a // The v0.12.4 regression shipped because every scenario here assumed a
// calm 90ms RTT. This replays the actual production input round-trips // calm 90ms RTT. This replays the actual production input round-trips