1
0
Fork 0

Compare commits

...

6 commits

Author SHA1 Message Date
535a5208da v0.12.0 - add Ordnance Disposal multiplayer drill, anchor SSE bus for dev 2026-10-16 00:43:51 -04:00
f1b26c3998 docs: add v0.12.0 changelog entry 2026-10-16 00:43:46 -04:00
bbee22a457 docs(minigames): drop em-dash from bomperator AGENTS note 2026-10-16 00:38:45 -04:00
e29af6bc29 test(minigames): add bomperator engine and registry specs
22 engine tests cover grid seeding, movement, charge fuse/detonation, chain
blasts, kick-push, round end and sudden death. 17 registry tests cover lobby,
seat lifecycle, reconnect window, dissolve below two seats, expiry sweep and XP
reward derivation.
2026-10-16 00:32:54 -04:00
bfb5cea3c1 feat(minigames): add Ordnance Disposal (bomperator) multiplayer drill
Add a 2-8 player free-for-all Bomberman-style charge-clearing drill at
/minigames/bomperator, category multiplayer. Pure engine plus a single-instance
in-memory match registry, mirroring the call-for-fire-versus split but upgraded
from turn-based to a fixed ~10 Hz tick loop.

Engine (src/lib/minigames/bomperator): seeded RNG via state.rngState/gridSeed;
grid is 15x13 with border, even/even pillars and seeded crates; classic pickups
bomb/range/speed/kick. Movement is grid-locked with sub-cell interpolation,
charges fuse about 2.5s, cross-flames stop at walls, crates are destroyed and
charges chain-detonate and kick-push. Round ends at one alive; sudden death
spawns random explosions after 150s with a draw guard.

Registry (registry.ts): one setInterval per live match started on startMatch and
cleared on complete/dissolve; globalThis-anchored map; holds seats across a
reconnect window then eliminates; below two active seats it dissolves. On a
manual end, broadcasts a bomperator-terminated event so remaining players see a
toast, then awards rewards via stats.ts (minigame:bomperator, profile group
bomperator: matchesPlayed/matchWins/roundsWon/kills/xpEarned).

Clients POST rate-limited inputs and poll fetchBomperatorMatch; the SSE bus pushes
snapshots with a guarded slow-poll fallback. Registry row ships as upcoming so the
page renders the coming-soon shell until an admin flips it active. Adds the
migration for the stats group, the minigame:bomperator event type, XP
aggregation on the profile, generated types, and real-time event wiring.
2026-10-16 00:32:52 -04:00
4c6d34e868 feat(realtime): anchor SSE client set on globalThis for cross-bundle delivery
Next.js dev bundles server packages per route, so a module-level Set forks
into one copy per bundle: a broadcast issued from a server action or registry
bundle would never reach a client subscribed through the /api/realtime route
bundle. Anchoring the client set on globalThis unifies every bundle copy within
the single dev process, the same trick blackjack/poker already use. It is a
no-op in production, which has one module instance anyway.
2026-10-16 00:32:42 -04:00
29 changed files with 4944 additions and 2 deletions

View file

@ -1,5 +1,19 @@
# Changelog
# v0.12.0
Ordnance Disposal, a new real-time multiplayer drill, plus various bug fixes and improvements.
### Features
- **Ordnance Disposal.** A free-for-all demolition duel for 2 to 8 players now lives at /minigames/bomperator. Blast your rivals off the depot grid and be the last technician standing to win the round. Pickup crates boost your bomb range, blast radius, and move speed, while charges fuse, destroy crates, and set neighbouring charges off in chain reactions. Every round counts toward your disposal record and awards XP and chips on completion.
### Fixes
- Various bug fixes and improvements.
---
# v0.11.2
Various bug fixes and improvements.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.11.2",
"version": "0.12.0",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -0,0 +1,172 @@
"use server";
/**
* Server-action surface for Ordnance Disposal (internal key `bomperator`).
* All match logic lives in the registry
* (src/lib/minigames/bomperator/registry.ts). The userId is always taken from
* the session, never from a client payload.
*/
import config from "@payload-config";
import { getPayload } from "payload";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import type {
BomperatorMatchSummary,
BomperatorView,
} from "@/lib/minigames/bomperator/types";
import type { BomperatorInput } from "@/lib/minigames/bomperator/engine";
import {
createMatch,
endMatch,
forceExpireMatch,
getSnapshotFor,
joinMatch,
leaveMatch,
listMatchSummaries,
startMatch,
submitInput,
} from "@/lib/minigames/bomperator/registry";
export type { BomperatorMatchSummary, BomperatorView, BomperatorInput };
interface ActionResult<T = undefined> {
success: boolean;
error?: string;
data?: T;
}
async function authenticate() {
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
const { headers } = await import("next/headers");
const hdrs = await headers();
const { user } = await payload.auth({
headers: hdrs,
canSetHeaders: false,
});
if (!user) {
throw new Error("Unauthorized");
}
return { payload, user };
}
function toError(error: unknown): { success: false; error: string } {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };
}
return { success: false, error: message };
}
interface UserLike {
id: number;
displayName?: string | null;
username?: string | null;
}
function userName(user: UserLike): string {
if (typeof user.displayName === "string" && user.displayName) return user.displayName;
if (typeof user.username === "string" && user.username) return user.username;
return `Operator ${user.id}`;
}
export async function createBomperatorMatch(
roundTarget?: number,
): Promise<ActionResult<{ matchId: string }>> {
try {
const { user } = await authenticate();
const matchId = createMatch(Number(user.id), userName(user), roundTarget);
return { success: true, data: { matchId } };
} catch (error) {
return toError(error);
}
}
export async function listBomperatorMatches(): Promise<ActionResult<BomperatorMatchSummary[]>> {
try {
const { user } = await authenticate();
return { success: true, data: listMatchSummaries(Number(user.id)) };
} catch (error) {
return toError(error);
}
}
export async function joinBomperatorMatch(matchId: string): Promise<ActionResult<BomperatorView>> {
try {
const { user } = await authenticate();
return { success: true, data: joinMatch(matchId, Number(user.id), userName(user)) };
} catch (error) {
return toError(error);
}
}
export async function fetchBomperatorMatch(
matchId: string,
): Promise<ActionResult<BomperatorView>> {
try {
const { user } = await authenticate();
return { success: true, data: getSnapshotFor(matchId, Number(user.id)) };
} catch (error) {
return toError(error);
}
}
export async function startBomperatorMatch(matchId: string): Promise<ActionResult<BomperatorView>> {
try {
const { user } = await authenticate();
return { success: true, data: startMatch(matchId, Number(user.id)) };
} catch (error) {
return toError(error);
}
}
export async function sendBomperatorInput(
matchId: string,
input: BomperatorInput,
): Promise<ActionResult<undefined>> {
try {
const { user } = await authenticate();
submitInput(matchId, Number(user.id), input);
return { success: true };
} catch (error) {
return toError(error);
}
}
export async function leaveBomperatorMatch(matchId: string): Promise<ActionResult<undefined>> {
try {
const { user } = await authenticate();
leaveMatch(matchId, Number(user.id));
return { success: true };
} catch (error) {
return toError(error);
}
}
export async function endBomperatorMatch(matchId: string): Promise<ActionResult<undefined>> {
try {
const { user } = await authenticate();
endMatch(matchId, Number(user.id));
return { success: true };
} catch (error) {
return toError(error);
}
}
export async function forceExpireBomperatorMatch(
matchId: string,
): Promise<ActionResult<undefined>> {
try {
const { payload, user } = await authenticate();
const allowed = await isSuperuser(payload, user);
if (!allowed) {
return { success: false, error: "Only administrators can force-end matches." };
}
forceExpireMatch(matchId);
return { success: true };
} catch (error) {
return toError(error);
}
}

View file

@ -0,0 +1,87 @@
import type { Metadata } from "next";
import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { redirect } from "next/navigation";
import { Bomb } from "lucide-react";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { BomperatorArena } from "@/components/frontend/minigames/bomperator/BomperatorArena";
export const metadata: Metadata = {
title: "Ordnance Disposal (Polaris Task Force)",
description:
"Multiplayer charge-clearing drill: a real-time free-for-all on the depot grid. Last technician standing wins.",
};
interface BomperatorPageProps {
searchParams: Promise<{
match?: string | string[];
}>;
}
export default async function BomperatorPage({ searchParams }: BomperatorPageProps) {
const headers = await nextHeaders();
const payload = await getPayload({ config: await config });
const { user } = await payload.auth({ headers, canSetHeaders: false });
if (!user) {
redirect(`/login?returnTo=${encodeURIComponent("/minigames/bomperator")}`);
}
const release = await getMinigameReleaseState(payload, "bomperator");
if (release.upcoming && release.game) {
return <MinigameComingSoon game={release.game} />;
}
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: Number(user.id) } },
limit: 1,
depth: 0,
overrideAccess: true,
select: {
progression: {
minigames: true,
},
},
});
const bomp = profileRes.docs[0]?.progression?.minigames?.bomperator ?? {};
const stats = {
matchesPlayed: bomp.matchesPlayed ?? 0,
matchWins: bomp.matchWins ?? 0,
roundsWon: bomp.roundsWon ?? 0,
kills: bomp.kills ?? 0,
xpEarned: bomp.xpEarned ?? 0,
};
const params = await searchParams;
const matchValue = params.match;
const initialMatchId = Array.isArray(matchValue) ? matchValue[0] : matchValue;
return (
<div className="flex min-w-0 flex-col gap-6 p-5">
{release.game?.status === "phasingOut" && (
<PhasingOutBanner estimatedRemovalDate={release.game.estimatedRemovalDate} />
)}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<Bomb className="size-5 text-muted-foreground" />
<h1 className="text-lg font-semibold">Ordnance Disposal</h1>
</div>
<p className="text-sm text-muted-foreground">
A real-time free-for-all on the depot grid. Grab power-ups from supply stacks, plant charges,
and blow your rivals off the field. Last technician standing takes the round.
</p>
</div>
<BomperatorArena
initialStats={stats}
currentUserId={Number(user.id)}
initialMatchId={initialMatchId}
/>
</div>
);
}

View file

@ -134,6 +134,7 @@ export const Profiles: CollectionConfig = {
opordRecall?: { xpEarned?: number | null };
callForFire?: { xpEarned?: number | null };
callForFireVersus?: { xpEarned?: number | null };
bomperator?: { xpEarned?: number | null };
poker?: { xpEarned?: number | null };
blackjack?: { xpEarned?: number | null };
};
@ -156,6 +157,7 @@ export const Profiles: CollectionConfig = {
const callForFireXp = progressionData?.minigames?.callForFire?.xpEarned ?? 0;
const callForFireVersusXp =
progressionData?.minigames?.callForFireVersus?.xpEarned ?? 0;
const bomperatorXp = progressionData?.minigames?.bomperator?.xpEarned ?? 0;
const pokerXp = progressionData?.minigames?.poker?.xpEarned ?? 0;
const blackjackXp = progressionData?.minigames?.blackjack?.xpEarned ?? 0;
const voiceoverXp = progressionData?.voiceover?.xpEarned ?? 0;
@ -206,6 +208,8 @@ export const Profiles: CollectionConfig = {
xpAcc += callForFireXp;
// Call for Fire versus: XP from artillery duels
xpAcc += callForFireVersusXp;
// Ordnance Disposal: XP from multiplayer charge-clearing drills
xpAcc += bomperatorXp;
// Poker sit-and-go: XP from placement payouts
xpAcc += pokerXp;
// Blackjack sessions: XP from profit-based payouts
@ -758,6 +762,43 @@ export const Profiles: CollectionConfig = {
},
],
},
{
name: "bomperator",
label: "Ordnance Disposal",
type: "group",
fields: [
{
name: "matchesPlayed",
label: "Drills Run",
type: "number",
defaultValue: 0,
},
{
name: "matchWins",
label: "Drills Won",
type: "number",
defaultValue: 0,
},
{
name: "roundsWon",
label: "Rounds Won",
type: "number",
defaultValue: 0,
},
{
name: "kills",
label: "Technicians Down",
type: "number",
defaultValue: 0,
},
{
name: "xpEarned",
label: "XP Earned",
type: "number",
defaultValue: 0,
},
],
},
{
name: "poker",
label: "Poker",

View file

@ -0,0 +1,292 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import {
endBomperatorMatch,
fetchBomperatorMatch,
leaveBomperatorMatch,
startBomperatorMatch,
type BomperatorView,
} from "@/app/(frontend)/minigames/bomperator/actions";
import { toast } from "sonner";
import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import {
BOMP_STATE_EVENT,
BOMP_TERMINATED_EVENT,
type BomperatorStateDetail,
type BomperatorTerminatedDetail,
} from "@/hooks/useGameTick";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { BomperatorLobby } from "./BomperatorLobby";
import { BomperatorGame } from "./BomperatorGame";
export interface BomperatorStats {
matchesPlayed: number;
matchWins: number;
roundsWon: number;
kills: number;
xpEarned: number;
}
const STAT_ITEMS = [
["Drills run", "matchesPlayed"],
["Drills won", "matchWins"],
["Rounds won", "roundsWon"],
["Technicians down", "kills"],
["XP earned", "xpEarned"],
] as const satisfies readonly (readonly [string, keyof BomperatorStats])[];
type ArenaView = "lobby" | "match";
/**
* Snapshot delivery is push-first: the server broadcasts a per-user snapshot over
* the SSE bus on every tick (see registry.pushSnapshots). This poll is only a
* correctness fallback for dropped pushes / dev module reloads, so it runs far
* slower than a tick and skips entirely while a request is already in flight.
* 500ms is deliberately conservative: it is ~50x lighter than the old 40ms flood
* (which saturated the dev server and delayed inputs by seconds), yet still bounds
* staleness to half a second even if the push path never lands.
*/
const FALLBACK_POLL_MS = 500;
export function BomperatorArena({
initialStats,
currentUserId,
initialMatchId,
}: {
initialStats: BomperatorStats;
currentUserId: number | string;
initialMatchId?: string;
}) {
const [view, setView] = useState<ArenaView>(initialMatchId ? "match" : "lobby");
const [match, setMatch] = useState<BomperatorView | null>(null);
const [matchId, setMatchId] = useState<string | null>(initialMatchId ?? null);
const [error, setError] = useState<string | null>(null);
/** Highest snapshot version applied; drops stale pushes/polls that arrive late. */
const lastVersionRef = useRef(-1);
/** Once we've handled leaving a match (self or remote), suppress repeat toasts. */
const endedRef = useRef(false);
const resetToLobby = useCallback(() => {
lastVersionRef.current = -1;
setView("lobby");
setMatch(null);
setMatchId(null);
setError(null);
if (typeof window !== "undefined") {
window.history.replaceState(null, "", "/minigames/bomperator");
}
}, []);
/** Apply a snapshot from any source (push or poll), ignoring stale versions. */
const applySnapshot = useCallback((next: BomperatorView) => {
if (next.version <= lastVersionRef.current) return;
lastVersionRef.current = next.version;
setMatch(next);
setMatchId(next.matchId);
setView("match");
setError(null);
}, []);
const applyMatch = useCallback((next: BomperatorView) => {
// Fresh match opened from the lobby: accept it regardless of version history.
endedRef.current = false;
lastVersionRef.current = next.version;
setMatch(next);
setMatchId(next.matchId);
setView("match");
setError(null);
if (typeof window !== "undefined" && next.matchId) {
window.history.replaceState(
null,
"",
`/minigames/bomperator?match=${encodeURIComponent(next.matchId)}`,
);
}
}, []);
/**
* Leave the current match with an explanatory toast, at most once per match.
* Used by both the host-ended SSE event and the poll's "not found" fallback, so
* whichever lands first wins and the other is ignored.
*/
const handleEnded = useCallback(
(message: string) => {
if (endedRef.current) return;
endedRef.current = true;
toast.info(message);
resetToLobby();
},
[resetToLobby],
);
// Deep link into a match (as a player or a spectator).
useEffect(() => {
if (!initialMatchId) return;
let cancelled = false;
void fetchBomperatorMatch(initialMatchId)
.then((result) => {
if (cancelled) return;
if (result.success && result.data) {
endedRef.current = false;
applySnapshot(result.data);
if (typeof window !== "undefined") {
window.history.replaceState(
null,
"",
`/minigames/bomperator?match=${encodeURIComponent(initialMatchId)}`,
);
}
} else {
setError(result.error ?? "This match was not found.");
}
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [initialMatchId, applySnapshot]);
// Push-first: apply snapshots the server broadcasts over the SSE bus for this
// match. The bus is globalThis-anchored so it reaches us from the action/tick
// bundles; version dedup keeps it consistent with the fallback poll below.
useEffect(() => {
if (view !== "match" || matchId === null) return;
const handleState = (event: Event) => {
const detail = (event as CustomEvent<BomperatorStateDetail>).detail;
if (!detail || detail.matchId !== matchId || !detail.snapshot) return;
applySnapshot(detail.snapshot);
};
window.addEventListener(BOMP_STATE_EVENT, handleState);
return () => window.removeEventListener(BOMP_STATE_EVENT, handleState);
}, [view, matchId, applySnapshot]);
// The host ended the drill: tell everyone else why, then drop to the lobby.
useEffect(() => {
if (view !== "match" || matchId === null) return;
const handleTerminated = (event: Event) => {
const detail = (event as CustomEvent<BomperatorTerminatedDetail>).detail;
if (!detail || detail.matchId !== matchId) return;
const message =
detail.reason === "host-ended"
? detail.hostName
? `${detail.hostName} ended the drill.`
: "The host ended the drill."
: "This drill has ended.";
handleEnded(message);
};
window.addEventListener(BOMP_TERMINATED_EVENT, handleTerminated);
return () => window.removeEventListener(BOMP_TERMINATED_EVENT, handleTerminated);
}, [view, matchId, handleEnded]);
// Slow, in-flight-guarded fallback poll: recovers dropped pushes and detects a
// dissolved match. Not the latency path (the push is), so it stays gentle and
// never stacks requests behind an outstanding one.
useEffect(() => {
if (view !== "match" || matchId === null) return;
let cancelled = false;
let inFlight = false;
const run = () => {
if (inFlight) return;
inFlight = true;
void fetchBomperatorMatch(matchId)
.then((result) => {
if (cancelled) return;
if (result.success && result.data) {
applySnapshot(result.data);
} else if (result.error === "Match not found.") {
// Fallback for a missed host-ended push: neutral wording, since the
// poll alone cannot tell why the match disappeared.
handleEnded("This drill has ended.");
}
})
.catch(() => undefined)
.finally(() => {
if (!cancelled) inFlight = false;
});
};
const poll = window.setInterval(run, FALLBACK_POLL_MS);
return () => {
cancelled = true;
window.clearInterval(poll);
};
}, [view, matchId, applySnapshot, handleEnded]);
const start = useCallback(async () => {
if (!matchId) return;
const result = await startBomperatorMatch(matchId);
if (result.success && result.data) applySnapshot(result.data);
else setError(result.error ?? "Could not start the drill.");
}, [matchId, applySnapshot]);
const leave = useCallback(async () => {
endedRef.current = true; // self-initiated exit: no "ended" toast for us
if (matchId) {
try {
await leaveBomperatorMatch(matchId);
} catch {
// Leaving is best-effort; resetting the view is what matters.
}
}
resetToLobby();
}, [matchId, resetToLobby]);
const end = useCallback(async () => {
endedRef.current = true; // we are the host ending it; no toast for us
if (matchId) {
try {
await endBomperatorMatch(matchId);
} catch {
// Best-effort; the host is leaving regardless.
}
}
resetToLobby();
}, [matchId, resetToLobby]);
const inMatch = view === "match" && matchId !== null;
const operatorsOnline = useRealtimePresence("bomperator", inMatch, true);
return (
<div className="flex flex-col gap-6">
<Card>
<CardHeader className="border-b p-4">
<CardTitle className="text-sm">Your disposal record</CardTitle>
<p className="text-sm text-muted-foreground">
Rewards are granted when a drill ends. Free-for-all, 2-8 technicians.
</p>
</CardHeader>
<CardContent className="grid grid-cols-2 gap-3 p-4 sm:grid-cols-5">
{STAT_ITEMS.map(([label, key]) => (
<div key={key} className="flex flex-col gap-1 rounded-lg border border-border p-3">
<span className="text-xs uppercase tracking-wider text-muted-foreground">{label}</span>
<span className="font-mono text-lg font-semibold tabular-nums">
{initialStats[key].toLocaleString()}
</span>
</div>
))}
</CardContent>
</Card>
{error && (
<p className="text-sm text-destructive" role="alert">
{error}
</p>
)}
{view === "lobby" ? (
<BomperatorLobby onOpenMatch={applyMatch} currentUserId={currentUserId} />
) : match ? (
<BomperatorGame
match={match}
currentUserId={currentUserId}
onLeave={leave}
onEnd={end}
onStart={start}
operatorsOnline={operatorsOnline.map((participant) => participant.name)}
/>
) : (
<p className="text-sm text-muted-foreground">Loading match…</p>
)}
</div>
);
}

View file

@ -0,0 +1,583 @@
"use client";
import { useCallback, useEffect, useRef, useState } 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 { GRID_H, GRID_W, MAX_SEATS, MIN_TO_START, TICKS_PER_SECOND } from "@/lib/minigames/bomperator/constants";
import { sendBomperatorInput } from "@/app/(frontend)/minigames/bomperator/actions";
import { BomperatorHud, seatColor } from "./BomperatorHud";
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;
}
/* ------------------------------------------------------------- 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 as the fuse burns down.
const blink = fuseTicks <= 6 ? 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 / 3 + 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);
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();
try {
await sendBomperatorInput(match.matchId, { drop: true });
} catch {
// Ignore transient failures.
}
}, [match.matchId, playPlace]);
useEffect(() => {
if (!canControl) return;
// Level-triggered movement: the server keeps applying the last direction we
// sent until we send a different one, so we only transmit on change (edge),
// plus a slow re-assert while a key is held to recover a lost packet. A single
// in-flight request with coalescing means inputs never stack behind each other
// or behind polls, which is what kept them seconds behind under load.
let desired: Dir | null = null;
let sending = false;
let pending = false;
const flush = () => {
if (sending) {
pending = true;
return;
}
sending = true;
const dir = desired;
void sendBomperatorInput(match.matchId, { dir })
.catch(() => undefined)
.finally(() => {
sending = false;
if (pending) {
pending = false;
flush();
}
});
};
const setDir = (dir: Dir | null) => {
desired = dir;
flush();
};
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();
heldKeysRef.current = [dir, ...heldKeysRef.current.filter((d) => d !== dir)];
setDir(dir);
};
const onKeyUp = (e: KeyboardEvent) => {
const dir = KEY_DIR[e.code];
if (!dir) return;
heldKeysRef.current = heldKeysRef.current.filter((d) => d !== dir);
setDir(heldKeysRef.current[0] ?? null);
};
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(() => {
if (desired !== null) flush();
}, 400);
return () => {
window.removeEventListener("keydown", onKeyDown, { capture: true });
window.removeEventListener("keyup", onKeyUp, { capture: true });
window.clearInterval(keepalive);
heldKeysRef.current = [];
};
}, [canControl, match.matchId, sendDrop]);
/* ---- render loop: ease toward the latest snapshot each frame ---- */
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;
canvas.style.width = `${CANVAS_W}px`;
canvas.style.height = `${CANVAS_H}px`;
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 dt = Math.min((now - last) / 16.6667, 3);
last = now;
const view = matchRef.current;
const pos = renderPosRef.current;
const ease = Math.min(1, 0.4 * dt);
// Ease every technician toward its authoritative server position. Monotonic
// (never overshoots a collision-valid target), so it cannot jitter or show a
// technician inside a wall. A large gap snaps instead of sliding across the
// map (round resets / teleports).
for (const player of view.players) {
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) drawBomb(ctx, bomb.x, bomb.y, bomb.fuseTicks, now);
for (const flame of view.flames) drawFlame(ctx, flame.x, flame.y, flame.ticksLeft, now);
for (const player of view.players) {
const rp = 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]">
<canvas
ref={canvasRef}
className="block 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>
<p className="text-center text-[11px] text-muted-foreground">
Move: WASD / arrows · Plant charge: Space
</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>
);
}

View file

@ -0,0 +1,132 @@
"use client";
import { Flame, Skull, Timer, Zap } from "lucide-react";
import type { BomperatorView, PlayerView } from "@/lib/minigames/bomperator/types";
import { BASE_SPEED_CELLS_PER_S, TICKS_PER_SECOND } from "@/lib/minigames/bomperator/constants";
import { cn } from "@/lib/utils";
/** Distinct technician color per seat, shared by the HUD chips and the canvas. */
export const SEAT_COLORS = [
"#38bdf8", // sky
"#f472b6", // pink
"#a3e635", // lime
"#fbbf24", // amber
"#c084fc", // violet
"#fb7185", // rose
"#34d399", // emerald
"#f97316", // orange
];
export function seatColor(seat: number): string {
return SEAT_COLORS[seat % SEAT_COLORS.length];
}
function Pip({ label, value, accent }: { label: string; value: string; accent?: boolean }) {
return (
<span
className={cn(
"flex items-center gap-1 rounded-sm border border-border/60 bg-background/40 px-1.5 py-0.5 font-mono text-[11px] tabular-nums",
accent && "border-amber-500/50 text-amber-300",
)}
title={label}
>
<span className="text-muted-foreground">{label}</span>
<span className="font-semibold text-foreground">{value}</span>
</span>
);
}
export function BomperatorHud({
match,
currentUserId,
}: {
match: BomperatorView;
currentUserId: number | string;
}) {
const me = match.yourSeat !== null ? match.players[match.yourSeat] : null;
const timerSeconds = Math.ceil(match.roundTimerTicks / TICKS_PER_SECOND);
const speedBoost = me ? Math.max(0, Math.round(me.speed - BASE_SPEED_CELLS_PER_S)) : 0;
return (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border bg-card px-3 py-2">
<div className="flex items-center gap-3 text-sm">
<span className="flex items-center gap-1 font-medium">
<Skull className="size-4 text-muted-foreground" />
{match.aliveCount} alive
</span>
<span className="text-xs text-muted-foreground">
Round {match.roundIndex + 1} · first to {match.roundTarget}
</span>
</div>
<div className="flex items-center gap-2">
{match.suddenDeath ? (
<span className="flex animate-pulse items-center gap-1 rounded-sm bg-red-600/20 px-2 py-0.5 text-xs font-semibold uppercase tracking-wider text-red-300">
<Flame className="size-3.5" /> Sudden death
</span>
) : (
<span
className={cn(
"flex items-center gap-1 font-mono text-sm tabular-nums",
timerSeconds <= 20 ? "text-amber-400" : "text-muted-foreground",
)}
>
<Timer className="size-4" />
{timerSeconds}s
</span>
)}
</div>
</div>
{/* Scoreboard */}
<div className="flex flex-wrap gap-1.5">
{match.players.map((player) => (
<ScoreChip
key={player.seat}
player={player}
isYou={String(player.userId) === String(currentUserId)}
/>
))}
</div>
{/* Own loadout pips */}
{me && me.alive && (
<div className="flex flex-wrap items-center gap-1.5 text-xs">
<Pip label="Charges" value={String(me.bombsMax)} />
<Pip label="Range" value={String(me.range)} accent={me.range > 1} />
<Pip label="Speed" value={speedBoost > 0 ? `+${speedBoost}` : "base"} accent={speedBoost > 0} />
<Pip label="Kick" value={me.kick ? "yes" : "no"} accent={me.kick} />
<span className="ml-1 flex items-center gap-1 text-[11px] text-muted-foreground">
<Zap className="size-3" /> {me.kills} down
</span>
</div>
)}
</div>
);
}
function ScoreChip({ player, isYou }: { player: PlayerView; isYou: boolean }) {
return (
<span
className={cn(
"flex items-center gap-1.5 rounded-sm border px-2 py-1 text-xs",
player.alive ? "border-border bg-background/40" : "border-border/40 bg-background/20 opacity-60",
isYou && "ring-1 ring-inset ring-white/40",
)}
title={`${player.name}${player.connected ? "" : " (disconnected)"}`}
>
<span
className="size-2.5 shrink-0 rounded-full"
style={{ backgroundColor: seatColor(player.seat) }}
aria-hidden="true"
/>
<span className={cn("max-w-[8rem] truncate font-medium", !player.alive && "line-through")}>
{isYou ? "You" : player.name}
</span>
<span className="font-mono tabular-nums text-muted-foreground">
{player.roundsWon}
{!player.connected && <span className="ml-1 text-amber-400">·</span>}
</span>
</span>
);
}

View file

@ -0,0 +1,180 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { Eye, Plus, RefreshCw, Bomb } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ROUND_TARGET_OPTIONS } from "@/lib/minigames/bomperator/constants";
import type { BomperatorMatchSummary, BomperatorView } from "@/lib/minigames/bomperator/types";
import {
createBomperatorMatch,
fetchBomperatorMatch,
joinBomperatorMatch,
listBomperatorMatches,
} from "@/app/(frontend)/minigames/bomperator/actions";
const PHASE_LABELS: Record<BomperatorMatchSummary["phase"], string> = {
waiting: "Waiting for technicians",
lobby: "In the waiting room",
countdown: "Starting",
battle: "In progress",
roundEnd: "Round over",
complete: "Finished",
};
export function BomperatorLobby({
onOpenMatch,
currentUserId,
}: {
onOpenMatch: (match: BomperatorView) => void;
currentUserId: number | string;
}) {
const [matches, setMatches] = useState<BomperatorMatchSummary[] | null>(null);
const [roundTarget, setRoundTarget] = useState<number>(3);
const [error, setError] = useState<string | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const refresh = useCallback(() => {
void listBomperatorMatches()
.then((result) => {
if (result.success && result.data) setMatches(result.data);
else setError(result.error ?? "Could not load matches.");
})
.catch(() => setError("Could not load matches."));
}, []);
useEffect(() => {
refresh();
const id = window.setInterval(refresh, 4000);
return () => window.clearInterval(id);
}, [refresh]);
const create = useCallback(async () => {
setBusyId("new");
setError(null);
const created = await createBomperatorMatch(roundTarget);
if (!created.success || !created.data) {
setBusyId(null);
setError(created.error ?? "Could not create a match.");
return;
}
const snapshot = await fetchBomperatorMatch(created.data.matchId);
setBusyId(null);
if (snapshot.success && snapshot.data) onOpenMatch(snapshot.data);
else refresh();
}, [onOpenMatch, refresh, roundTarget]);
const enter = useCallback(
async (matchId: string, spectate: boolean) => {
setBusyId(matchId);
setError(null);
const result = spectate ? await fetchBomperatorMatch(matchId) : await joinBomperatorMatch(matchId);
setBusyId(null);
if (result.success && result.data) onOpenMatch(result.data);
else {
setError(result.error ?? "Could not enter the match.");
refresh();
}
},
[onOpenMatch, refresh],
);
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">
<Bomb className="size-4 text-muted-foreground" />
Ordnance Disposal drills
</CardTitle>
<p className="text-sm text-muted-foreground">
Open a depot and share the link, or join one below. Last technician standing wins the round.
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex items-center gap-1" role="group" aria-label="Rounds to win">
<span className="mr-1 text-xs text-muted-foreground">Best of</span>
{ROUND_TARGET_OPTIONS.map((option) => (
<Button
key={option}
type="button"
size="sm"
variant={roundTarget === option ? "default" : "outline"}
className="h-8 w-8 p-0"
onClick={() => setRoundTarget(option)}
disabled={busyId !== null}
>
{option}
</Button>
))}
</div>
<Button variant="outline" size="sm" onClick={refresh} disabled={busyId !== null}>
<RefreshCw /> Refresh
</Button>
<Button size="sm" onClick={create} disabled={busyId !== null}>
<Plus /> New drill
</Button>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
{error && (
<p className="px-4 pt-4 text-sm text-destructive" role="alert">
{error}
</p>
)}
{matches === null ? (
<p className="px-4 py-6 text-sm text-muted-foreground">Loading matches…</p>
) : matches.length === 0 ? (
<p className="px-4 py-6 text-sm text-muted-foreground">
No live drills. Start one and send the link to your squad.
</p>
) : (
<ul className="divide-y divide-border">
{matches.map((match) => {
const open = match.phase === "waiting" || match.phase === "lobby";
const canJoin = !match.joined && open && match.seatedCount < match.maxSeats;
return (
<li
key={match.matchId}
className="flex flex-wrap items-center justify-between gap-3 px-4 py-3"
>
<div className="flex min-w-0 flex-col">
<span className="truncate text-sm font-medium">
{match.name ?? "Ordnance Disposal"}
</span>
<span className="text-xs text-muted-foreground">
{match.hostName} · {match.seatedCount}/{match.maxSeats} · first to{" "}
{match.roundTarget} · {PHASE_LABELS[match.phase]}
</span>
</div>
<div className="flex items-center gap-2">
{!open && !match.joined && (
<Button
size="sm"
variant="ghost"
disabled={busyId !== null}
onClick={() => enter(match.matchId, true)}
>
<Eye /> Watch
</Button>
)}
<Button
size="sm"
variant={match.joined || canJoin ? "default" : "outline"}
disabled={busyId !== null || (!match.joined && !canJoin)}
onClick={() => enter(match.matchId, false)}
>
{match.joined ? "Rejoin" : canJoin ? "Join" : "Full"}
</Button>
</div>
</li>
);
})}
</ul>
)}
</CardContent>
</Card>
);
}

View file

@ -0,0 +1,98 @@
"use client";
import { Music2, SlidersHorizontal, Volume2, VolumeX } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Slider } from "@/components/ui/slider";
export function BomperatorSoundToggle({
muted,
musicVolume,
effectsVolume,
onToggleMuted,
onMusicVolumeChange,
onEffectsVolumeChange,
}: {
muted: boolean;
musicVolume: number;
effectsVolume: number;
onToggleMuted: () => void;
onMusicVolumeChange: (volume: number) => void;
onEffectsVolumeChange: (volume: number) => void;
}) {
return (
<div className="flex items-center gap-1" aria-label="Ordnance Disposal audio controls">
<Button
type="button"
variant="outline"
size="icon"
className="size-8"
onClick={onToggleMuted}
aria-label={muted ? "Unmute audio" : "Mute audio"}
title={muted ? "Unmute audio" : "Mute audio"}
>
{muted ? (
<VolumeX aria-hidden="true" className="size-4" />
) : (
<Volume2 aria-hidden="true" className="size-4" />
)}
</Button>
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="size-8"
aria-label="Audio levels"
title="Audio levels"
>
<SlidersHorizontal aria-hidden="true" className="size-4" />
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-64">
<p className="text-sm font-medium">Audio</p>
<div className="mt-3 flex flex-col gap-1.5">
<Label
htmlFor="bomp-music"
className="flex items-center justify-between text-xs text-muted-foreground"
>
<span className="flex items-center gap-1.5">
<Music2 aria-hidden="true" className="size-3.5" /> Music
</span>
<span className="tabular-nums">{Math.round(musicVolume * 100)}%</span>
</Label>
<Slider
id="bomp-music"
min={0}
max={1}
step={0.05}
value={[musicVolume]}
onValueChange={(value) => onMusicVolumeChange(value[0] ?? 0)}
/>
</div>
<div className="mt-3 flex flex-col gap-1.5">
<Label
htmlFor="bomp-effects"
className="flex items-center justify-between text-xs text-muted-foreground"
>
<span className="flex items-center gap-1.5">
<Volume2 aria-hidden="true" className="size-3.5" /> Effects
</span>
<span className="tabular-nums">{Math.round(effectsVolume * 100)}%</span>
</Label>
<Slider
id="bomp-effects"
min={0}
max={1}
step={0.05}
value={[effectsVolume]}
onValueChange={(value) => onEffectsVolumeChange(value[0] ?? 0)}
/>
</div>
</PopoverContent>
</Popover>
</div>
);
}

View file

@ -0,0 +1,555 @@
"use client";
/**
* Procedural sound effects for Ordnance Disposal, plus a hook that fires them
* from the snapshot's event buffer. Pure Web Audio, no sampled assets: charges
* and pickups are synthesized tones and noise bursts, so nothing ships in
* /public. The AudioContext is created lazily and only resumes after a gesture.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import type { BomperatorView, SequencedEvent } from "@/lib/minigames/bomperator/types";
export const DEFAULT_MUSIC_VOLUME = 0.35;
export const DEFAULT_EFFECTS_VOLUME = 0.6;
const SETTINGS_KEY = "polaris:bomperator-sound";
type Tone = readonly [frequency: number, offset: number, duration: number];
function clampVolume(value: number, fallback: number): number {
if (!Number.isFinite(value)) return fallback;
return Math.min(1, Math.max(0, value));
}
/* ------------------------------------------------------------- background music */
/** Which loop is playing; chosen from the match phase + sudden-death flag. */
type MusicPhase = "calm" | "action" | "sudden";
/** Music sub-mix level, kept below the SFX path so explosions still punch. */
const MUSIC_LEVEL = 0.5;
/** Scheduler cadence and how far ahead of the audio clock we queue notes. */
const MUSIC_TICK_MS = 25;
const MUSIC_AHEAD_S = 0.12;
function midiToFreq(midi: number): number {
return 440 * Math.pow(2, (midi - 69) / 12);
}
interface MusicTrack {
readonly bpm: number;
/** 16 eighth-note steps; 0 is a rest, otherwise a MIDI note number. */
readonly bass: readonly number[];
readonly lead: readonly number[];
}
// A-minor chiptune loops, 16 steps each. Calm for the waiting room, driving for
// battle, faster and busier once sudden death starts squeezing the arena.
const CALM_TRACK: MusicTrack = {
bpm: 104,
lead: [69, 0, 72, 0, 76, 0, 72, 0, 69, 0, 72, 0, 74, 0, 72, 0],
bass: [45, 0, 0, 0, 0, 0, 0, 0, 41, 0, 0, 0, 0, 0, 0, 0],
};
const ACTION_TRACK: MusicTrack = {
bpm: 140,
lead: [57, 0, 60, 57, 55, 0, 52, 0, 57, 0, 60, 64, 62, 60, 57, 0],
bass: [33, 0, 0, 33, 0, 0, 33, 0, 33, 0, 0, 33, 0, 0, 40, 0],
};
const SUDDEN_TRACK: MusicTrack = {
bpm: 168,
lead: [59, 62, 59, 57, 54, 57, 59, 0, 59, 62, 66, 64, 62, 59, 57, 0],
bass: [33, 33, 0, 33, 33, 0, 33, 0, 33, 33, 0, 33, 40, 0, 38, 0],
};
function trackFor(phase: MusicPhase): MusicTrack {
if (phase === "calm") return CALM_TRACK;
if (phase === "sudden") return SUDDEN_TRACK;
return ACTION_TRACK;
}
export class BomperatorSoundEngine {
private context: AudioContext | null = null;
private master: GainNode | null = null;
private sfxGain: GainNode | null = null;
private musicGain: GainNode | null = null;
private muted = false;
private musicVolume = DEFAULT_MUSIC_VOLUME;
private effectsVolume = DEFAULT_EFFECTS_VOLUME;
private noiseBuffer: AudioBuffer | null = null;
private musicTimer: ReturnType<typeof setInterval> | null = null;
private musicPhase: MusicPhase | null = null;
private musicStep = 0;
private musicNextTime = 0;
setMuted(muted: boolean): void {
this.muted = muted;
this.applyMaster();
}
setMusicVolume(volume: number): void {
this.musicVolume = clampVolume(volume, DEFAULT_MUSIC_VOLUME);
this.applyMusicGain();
}
setEffectsVolume(volume: number): void {
this.effectsVolume = clampVolume(volume, DEFAULT_EFFECTS_VOLUME);
this.applySfxGain();
}
unlock(): void {
const context = this.ensureContext();
if (context && context.state === "suspended") void context.resume().catch(() => undefined);
}
dispose(): void {
this.stopMusic();
const context = this.context;
this.context = null;
this.master = null;
this.sfxGain = null;
this.musicGain = null;
this.noiseBuffer = null;
if (context) void context.close().catch(() => undefined);
}
play(event: SequencedEvent["type"] | "round-win" | "place"): void {
const context = this.ensureContext();
const sfx = this.sfxGain;
if (!context || this.muted || !sfx || this.effectsVolume <= 0) return;
const now = context.currentTime;
switch (event) {
case "place":
this.playTone(context, now, 220, 0.08, 0.14, "square");
return;
case "explosion":
this.playNoise(context, now, 0.55, 0.5, 2000);
this.playTone(context, now, 130, 0.4, 0.32, "sine", 42);
return;
case "crateBroken":
this.playNoise(context, now, 0.16, 0.22, 1200);
return;
case "pickup":
this.playTones(context, now, [
[660, 0, 0.07],
[990, 0.07, 0.09],
], "triangle", 0.18);
return;
case "death":
this.playTones(context, now, [
[400, 0, 0.12],
[240, 0.1, 0.16],
[140, 0.24, 0.24],
], "sawtooth", 0.2);
return;
case "suddenDeath":
this.playTones(context, now, [
[180, 0, 0.18],
[180, 0.22, 0.18],
[240, 0.44, 0.24],
], "square", 0.16);
return;
case "roundEnd":
this.playTones(context, now, [
[523, 0, 0.12],
[659, 0.11, 0.12],
[784, 0.22, 0.16],
], "triangle", 0.2);
return;
case "round-win":
this.playTones(context, now, [
[523, 0, 0.12],
[659, 0.11, 0.12],
[784, 0.22, 0.14],
[1047, 0.35, 0.26],
], "triangle", 0.22);
return;
default:
return;
}
}
private ensureContext(): AudioContext | null {
if (typeof window === "undefined") return null;
if (this.context) return this.context;
const ctor = (window.AudioContext ??
(window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext) as
| typeof AudioContext
| undefined;
if (!ctor) return null;
try {
const context = new ctor();
const master = context.createGain();
master.gain.value = this.muted ? 0 : 1;
master.connect(context.destination);
const sfxGain = context.createGain();
sfxGain.gain.value = this.effectsVolume;
sfxGain.connect(master);
const musicGain = context.createGain();
musicGain.gain.value = this.musicVolume * MUSIC_LEVEL;
musicGain.connect(master);
this.context = context;
this.master = master;
this.sfxGain = sfxGain;
this.musicGain = musicGain;
return context;
} catch {
return null;
}
}
private applyMaster(): void {
if (this.master) this.master.gain.value = this.muted ? 0 : 1;
}
private applySfxGain(): void {
if (this.sfxGain) this.sfxGain.gain.value = this.effectsVolume;
}
private applyMusicGain(): void {
if (this.musicGain) this.musicGain.gain.value = this.musicVolume * MUSIC_LEVEL;
}
private playTone(
context: AudioContext,
at: number,
frequency: number,
duration: number,
gain: number,
type: OscillatorType,
endFrequency?: number,
): void {
const dest = this.sfxGain;
if (!dest) return;
const osc = context.createOscillator();
const envelope = context.createGain();
osc.type = type;
osc.frequency.setValueAtTime(frequency, at);
if (endFrequency !== undefined) {
osc.frequency.exponentialRampToValueAtTime(Math.max(1, endFrequency), at + duration);
}
envelope.gain.setValueAtTime(0.0001, at);
envelope.gain.exponentialRampToValueAtTime(gain, at + Math.min(0.015, duration * 0.3));
envelope.gain.exponentialRampToValueAtTime(0.0001, at + duration);
osc.connect(envelope);
envelope.connect(dest);
osc.start(at);
osc.stop(at + duration + 0.02);
}
private playTones(
context: AudioContext,
at: number,
tones: readonly Tone[],
type: OscillatorType,
gain: number,
): void {
for (const [frequency, offset, duration] of tones) {
this.playTone(context, at + offset, frequency, duration, gain, type);
}
}
private noise(context: AudioContext): AudioBuffer {
if (this.noiseBuffer) return this.noiseBuffer;
const length = Math.floor(context.sampleRate);
const buffer = context.createBuffer(1, length, context.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < length; i += 1) data[i] = Math.random() * 2 - 1;
this.noiseBuffer = buffer;
return buffer;
}
private playNoise(
context: AudioContext,
at: number,
duration: number,
gain: number,
filterFrequency: number,
): void {
const dest = this.sfxGain;
if (!dest) return;
const source = context.createBufferSource();
source.buffer = this.noise(context);
const filter = context.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.setValueAtTime(filterFrequency, at);
const envelope = context.createGain();
envelope.gain.setValueAtTime(gain, at);
envelope.gain.exponentialRampToValueAtTime(0.0001, at + duration);
source.connect(filter);
filter.connect(envelope);
envelope.connect(dest);
source.start(at);
source.stop(at + duration + 0.02);
}
/**
* Begin (or retune) the looping background track. Idempotent: calling it while
* already running just swaps the pattern/tempo for the next scheduled steps.
* Notes are queued against the audio clock by a lookahead scheduler so timing
* stays rock-steady regardless of main-thread jitter.
*/
startMusic(phase: MusicPhase): void {
const context = this.ensureContext();
if (!context || !this.musicGain) return;
if (context.state === "suspended") void context.resume().catch(() => undefined);
this.musicPhase = phase;
if (this.musicTimer !== null) return; // running; phase swap above is enough
this.musicStep = 0;
this.musicNextTime = context.currentTime + 0.08;
this.musicTimer = setInterval(() => this.scheduleMusic(), MUSIC_TICK_MS);
this.scheduleMusic();
}
stopMusic(): void {
if (this.musicTimer !== null) {
clearInterval(this.musicTimer);
this.musicTimer = null;
}
this.musicPhase = null;
this.musicStep = 0;
}
private scheduleMusic(): void {
const context = this.context;
if (!context || !this.musicGain || this.musicPhase === null || this.muted || this.musicVolume <= 0)
return;
// While the context is suspended the clock is frozen; queue nothing until it
// runs so we never dump a burst of notes on resume.
if (context.state !== "running") return;
// Recover if we ever fall behind the clock (tab throttling, long GC pause).
if (this.musicNextTime < context.currentTime) {
this.musicNextTime = context.currentTime + 0.05;
}
const track = trackFor(this.musicPhase);
const stepDur = 60 / track.bpm / 2;
while (this.musicNextTime < context.currentTime + MUSIC_AHEAD_S) {
const at = this.musicNextTime;
const step = this.musicStep % 16;
const bass = track.bass[step];
const lead = track.lead[step];
if (bass) this.playMusicNote(context, at, bass, stepDur * 1.7, 0.18, "triangle");
if (lead) this.playMusicNote(context, at, lead, stepDur * 0.9, 0.12, "square");
this.musicNextTime += stepDur;
this.musicStep += 1;
}
}
private playMusicNote(
context: AudioContext,
at: number,
midi: number,
duration: number,
gain: number,
type: OscillatorType,
): void {
const dest = this.musicGain;
if (!dest) return;
const osc = context.createOscillator();
const envelope = context.createGain();
osc.type = type;
osc.frequency.setValueAtTime(midiToFreq(midi), at);
envelope.gain.setValueAtTime(0.0001, at);
envelope.gain.exponentialRampToValueAtTime(gain, at + Math.min(0.02, duration * 0.3));
envelope.gain.exponentialRampToValueAtTime(0.0001, at + duration);
osc.connect(envelope);
envelope.connect(dest);
osc.start(at);
osc.stop(at + duration + 0.02);
}
}
interface SoundSettings {
readonly muted: boolean;
readonly musicVolume: number;
readonly effectsVolume: number;
}
const DEFAULT_SETTINGS: SoundSettings = {
muted: false,
musicVolume: DEFAULT_MUSIC_VOLUME,
effectsVolume: DEFAULT_EFFECTS_VOLUME,
};
function readStored(): SoundSettings {
if (typeof window === "undefined") return DEFAULT_SETTINGS;
try {
const raw = window.localStorage.getItem(SETTINGS_KEY);
if (!raw) return DEFAULT_SETTINGS;
const parsed = JSON.parse(raw) as Partial<SoundSettings> & { volume?: number };
// Migrate the legacy single-`volume` shape onto both channels.
const hasChannels =
typeof parsed.musicVolume === "number" || typeof parsed.effectsVolume === "number";
if (!hasChannels) {
if (typeof parsed.volume !== "number") return DEFAULT_SETTINGS;
const legacy = clampVolume(parsed.volume, DEFAULT_EFFECTS_VOLUME);
return { muted: parsed.muted === true, musicVolume: legacy, effectsVolume: legacy };
}
return {
muted: parsed.muted === true,
musicVolume: clampVolume(parsed.musicVolume ?? DEFAULT_MUSIC_VOLUME, DEFAULT_MUSIC_VOLUME),
effectsVolume: clampVolume(parsed.effectsVolume ?? DEFAULT_EFFECTS_VOLUME, DEFAULT_EFFECTS_VOLUME),
};
} catch {
return DEFAULT_SETTINGS;
}
}
export interface BomperatorSoundControls {
muted: boolean;
musicVolume: number;
effectsVolume: number;
toggleMuted: () => void;
setMusicVolume: (volume: number) => void;
setEffectsVolume: (volume: number) => void;
/** Fire the placement sound on a local drop keypress for immediate feedback. */
playPlace: () => void;
}
/**
* Plays a sound for every event the client has not yet seen (tracked by the
* monotonic event id), so the fallback poll never drops an explosion or pickup,
* and drives the phase-based background track. Music and effects have independent
* volumes under one master mute; settings persist per browser.
*/
export function useBomperatorSounds(match: BomperatorView | null): BomperatorSoundControls {
const [settings, setSettings] = useState<SoundSettings>(DEFAULT_SETTINGS);
const settingsRef = useRef<SoundSettings>(DEFAULT_SETTINGS);
settingsRef.current = settings;
const engineRef = useRef<BomperatorSoundEngine | null>(null);
const loadedRef = useRef(false);
const lastEventIdRef = useRef<number | null>(null);
const prevPhaseRef = useRef<string | null>(null);
const ensureEngine = useCallback((): BomperatorSoundEngine => {
const engine = engineRef.current ?? new BomperatorSoundEngine();
engineRef.current = engine;
engine.setMusicVolume(settingsRef.current.musicVolume);
engine.setEffectsVolume(settingsRef.current.effectsVolume);
engine.setMuted(settingsRef.current.muted);
engine.unlock();
return engine;
}, []);
const toggleMuted = useCallback(() => {
const muted = !settingsRef.current.muted;
settingsRef.current = { ...settingsRef.current, muted };
setSettings((current) => ({ ...current, muted }));
ensureEngine();
}, [ensureEngine]);
const setMusicVolume = useCallback(
(volume: number) => {
const musicVolume = clampVolume(volume, DEFAULT_MUSIC_VOLUME);
settingsRef.current = { ...settingsRef.current, musicVolume };
setSettings((current) => ({ ...current, musicVolume }));
ensureEngine();
},
[ensureEngine],
);
const setEffectsVolume = useCallback(
(volume: number) => {
const effectsVolume = clampVolume(volume, DEFAULT_EFFECTS_VOLUME);
settingsRef.current = { ...settingsRef.current, effectsVolume };
setSettings((current) => ({ ...current, effectsVolume }));
ensureEngine();
},
[ensureEngine],
);
const playPlace = useCallback(() => {
ensureEngine().play("place");
}, [ensureEngine]);
useEffect(() => {
setSettings(readStored());
loadedRef.current = true;
}, []);
useEffect(() => {
if (loadedRef.current) window.localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
}, [settings]);
useEffect(() => () => {
engineRef.current?.dispose();
engineRef.current = null;
}, []);
useEffect(() => {
if (!match) {
lastEventIdRef.current = null;
prevPhaseRef.current = null;
return;
}
const engine = engineRef.current;
// First observation: adopt the current watermark without replaying history.
if (lastEventIdRef.current === null) {
lastEventIdRef.current = match.lastEventId;
} else if (engine) {
for (const event of match.events) {
if (event.id > lastEventIdRef.current) engine.play(event.type);
}
lastEventIdRef.current = Math.max(lastEventIdRef.current, match.lastEventId);
}
if (prevPhaseRef.current && prevPhaseRef.current !== "complete" && match.phase === "complete") {
engine?.play("round-win");
}
prevPhaseRef.current = match.phase;
}, [match]);
// Pick the background track from the live phase: calm in the waiting room and
// countdown, driving in battle, frantic under sudden death, silent once done or
// muted. A primitive, so the effect below only re-runs when it actually changes.
const phase = match?.phase ?? null;
const suddenDeath = match?.suddenDeath ?? false;
const desiredMusic: MusicPhase | null =
!match || settings.muted || settings.musicVolume <= 0 || phase === "complete"
? null
: phase === "lobby" || phase === "countdown"
? "calm"
: suddenDeath
? "sudden"
: "action";
const desiredMusicRef = useRef<MusicPhase | null>(desiredMusic);
desiredMusicRef.current = desiredMusic;
// Apply the chosen track whenever it changes. Only acts once an AudioContext
// exists (created on the first gesture) so we never fight browser autoplay rules.
useEffect(() => {
const engine = engineRef.current;
if (!engine) return;
if (desiredMusic) engine.startMusic(desiredMusic);
else engine.stopMusic();
}, [desiredMusic]);
// Browsers block audio until a user gesture. On the first pointer/key event,
// create and resume the context and start whatever track the match wants now.
useEffect(() => {
const onGesture = () => {
const engine = ensureEngine();
engine.unlock();
const target = desiredMusicRef.current;
if (target) engine.startMusic(target);
window.removeEventListener("pointerdown", onGesture);
window.removeEventListener("keydown", onGesture);
};
window.addEventListener("pointerdown", onGesture);
window.addEventListener("keydown", onGesture);
return () => {
window.removeEventListener("pointerdown", onGesture);
window.removeEventListener("keydown", onGesture);
};
}, [ensureEngine]);
return {
muted: settings.muted,
musicVolume: settings.musicVolume,
effectsVolume: settings.effectsVolume,
toggleMuted,
setMusicVolume,
setEffectsVolume,
playPlace,
};
}

View file

@ -6,6 +6,8 @@ import {
BLACKJACK_STATE_EVENT,
BLACKJACK_TABLES_EVENT,
BLACKJACK_TERMINATED_EVENT,
BOMP_STATE_EVENT,
BOMP_TERMINATED_EVENT,
GAME_EVENT_EVENT,
GAME_TICK_EVENT,
NOTIFICATION_EVENT,
@ -16,6 +18,8 @@ import {
type BlackjackStateDetail,
type BlackjackTablesDetail,
type BlackjackTerminatedDetail,
type BomperatorStateDetail,
type BomperatorTerminatedDetail,
type GameTickDetail,
type PokerStateDetail,
type PokerTablesDetail,
@ -123,6 +127,24 @@ export function GameTickRealtime() {
}
window.dispatchEvent(new CustomEvent(BLACKJACK_TERMINATED_EVENT, { detail }));
});
source.addEventListener("bomperator-state", (event) => {
let detail: BomperatorStateDetail = {};
try {
detail = JSON.parse(event.data ?? "{}");
} catch {
// ignore malformed payload
}
window.dispatchEvent(new CustomEvent(BOMP_STATE_EVENT, { detail }));
});
source.addEventListener("bomperator-terminated", (event) => {
let detail: BomperatorTerminatedDetail = {};
try {
detail = JSON.parse(event.data ?? "{}");
} catch {
// ignore malformed payload
}
window.dispatchEvent(new CustomEvent(BOMP_TERMINATED_EVENT, { detail }));
});
return () => {
if (refreshTimer) clearTimeout(refreshTimer);
source.close();

View file

@ -6,6 +6,7 @@ import type {
BlackjackTableSummary,
} from "@/app/(frontend)/minigames/blackjack/actions";
import type { PokerSnapshot, PokerTableSummary } from "@/app/(frontend)/minigames/poker/actions";
import type { BomperatorView } from "@/lib/minigames/bomperator/types";
export const GAME_TICK_EVENT = "ptf:game-tick";
export const PROFILE_UPDATE_EVENT = "ptf:profile-update";
@ -20,6 +21,8 @@ export const POKER_TERMINATED_EVENT = "ptf:poker-terminated";
export const BLACKJACK_STATE_EVENT = "ptf:blackjack-state";
export const BLACKJACK_TABLES_EVENT = "ptf:blackjack-tables";
export const BLACKJACK_TERMINATED_EVENT = "ptf:blackjack-terminated";
export const BOMP_STATE_EVENT = "ptf:bomperator-state";
export const BOMP_TERMINATED_EVENT = "ptf:bomperator-terminated";
export interface GameTickDetail {
processedAt?: string;
@ -60,6 +63,17 @@ export interface BlackjackTerminatedDetail {
reason?: string;
}
export interface BomperatorStateDetail {
matchId?: string;
snapshot?: BomperatorView;
}
export interface BomperatorTerminatedDetail {
matchId?: string;
reason?: string;
hostName?: string | null;
}
export function useGameTick(onTick?: () => void): number {
const [count, setCount] = useState(0);
const callbackRef = useRef(onTick);

View file

@ -10,6 +10,7 @@ Five XP-earning minigames under one parent: routes live at `/minigames/*` (moved
- **Flight Simulator**: `/minigames/flappy` (canvas game + leaderboard). **Minefield Clearance (EOD)**: `/minigames/eod`. **OPORD Recall**: `/minigames/opord` (`src/lib/minigames/opord-recall.ts`).
- **Call for Fire (artillery observer)**: `/minigames/call-for-fire`, game rules in `src/lib/minigames/call-for-fire.ts` (patrol/checkpoint/compound difficulties, compass bearing observer reports, ADD/DROP + RIGHT/LEFT corrections, scoring/accuracy/XP, injected rng, pure). Components: `src/components/frontend/minigames/call-for-fire/` (`CallForFireArena`, `FireMissionBoard`, `CallForFireLeaderboard`). Action `submitCallForFireResult` validates result bounds, updates profile stats, awards XP + chips, emits `minigame:call-for-fire`, and records the ledger entry (accuracy is distance-to-target on a win, null on a loss).
- **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 ~10 Hz tick loop**: `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 20/s) and poll `fetchBomperatorMatch` (~150ms); 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).
- Leaderboards match active players by user id (not display name) — see commit 72715c4 if leaderboard queries look wrong.
## Periods, achievements & the game registry

View file

@ -0,0 +1,121 @@
/**
* Tunables for Ordnance Disposal (internal key `bomperator`), a real-time
* multiplayer Bomberman-style charge-clearing drill.
*
* Pure and client-safe: no Payload or Node imports. Every value here is a
* flagged assumption the plan calls out as tunable; adjust freely and the engine
* unit tests will pin the resulting behavior.
*/
/* ------------------------------------------------------------------ timing */
/** Fixed simulation tick. ~10 Hz server-authoritative loop. */
export const TICK_MS = 100;
/** Ticks per second, derived from TICK_MS. */
export const TICKS_PER_SECOND = Math.round(1000 / TICK_MS);
/* -------------------------------------------------------------------- grid */
/** Classic depot grid: 15 wide by 13 tall. One cell is one lane. */
export const GRID_W = 15;
export const GRID_H = 13;
export const CELL_COUNT = GRID_W * GRID_H;
/** Fraction of passable, non-spawn cells that become destructible crates. */
export const CRATE_DENSITY = 0.4;
/* ------------------------------------------------------------------- bombs */
/** Fuse length in ticks (~2.5s at 10 Hz). */
export const BOMB_FUSE_TICKS = 25;
/** How long a flame cell lingers after an explosion (ticks). */
export const FLAME_LIFETIME_TICKS = 3;
/** Starting loadout every technician begins each round with. */
export const START_BOMBS = 1;
export const START_RANGE = 1;
/** Base movement speed in cells per second (interpolated between snapshots). */
export const BASE_SPEED_CELLS_PER_S = 7;
/** Speed boots add this many cells/s, up to the cap. */
export const SPEED_BOOST_CELLS_PER_S = 1;
export const MAX_SPEED_CELLS_PER_S = 8;
/** Range / bomb-slot caps so pickups cannot run away. */
export const MAX_RANGE = 7;
export const MAX_BOMBS = 6;
/* --------------------------------------------------------------- weighting */
/** Weighted pool for the power-up hidden under each crate. */
export const POWERUP_WEIGHTS: Record<"bomb" | "range" | "speed" | "kick", number> = {
bomb: 35,
range: 35,
speed: 20,
kick: 10,
};
/* ------------------------------------------------------------------ rounds */
/** Round timer before sudden death (seconds). */
export const ROUND_TIMER_S = 150;
export const ROUND_TIMER_TICKS = ROUND_TIMER_S * TICKS_PER_SECOND;
/** In sudden death, spawn a random-cell explosion every N ticks (~4s). */
export const SUDDEN_DEATH_INTERVAL_TICKS = 40;
/** Countdown between rounds (seconds). */
export const INTER_ROUND_COUNTDOWN_S = 3;
export const INTER_ROUND_COUNTDOWN_TICKS = INTER_ROUND_COUNTDOWN_S * TICKS_PER_SECOND;
/** Brief result hold at the end of a round before the next countdown. */
export const ROUND_END_HOLD_TICKS = 3 * TICKS_PER_SECOND;
/** Spawn protection so nobody dies the instant a round opens (ticks). */
export const SPAWN_INVULNERABLE_TICKS = 10;
/**
* Draw guard: if sudden death runs this many explosions without reducing the
* field to one technician, the round is called a draw rather than looping.
*/
export const MAX_SUDDEN_DEATH_EXPLOSIONS = 60;
/* --------------------------------------------------------------- lifecycle */
/** Seats and gating. */
export const MAX_SEATS = 8;
export const MIN_TO_START = 2;
/** Live matches: registry cap and idle expiry (mirrors the versus registry). */
export const BOMP_MAX_MATCHES = 20;
export const BOMP_MATCH_EXPIRY_MS = 5 * 60_000;
export const BOMP_SWEEP_INTERVAL_MS = 30_000;
/** A disconnected seat is held for reconnect this long before it is dropped. */
export const RECONNECT_WINDOW_MS = 60_000;
/** Default best-of target (first to N round-wins); lobby can override to 1/3/5. */
export const DEFAULT_ROUND_TARGET = 3;
export const ROUND_TARGET_OPTIONS = [1, 3, 5] as const;
/** Input rate limit per user at the action boundary (inputs per second). Sized
* above the ~12.5/s keepalive plus key/drop bursts so real play is never throttled. */
export const INPUT_RATE_LIMIT_PER_S = 40;
/* ------------------------------------------------------------------ awards */
/** XP payout on match completion. Mirrors the versus magnitudes. */
export const BOMP_XP_WIN = 40;
export const BOMP_XP_LOSS = 10;
export const BOMP_XP_PER_KILL = 5;
/* ------------------------------------------------------------------ spawns */
/**
* Eight spawn cells spread around the depot: four corners first (so a two- or
* four-player match gets opposite corners), then the mid-edge positions. Every
* coordinate is passable under the standard border + pillar layout.
*/
export const SPAWN_POINTS: readonly { readonly x: number; readonly y: number }[] = [
{ x: 1, y: 1 },
{ x: GRID_W - 2, y: GRID_H - 2 },
{ x: GRID_W - 2, y: 1 },
{ x: 1, y: GRID_H - 2 },
{ x: Math.floor(GRID_W / 2), y: 1 },
{ x: Math.floor(GRID_W / 2), y: GRID_H - 2 },
{ x: 1, y: Math.floor(GRID_H / 2) },
{ x: GRID_W - 2, y: Math.floor(GRID_H / 2) },
];

View file

@ -0,0 +1,858 @@
/**
* Pure rules for Ordnance Disposal (internal key `bomperator`). No I/O, no
* timers, no Payload: the server registry (./registry.ts) owns live match
* records and drives these functions from a fixed tick loop, and unit tests
* call them directly.
*
* Every mutator returns a NEW state built from local copies; the input state is
* never mutated. Randomness is injected through `state.rngState` / `gridSeed`,
* so a given seed reproduces the same grid and the same sudden-death draws.
*/
import {
BASE_SPEED_CELLS_PER_S,
BOMB_FUSE_TICKS,
CELL_COUNT,
CRATE_DENSITY,
FLAME_LIFETIME_TICKS,
GRID_H,
GRID_W,
INTER_ROUND_COUNTDOWN_TICKS,
MAX_BOMBS,
MAX_RANGE,
MAX_SPEED_CELLS_PER_S,
MAX_SUDDEN_DEATH_EXPLOSIONS,
POWERUP_WEIGHTS,
ROUND_END_HOLD_TICKS,
ROUND_TIMER_TICKS,
SPAWN_INVULNERABLE_TICKS,
SPAWN_POINTS,
SPEED_BOOST_CELLS_PER_S,
START_BOMBS,
START_RANGE,
SUDDEN_DEATH_INTERVAL_TICKS,
TICK_MS,
} from "./constants";
import type {
BomperatorEvent,
BomperatorState,
Bomb,
CellType,
Dir,
Drop,
Flame,
Player,
PowerUpKind,
} from "./types";
/* --------------------------------------------------------------------- rng */
/** Shallow-mutable view of a readonly interface, for per-tick working copies. */
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
/** mulberry32 step: returns a float in [0,1) and the next integer state. */
function rng(state: number): { value: number; next: number } {
const a = (state + 0x6d2b79f5) | 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
const value = ((t ^ (t >>> 14)) >>> 0) / 4294967296;
return { value, next: a };
}
/** Derive an independent seed for a round from the match seed + round index. */
export function deriveSeed(matchSeed: number, roundIndex: number): number {
let h = (matchSeed ^ 0x9e3779b9) >>> 0;
h = Math.imul(h ^ (roundIndex + 0x85ebca6b), 0xc2b2ae35);
h ^= h >>> 13;
return h >>> 0;
}
/* ------------------------------------------------------------------- grid */
export function idx(x: number, y: number): number {
return y * GRID_W + x;
}
export function inBounds(x: number, y: number): boolean {
return x >= 0 && y >= 0 && x < GRID_W && y < GRID_H;
}
function isSolidLayout(x: number, y: number): boolean {
if (x === 0 || y === 0 || x === GRID_W - 1 || y === GRID_H - 1) return true; // border
return x % 2 === 0 && y % 2 === 0; // interior pillars on even/even
}
/** Weighted power-up pick from a [0,1) draw. */
function pickPowerUp(value: number): PowerUpKind {
const order: PowerUpKind[] = ["bomb", "range", "speed", "kick"];
const total = order.reduce((sum, kind) => sum + POWERUP_WEIGHTS[kind], 0);
let acc = 0;
const roll = value * total;
for (const kind of order) {
acc += POWERUP_WEIGHTS[kind];
if (roll < acc) return kind;
}
return "kick";
}
/** Cells that must stay crate-free so every spawn has an escape corridor. */
function protectedSpawnCells(): Set<number> {
const set = new Set<number>();
const dirs: Array<[number, number]> = [
[0, 0],
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];
for (const spawn of SPAWN_POINTS) {
for (const [dx, dy] of dirs) {
const x = spawn.x + dx;
const y = spawn.y + dy;
if (inBounds(x, y) && !isSolidLayout(x, y)) set.add(idx(x, y));
}
}
return set;
}
/**
* Build the classic depot layout from a seed: solid border, pillar grid on even
* coordinates, seeded-random destructible crates on the remaining passable
* cells (spawn areas and their escape corridors kept clear), and one hidden
* power-up under each crate.
*/
export function generateGrid(seed: number): {
grid: CellType[];
hidden: (PowerUpKind | null)[];
} {
const grid: CellType[] = new Array(CELL_COUNT).fill("empty");
const hidden: (PowerUpKind | null)[] = new Array(CELL_COUNT).fill(null);
for (let y = 0; y < GRID_H; y += 1) {
for (let x = 0; x < GRID_W; x += 1) {
if (isSolidLayout(x, y)) grid[idx(x, y)] = "solid";
}
}
const protectedCells = protectedSpawnCells();
let rs = seed >>> 0;
for (let y = 0; y < GRID_H; y += 1) {
for (let x = 0; x < GRID_W; x += 1) {
const i = idx(x, y);
if (grid[i] !== "empty" || protectedCells.has(i)) continue;
const roll = rng(rs);
rs = roll.next;
if (roll.value < CRATE_DENSITY) {
grid[i] = "crate";
const pick = rng(rs);
rs = pick.next;
hidden[i] = pickPowerUp(pick.value);
}
}
}
return { grid, hidden };
}
/* --------------------------------------------------------------- lifecycle */
function freshPlayer(seat: number, userId: number, name: string): Player {
const spawn = SPAWN_POINTS[seat % SPAWN_POINTS.length];
return {
seat,
userId,
name,
x: spawn.x,
y: spawn.y,
dir: "down",
alive: true,
invulnerableTicks: 0,
bombsMax: START_BOMBS,
range: START_RANGE,
speed: BASE_SPEED_CELLS_PER_S,
kick: false,
kills: 0,
deaths: 0,
roundsWon: 0,
inputDir: null,
wantDrop: false,
connected: true,
disconnectedAt: null,
};
}
export interface SeatDescriptor {
readonly seat: number;
readonly userId: number;
readonly name: string;
}
/** A fresh match in the lobby (no grid yet; the first startRound builds one). */
export function createMatchState(
seats: readonly SeatDescriptor[],
roundTarget: number,
matchSeed: number,
): BomperatorState {
const players = seats.map((s) => freshPlayer(s.seat, s.userId, s.name));
return {
phase: "lobby",
roundTarget,
roundIndex: 0,
gridSeed: matchSeed >>> 0,
tickCount: 0,
rngState: matchSeed >>> 0,
grid: new Array(CELL_COUNT).fill("empty"),
hidden: new Array(CELL_COUNT).fill(null),
players,
bombs: [],
flames: [],
drops: [],
countdownTicks: 0,
roundTimerTicks: ROUND_TIMER_TICKS,
roundEndHoldTicks: 0,
suddenDeath: false,
suddenDeathTicks: 0,
suddenDeathExplosions: 0,
roundWinnerSeat: null,
matchWinnerSeat: null,
endReason: null,
events: [],
lastEventId: 0,
};
}
/**
* Begin a round: regenerate the grid from a fresh seed, reset every seated
* player to their spawn with base loadout, and enter the countdown. Match-scoped
* counters (kills, roundsWon) are preserved.
*/
export function startRound(state: BomperatorState, seedOverride?: number): BomperatorState {
const seed = (seedOverride ?? deriveSeed(state.gridSeed, state.roundIndex)) >>> 0;
const { grid, hidden } = generateGrid(seed);
const players = state.players.map((p) => {
const spawn = SPAWN_POINTS[p.seat % SPAWN_POINTS.length];
return {
...p,
x: spawn.x,
y: spawn.y,
dir: "down" as Dir,
alive: true,
invulnerableTicks: SPAWN_INVULNERABLE_TICKS,
bombsMax: START_BOMBS,
range: START_RANGE,
speed: BASE_SPEED_CELLS_PER_S,
kick: false,
inputDir: null,
wantDrop: false,
};
});
return {
...state,
phase: "countdown",
gridSeed: seed,
rngState: seed >>> 0,
grid,
hidden,
players,
bombs: [],
flames: [],
drops: [],
countdownTicks: INTER_ROUND_COUNTDOWN_TICKS,
roundTimerTicks: ROUND_TIMER_TICKS,
roundEndHoldTicks: 0,
suddenDeath: false,
suddenDeathTicks: 0,
suddenDeathExplosions: 0,
roundWinnerSeat: null,
};
}
/* ------------------------------------------------------------------ inputs */
export interface BomperatorInput {
readonly dir?: Dir | null;
readonly drop?: boolean;
}
/**
* Record a seat's latest intent. Movement direction is level-triggered (the last
* value wins and persists until changed); `drop` is edge-triggered and sticky so
* a press between ticks is never lost, consumed by the next tick.
*/
export function applyInput(
state: BomperatorState,
seat: number,
input: BomperatorInput,
): BomperatorState {
if (state.phase !== "battle") return state;
const player = state.players[seat];
if (!player || !player.alive) return state;
const players = [...state.players];
players[seat] = {
...player,
inputDir: input.dir ?? null,
wantDrop: player.wantDrop || input.drop === true,
};
return { ...state, players };
}
/* -------------------------------------------------------------- presence */
/** Mark a seat connected/disconnected (engine keeps them frozen while held). */
export function setConnected(state: BomperatorState, seat: number, connected: boolean): BomperatorState {
const player = state.players[seat];
if (!player || player.connected === connected) return state;
const players = [...state.players];
players[seat] = { ...player, connected };
return { ...state, players };
}
/** Eliminate a seat from the current round (no-show or dropped connection). */
export function eliminateSeat(state: BomperatorState, seat: number): BomperatorState {
const player = state.players[seat];
if (!player || !player.alive) return state;
const players = [...state.players];
players[seat] = { ...player, alive: false, deaths: player.deaths + 1, inputDir: null, wantDrop: false };
return withEvent({ ...state, players }, { type: "death", seat, killerSeat: null });
}
/* ----------------------------------------------------------------- helpers */
function bombsActiveFor(bombs: readonly Bomb[], seat: number): number {
let n = 0;
for (const b of bombs) if (b.ownerSeat === seat) n += 1;
return n;
}
function bombAt(bombs: readonly Bomb[], x: number, y: number): Bomb | undefined {
return bombs.find((b) => b.x === x && b.y === y);
}
function terrainIsOpen(grid: readonly CellType[], x: number, y: number): boolean {
return inBounds(x, y) && grid[idx(x, y)] === "empty";
}
/** A cell a technician may stand on: open terrain and no charge sitting there. */
function canStand(state: BomperatorState, bombs: readonly Bomb[], x: number, y: number): boolean {
return terrainIsOpen(state.grid, x, y) && !bombAt(bombs, x, y);
}
const DIR_VEC: Record<Dir, [number, number]> = {
up: [0, -1],
down: [0, 1],
left: [-1, 0],
right: [1, 0],
};
/** True when a position sits exactly on a cell center (within float epsilon). */
function isCellCentered(x: number, y: number): boolean {
const EPS = 1e-6;
return Math.abs(x - Math.round(x)) < EPS && Math.abs(y - Math.round(y)) < EPS;
}
/* --------------------------------------------------------------- movement */
interface MoveResult {
readonly x: number;
readonly y: number;
readonly pushedBombId?: string;
readonly pushedTo?: { x: number; y: number };
}
/**
* Advance one technician along its input direction for a single tick. Movement is
* grid-locked: a technician only leaves a cell center toward an adjacent open
* cell, and finishes lining up on the perpendicular axis before turning. A
* kick-capable technician shoves an adjacent charge one cell forward instead of
* being blocked by it.
*/
function advancePlayer(
state: BomperatorState,
player: Player,
bombs: readonly Bomb[],
step: number,
): MoveResult {
const dir = player.inputDir;
if (!dir) return { x: player.x, y: player.y };
const [dx, dy] = DIR_VEC[dir];
const EPS = 1e-6;
let { x, y } = player;
if (dx !== 0) {
// Finish aligning vertically before moving horizontally.
if (Math.abs(y - Math.round(y)) > EPS) {
const ty = Math.round(y);
y += Math.sign(ty - y) * Math.min(Math.abs(ty - y), step);
if (Math.abs(ty - y) < 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 + EPS) : Math.ceil(x - EPS);
const bomb = bombAt(bombs, entering, cy);
if (bomb) {
if (player.kick) {
const bx = entering + dx;
if (terrainIsOpen(state.grid, bx, cy) && !bombAt(bombs, bx, cy)) {
return { x: approach(x, entering, step), y, pushedBombId: bomb.id, pushedTo: { x: bx, y: cy } };
}
}
return { x: home, y };
}
if (!canStand(state, bombs, entering, cy)) return { x: home, y };
x = approach(x, entering, step);
} else {
// Finish aligning horizontally before moving vertically.
if (Math.abs(x - Math.round(x)) > EPS) {
const tX = Math.round(x);
x += Math.sign(tX - x) * Math.min(Math.abs(tX - x), step);
if (Math.abs(tX - x) < 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 + EPS) : Math.ceil(y - EPS);
const bomb = bombAt(bombs, cx, entering);
if (bomb) {
if (player.kick) {
const by = entering + dy;
if (terrainIsOpen(state.grid, cx, by) && !bombAt(bombs, cx, by)) {
return { x, y: approach(y, entering, step), pushedBombId: bomb.id, pushedTo: { x: cx, y: by } };
}
}
return { x, y: home };
}
if (!canStand(state, bombs, cx, entering)) return { x, y: home };
y = approach(y, entering, step);
}
return { x, y };
}
function approach(current: number, target: number, step: number): number {
const delta = target - current;
if (Math.abs(delta) <= step) return target;
return current + Math.sign(delta) * step;
}
/* -------------------------------------------------------------- explosions */
interface SimContext {
grid: CellType[];
hidden: (PowerUpKind | null)[];
bombs: Bomb[];
flames: Flame[];
drops: Drop[];
events: BomperatorEvent[];
}
/**
* Spread a cross flame from a detonation. Each arm runs until it hits a solid
* wall; the first crate in an arm is destroyed (revealing its power-up) and stops
* that arm; another charge is either shoved along (kickable) or chain-detonated.
*/
function spreadExplosion(
ctx: SimContext,
centerX: number,
centerY: number,
range: number,
sourceSeat: number | null,
queue: Bomb[],
): void {
const addFlame = (x: number, y: number) => {
if (!ctx.flames.some((f) => f.x === x && f.y === y)) {
ctx.flames.push({ x, y, ticksLeft: FLAME_LIFETIME_TICKS, sourceSeat });
}
};
addFlame(centerX, centerY);
for (const [dx, dy] of Object.values(DIR_VEC)) {
let x = centerX + dx;
let y = centerY + dy;
for (let step = 1; step <= range; step += 1) {
if (!inBounds(x, y)) break;
const cell = ctx.grid[idx(x, y)];
if (cell === "solid") break;
if (cell === "crate") {
addFlame(x, y);
destroyCrate(ctx, x, y);
break;
}
const other = bombAt(ctx.bombs, x, y);
if (other) {
const remaining = range - step;
const pushed = tryKickBomb(ctx, other, dx, dy, remaining);
if (pushed) {
// Flame fills the vacated trail up to (not including) the charge's rest.
for (const cell of pushed) addFlame(cell.x, cell.y);
} else {
addFlame(x, y);
queue.push(other);
}
break;
}
addFlame(x, y);
x += dx;
y += dy;
}
}
}
/** Destroy a crate at a cell and expose its hidden power-up as a drop. */
function destroyCrate(ctx: SimContext, x: number, y: number): void {
const i = idx(x, y);
if (ctx.grid[i] !== "crate") return;
ctx.grid[i] = "empty";
const kind = ctx.hidden[i];
ctx.hidden[i] = null;
if (kind) ctx.drops.push({ x, y, kind });
ctx.events.push({ type: "crateBroken", x, y });
}
/**
* Kick-push rule: shove a kickable charge along the flame direction by up to
* `remaining` cells, stopping before the first blocked cell. Returns the vacated
* trail (cells the flame may fill) on success, or null when it cannot move at all
* (the caller then chain-detonates the charge instead).
*/
function tryKickBomb(
ctx: SimContext,
bomb: Bomb,
dx: number,
dy: number,
remaining: number,
): { x: number; y: number }[] | null {
if (!bomb.kickable || remaining < 1) return null;
let bx = bomb.x;
let by = bomb.y;
const vacated: { x: number; y: number }[] = [];
for (let i = 0; i < remaining; i += 1) {
const nx = bx + dx;
const ny = by + dy;
if (!terrainIsOpen(ctx.grid, nx, ny) || bombAt(ctx.bombs, nx, ny)) break;
vacated.push({ x: bx, y: by });
bx = nx;
by = ny;
}
if (vacated.length === 0) return null;
ctx.bombs = ctx.bombs.map((b) => (b.id === bomb.id ? { ...b, x: bx, y: by } : b));
return vacated;
}
/** Detonate a set of charges (fuses that expired), resolving chains. */
function detonateAll(
ctx: SimContext,
initial: readonly Bomb[],
): void {
const queue: Bomb[] = [...initial];
const detonatedIds = new Set<string>();
while (queue.length > 0) {
const bomb = queue.shift()!;
if (detonatedIds.has(bomb.id)) continue;
// Remove it from the live set before spreading so it is not re-hit.
ctx.bombs = ctx.bombs.filter((b) => b.id !== bomb.id);
detonatedIds.add(bomb.id);
ctx.events.push({ type: "explosion", x: bomb.x, y: bomb.y });
spreadExplosion(ctx, bomb.x, bomb.y, bomb.range, bomb.ownerSeat, queue);
}
}
/* -------------------------------------------------------------------- tick */
const EVENT_BUFFER = 48;
function withEvent(state: BomperatorState, event: BomperatorEvent): BomperatorState {
const id = state.lastEventId + 1;
const events = [...state.events, { ...event, id }].slice(-EVENT_BUFFER);
return { ...state, events, lastEventId: id };
}
/**
* Advance the simulation by one fixed tick. Handles phase transitions
* (countdown -> battle -> roundEnd -> next round / complete), movement, charge
* placement, fuses and chain detonations, flame decay, pickups, elimination and
* round-end checks, the round timer, and sudden-death spawning.
*/
export function tick(state: BomperatorState): BomperatorState {
switch (state.phase) {
case "countdown":
return tickCountdown(state);
case "battle":
return tickBattle(state);
case "roundEnd":
return tickRoundEnd(state);
default:
// lobby / complete are inert to ticking.
return { ...state, tickCount: state.tickCount + 1 };
}
}
function tickCountdown(state: BomperatorState): BomperatorState {
const countdownTicks = state.countdownTicks - 1;
if (countdownTicks > 0) {
return { ...state, tickCount: state.tickCount + 1, countdownTicks };
}
return { ...state, tickCount: state.tickCount + 1, countdownTicks: 0, phase: "battle" };
}
function tickRoundEnd(state: BomperatorState): BomperatorState {
const hold = state.roundEndHoldTicks - 1;
if (hold > 0) {
return { ...state, tickCount: state.tickCount + 1, roundEndHoldTicks: hold };
}
// Advance to the next round.
return startRound({ ...state, roundIndex: state.roundIndex + 1 });
}
function tickBattle(state: BomperatorState): BomperatorState {
let rngState = state.rngState;
const ctx: SimContext = {
grid: [...state.grid],
hidden: [...state.hidden],
bombs: [...state.bombs],
flames: [...state.flames],
drops: [...state.drops],
events: [],
};
// 1. Movement (with kick pushes applied to ctx.bombs).
const players: Mutable<Player>[] = state.players.map((p) => ({ ...p }));
for (let seat = 0; seat < players.length; seat += 1) {
const p = players[seat];
if (!p.alive) continue;
// Slip feel: with no active input, keep traveling in the last direction until
// the technician reaches the next cell center, then rest exactly on it. This
// reuses advancePlayer's collision rules, so a slip can never enter a wall or
// charge; if the cell ahead is blocked the technician settles back onto the one
// they are leaving. Resting on a whole cell also makes bomb/flame rounding exact.
const slipping = p.inputDir === null && !isCellCentered(p.x, p.y);
const dir = p.inputDir ?? (slipping ? p.dir : null);
if (!dir) continue;
const cellsPerTick = (p.speed * TICK_MS) / 1000;
const res = advancePlayer(state, { ...p, inputDir: dir }, ctx.bombs, cellsPerTick);
p.x = res.x;
p.y = res.y;
if (p.inputDir) p.dir = p.inputDir;
if (res.pushedBombId && res.pushedTo) {
ctx.bombs = ctx.bombs.map((b) =>
b.id === res.pushedBombId ? { ...b, x: res.pushedTo!.x, y: res.pushedTo!.y } : b,
);
}
}
// 2. Charge placement.
for (let seat = 0; seat < players.length; seat += 1) {
const p = players[seat];
if (!p.alive || !p.wantDrop) continue;
p.wantDrop = false;
const cx = Math.round(p.x);
const cy = Math.round(p.y);
if (!terrainIsOpen(ctx.grid, cx, cy)) continue;
if (bombAt(ctx.bombs, cx, cy)) continue;
if (bombsActiveFor(ctx.bombs, seat) >= p.bombsMax) continue;
ctx.bombs.push({
id: `${state.tickCount}:${seat}:${ctx.bombs.length}`,
ownerSeat: seat,
x: cx,
y: cy,
fuseTicks: BOMB_FUSE_TICKS,
range: p.range,
kickable: p.kick,
});
}
// 3. Advance fuses and detonate whatever reached zero (with chains).
const expired: Bomb[] = [];
ctx.bombs = ctx.bombs.map((b) => {
const fuseTicks = b.fuseTicks - 1;
if (fuseTicks <= 0) {
expired.push({ ...b, fuseTicks: 0 });
return { ...b, fuseTicks: 0 };
}
return { ...b, fuseTicks };
});
if (expired.length > 0) detonateAll(ctx, expired);
// 4. Flame overlap kills (covers both fresh flames and lingering ones).
for (let seat = 0; seat < players.length; seat += 1) {
const p = players[seat];
if (!p.alive || p.invulnerableTicks > 0) continue;
const cx = Math.round(p.x);
const cy = Math.round(p.y);
const hit = ctx.flames.find((f) => f.x === cx && f.y === cy);
if (hit) {
p.alive = false;
p.deaths += 1;
p.inputDir = null;
p.wantDrop = false;
const killerSeat = hit.sourceSeat !== null && hit.sourceSeat !== seat ? hit.sourceSeat : null;
if (killerSeat !== null && players[killerSeat]) players[killerSeat].kills += 1;
ctx.events.push({ type: "death", seat, killerSeat });
}
}
// 5. Pickups: a living technician entering an exposed drop collects it.
for (let seat = 0; seat < players.length; seat += 1) {
const p = players[seat];
if (!p.alive) continue;
const cx = Math.round(p.x);
const cy = Math.round(p.y);
const di = ctx.drops.findIndex((d) => d.x === cx && d.y === cy);
if (di >= 0) {
const drop = ctx.drops[di];
ctx.drops.splice(di, 1);
applyPowerUp(p, drop.kind);
ctx.events.push({ type: "pickup", seat, kind: drop.kind });
}
}
// 6. Flame decay + spawn protection decay.
ctx.flames = ctx.flames
.map((f) => ({ ...f, ticksLeft: f.ticksLeft - 1 }))
.filter((f) => f.ticksLeft > 0);
for (const p of players) {
if (p.invulnerableTicks > 0) p.invulnerableTicks -= 1;
}
// 7. Round timer / sudden death.
let suddenDeath = state.suddenDeath;
let suddenDeathTicks = state.suddenDeathTicks;
let suddenDeathExplosions = state.suddenDeathExplosions;
const aliveSeats = players.filter((p) => p.alive).map((p) => p.seat);
if (aliveSeats.length > 1) {
if (!suddenDeath) {
const roundTimerTicks = state.roundTimerTicks - 1;
if (roundTimerTicks <= 0) {
suddenDeath = true;
suddenDeathTicks = SUDDEN_DEATH_INTERVAL_TICKS;
ctx.events.push({ type: "suddenDeath" });
} else {
state = { ...state, roundTimerTicks };
}
}
if (suddenDeath) {
suddenDeathTicks -= 1;
if (suddenDeathTicks <= 0 && suddenDeathExplosions < MAX_SUDDEN_DEATH_EXPLOSIONS) {
const draw = rng(rngState);
rngState = draw.next;
spawnSuddenDeath(ctx, draw.value);
suddenDeathExplosions += 1;
suddenDeathTicks = SUDDEN_DEATH_INTERVAL_TICKS;
// Re-check kills from the new flames.
for (let seat = 0; seat < players.length; seat += 1) {
const p = players[seat];
if (!p.alive || p.invulnerableTicks > 0) continue;
const cx = Math.round(p.x);
const cy = Math.round(p.y);
if (ctx.flames.some((f) => f.x === cx && f.y === cy)) {
p.alive = false;
p.deaths += 1;
p.inputDir = null;
ctx.events.push({ type: "death", seat, killerSeat: null });
}
}
}
}
}
// 8. Round-end resolution.
const survivors = players.filter((p) => p.alive);
let next: BomperatorState = {
...state,
tickCount: state.tickCount + 1,
rngState,
grid: ctx.grid,
hidden: ctx.hidden,
bombs: ctx.bombs,
flames: ctx.flames,
drops: ctx.drops,
players,
suddenDeath,
suddenDeathTicks,
suddenDeathExplosions,
};
if (survivors.length <= 1) {
next = resolveRoundEnd(next, survivors[0]?.seat ?? null);
} else if (suddenDeath && suddenDeathExplosions >= MAX_SUDDEN_DEATH_EXPLOSIONS) {
// Draw guard: sudden death spent its whole explosion budget without reducing
// the field to one technician, so call the round a draw rather than loop.
next = resolveRoundEnd(next, null);
}
// Fold this tick's events into the rolling buffer.
for (const ev of ctx.events) next = withEvent(next, ev);
return next;
}
function applyPowerUp(player: Mutable<Player>, kind: PowerUpKind): void {
switch (kind) {
case "bomb":
player.bombsMax = Math.min(MAX_BOMBS, player.bombsMax + 1);
break;
case "range":
player.range = Math.min(MAX_RANGE, player.range + 1);
break;
case "speed":
player.speed = Math.min(MAX_SPEED_CELLS_PER_S, player.speed + SPEED_BOOST_CELLS_PER_S);
break;
case "kick":
player.kick = true;
break;
}
}
/** Pick a random open cell and detonate a small charge there. */
function spawnSuddenDeath(ctx: SimContext, value: number): void {
const openCells: Array<{ x: number; y: number }> = [];
for (let y = 0; y < GRID_H; y += 1) {
for (let x = 0; x < GRID_W; x += 1) {
if (ctx.grid[idx(x, y)] === "empty" && !bombAt(ctx.bombs, x, y)) {
openCells.push({ x, y });
}
}
}
if (openCells.length === 0) return;
const pick = openCells[Math.floor(value * openCells.length) % openCells.length];
const queue: Bomb[] = [];
spreadExplosion(
ctx,
pick.x,
pick.y,
1,
null,
queue,
);
// Any charges caught by the sudden-death blast go off too.
detonateAll(ctx, queue);
ctx.events.push({ type: "explosion", x: pick.x, y: pick.y });
}
/** Award a round and either continue to the next or complete the match. */
function resolveRoundEnd(state: BomperatorState, winnerSeat: number | null): BomperatorState {
let players = state.players;
let matchWinnerSeat: number | null = null;
if (winnerSeat !== null) {
players = players.map((p) => (p.seat === winnerSeat ? { ...p, roundsWon: p.roundsWon + 1 } : p));
const champ = players.find((p) => p.seat === winnerSeat);
if (champ && champ.roundsWon >= state.roundTarget) matchWinnerSeat = winnerSeat;
}
let next: BomperatorState = {
...state,
players,
roundWinnerSeat: winnerSeat,
bombs: [],
flames: [],
};
next = withEvent(next, { type: "roundEnd", roundIndex: state.roundIndex, winnerSeat });
if (matchWinnerSeat !== null) {
return { ...next, phase: "complete", matchWinnerSeat, endReason: "rounds" };
}
return { ...next, phase: "roundEnd", roundEndHoldTicks: ROUND_END_HOLD_TICKS };
}
/**
* End the match early (used by the registry when it dissolves below two seated
* players). No round is awarded.
*/
export function dissolveMatch(state: BomperatorState): BomperatorState {
return { ...state, phase: "complete", endReason: "dissolved", matchWinnerSeat: null };
}

View file

@ -0,0 +1,10 @@
/**
* Public API of the pure Ordnance Disposal engine. Everything exported here is
* client-safe: no Payload, Next.js, process, or database imports, and no
* module-level mutable state (that lives in ./registry.ts).
*/
export * from "./constants";
export * from "./types";
export * from "./engine";
export * from "./views";

View file

@ -0,0 +1,525 @@
/**
* Server-side match registry for Ordnance Disposal (internal key `bomperator`).
*
* Holds live match records in a module-level Map anchored on `globalThis` (same
* pattern as src/lib/minigames/blackjack/tables.ts), so Next.js dev module
* duplication does not fork the store. SINGLE-INSTANCE ONLY: match state lives
* in process memory, so this will not work across multiple server instances,
* and a server restart or redeploy ends any live match.
*
* The pure engine (./engine, ./views) never touches timers or I/O. This wrapper
* owns the fixed ~10 Hz tick loop, lobby membership, the disconnect/reconnect
* window, completion rewards, and the idle-expiry sweep. Clients POST inputs and
* poll snapshots; the in-memory SSE bus is used only for the profile-update nudge
* after awards (it is unreliable across dev module copies, same as blackjack).
*/
import { getPayload } from "payload";
import type { Payload } from "payload";
import { generateTableName } from "@/lib/minigames/tableNames";
import {
BOMP_MATCH_EXPIRY_MS,
BOMP_MAX_MATCHES,
BOMP_SWEEP_INTERVAL_MS,
DEFAULT_ROUND_TARGET,
INPUT_RATE_LIMIT_PER_S,
MAX_SEATS,
MIN_TO_START,
RECONNECT_WINDOW_MS,
ROUND_TARGET_OPTIONS,
TICK_MS,
} from "./constants";
import {
applyInput,
createMatchState,
dissolveMatch,
eliminateSeat,
startRound,
tick,
type BomperatorInput,
} from "./engine";
import { awardBomperatorResult, type BomperatorMatchResult } from "./stats";
import type { BomperatorMatchSummary, BomperatorState, BomperatorView } from "./types";
import { buildBomperatorView } from "./views";
import { broadcastToUser } from "@/lib/realtime/bus";
interface RosterEntry {
readonly userId: number;
readonly name: string;
}
interface BomperatorMatchRecord {
id: string;
name: string | null;
version: number;
hostUserId: number;
roster: RosterEntry[];
/** Seats whose occupant left permanently (window expired or lobby leave). */
leftSeats: Set<number>;
roundTarget: number;
seed: number;
state: BomperatorState;
awarded: boolean;
tickTimer: ReturnType<typeof setInterval> | null;
createdAt: string;
lastActivityAt: number;
/** Per-seat input rate limiting: rolling one-second window. */
inputWindow: Map<number, { count: number; windowStart: number }>;
/** userId -> last time they polled/watched, so we can push snapshots to
* seated players AND active spectators over the SSE bus. */
viewers: Map<number, number>;
}
type MatchesStore = Map<string, BomperatorMatchRecord>;
interface GlobalRegistry {
__bomperatorMatches?: MatchesStore;
}
const globalRegistry = globalThis as typeof globalThis & GlobalRegistry;
const matches: MatchesStore = (globalRegistry.__bomperatorMatches ??= new Map());
/* --------------------------------------------------------------- helpers */
function seatOf(record: BomperatorMatchRecord, userId: number): number | null {
const index = record.roster.findIndex((entry) => entry.userId === userId);
return index === -1 ? null : index;
}
/** Seats still in the match (roster minus those who left permanently). */
function activeSeatCount(record: BomperatorMatchRecord): number {
return record.roster.length - record.leftSeats.size;
}
function rosterDescriptors(record: BomperatorMatchRecord) {
return record.roster.map((entry, seat) => ({ seat, userId: entry.userId, name: entry.name }));
}
async function getPayloadOrNull(): Promise<Payload | null> {
try {
const config = (await import("@payload-config")).default;
return await getPayload({ config });
} catch {
return null;
}
}
function buildViewFor(record: BomperatorMatchRecord, userId: number | null): BomperatorView {
const yourSeat = userId === null ? null : seatOf(record, userId);
return buildBomperatorView(record.state, {
matchId: record.id,
name: record.name,
version: record.version,
yourSeat,
});
}
/**
* Push a fresh per-user snapshot to every seated technician and active spectator
* over the SSE bus. This is the low-latency path; the client keeps a slow guarded
* poll as a correctness fallback (the bus is single-instance and can drop on dev
* module reloads). Recipients are deduped; stale spectators are pruned.
*/
function pushSnapshots(record: BomperatorMatchRecord): void {
const now = Date.now();
const recipients = new Set<number>();
for (const entry of record.roster) recipients.add(entry.userId);
for (const [userId, seen] of record.viewers) {
if (now - seen > 30_000) record.viewers.delete(userId);
else recipients.add(userId);
}
for (const userId of recipients) {
broadcastToUser("bomperator-state", userId, {
matchId: record.id,
snapshot: buildViewFor(record, userId),
});
}
}
/** Rebuild the inert lobby state after a membership change (contiguous seats). */
function rebuildLobbyState(record: BomperatorMatchRecord): void {
record.state = createMatchState(rosterDescriptors(record), record.roundTarget, record.seed);
}
function listSummaries(viewerId?: number): BomperatorMatchSummary[] {
return [...matches.values()].map((record) => ({
matchId: record.id,
name: record.name,
hostName: record.roster[0]?.name ?? "Unknown",
seatedCount: record.roster.length,
maxSeats: MAX_SEATS,
phase: record.roster.length < MIN_TO_START && record.state.phase === "lobby" ? "waiting" : record.state.phase,
roundTarget: record.roundTarget,
createdAt: record.createdAt,
joined: viewerId !== undefined && seatOf(record, viewerId) !== null,
}));
}
/* ----------------------------------------------------------------- awards */
function matchResults(state: BomperatorState): BomperatorMatchResult[] {
return state.players.map((player) => ({
userId: player.userId,
won: state.matchWinnerSeat !== null && state.players[state.matchWinnerSeat]?.userId === player.userId,
kills: player.kills,
roundsWon: player.roundsWon,
}));
}
/** Fire-and-forget reward for a completed match; idempotent per record. */
function awardCompleted(record: BomperatorMatchRecord): void {
if (record.awarded || record.state.phase !== "complete") return;
record.awarded = true;
const results = matchResults(record.state);
if (results.length === 0) return;
void (async () => {
const payload = await getPayloadOrNull();
if (!payload) return;
await awardBomperatorResult(payload, record.id, results);
})();
}
/* -------------------------------------------------------------- tick loop */
/**
* When false, `startTickLoop` does not spawn a wall-clock interval. Integration
* tests disable this and drive the sim deterministically via `advanceForTests`.
*/
let autoTickEnabled = true;
function startTickLoop(record: BomperatorMatchRecord): void {
if (!autoTickEnabled || record.tickTimer) return;
record.tickTimer = setInterval(() => step(record), TICK_MS);
record.tickTimer.unref?.();
}
function stopTickLoop(record: BomperatorMatchRecord): void {
if (record.tickTimer) clearInterval(record.tickTimer);
record.tickTimer = null;
}
/** Patch a seat's presence flags without disturbing engine rules. */
function withPresence(
state: BomperatorState,
seat: number,
connected: boolean,
disconnectedAt: number | null,
): BomperatorState {
const players = [...state.players];
if (!players[seat]) return state;
players[seat] = { ...players[seat], connected, disconnectedAt };
return { ...state, players };
}
/** One simulation step: expire disconnects, advance the engine, resolve ends. */
function step(record: BomperatorMatchRecord, now: number = Date.now()): void {
let state = record.state;
// Expire seats whose reconnect window has elapsed: eliminate + mark left.
for (let seat = 0; seat < record.roster.length; seat += 1) {
if (record.leftSeats.has(seat)) continue;
const player = state.players[seat];
if (player && !player.connected && player.disconnectedAt !== null) {
if (now - player.disconnectedAt > RECONNECT_WINDOW_MS) {
state = eliminateSeat(state, seat);
record.leftSeats.add(seat);
}
}
}
const prevRound = state.roundIndex;
state = tick(state);
record.version += 1;
// A technician still disconnected when a fresh round opens has left the match.
if (state.roundIndex > prevRound) {
for (let seat = 0; seat < record.roster.length; seat += 1) {
if (record.leftSeats.has(seat)) continue;
const player = state.players[seat];
if (player && !player.connected) {
state = eliminateSeat(state, seat);
record.leftSeats.add(seat);
}
}
}
// Dissolve once fewer than two technicians remain in the match.
if (activeSeatCount(record) < MIN_TO_START && state.phase !== "complete") {
state = dissolveMatch(state);
}
record.state = state;
// Push the fresh snapshot to seated players + spectators (low-latency path).
pushSnapshots(record);
if (state.phase === "complete") {
stopTickLoop(record);
awardCompleted(record);
}
}
/* ------------------------------------------------------------------ public */
export function createMatch(
userId: number,
displayName: string,
roundTarget: number = DEFAULT_ROUND_TARGET,
): string {
if (matches.size >= BOMP_MAX_MATCHES) {
throw new Error("The maximum number of live matches exists. Try again later.");
}
for (const existing of matches.values()) {
// A finished match never blocks starting a new one (it clears on its own).
if (seatOf(existing, userId) !== null && existing.state.phase !== "complete") {
throw new Error("You are already in a match. Leave it first.");
}
}
const target = (ROUND_TARGET_OPTIONS as readonly number[]).includes(roundTarget)
? roundTarget
: DEFAULT_ROUND_TARGET;
const seed = (Date.now() ^ Math.floor(Math.random() * 0xffffffff)) >>> 0;
const record: BomperatorMatchRecord = {
id: crypto.randomUUID(),
name: generateTableName(),
version: 1,
hostUserId: userId,
roster: [{ userId, name: displayName }],
leftSeats: new Set(),
roundTarget: target,
seed,
state: createMatchState([{ seat: 0, userId, name: displayName }], target, seed),
awarded: false,
tickTimer: null,
createdAt: new Date().toISOString(),
lastActivityAt: Date.now(),
inputWindow: new Map(),
viewers: new Map(),
};
matches.set(record.id, record);
return record.id;
}
export function listMatchSummaries(viewerId?: number): BomperatorMatchSummary[] {
return listSummaries(viewerId);
}
export function joinMatch(matchId: string, userId: number, displayName: string): BomperatorView {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
const existing = seatOf(record, userId);
if (existing !== null) {
// Rejoin: restore a held seat within the reconnect window.
if (!record.state.players[existing]?.connected) {
record.state = withPresence(record.state, existing, true, null);
record.version += 1;
}
record.lastActivityAt = Date.now();
record.viewers.set(userId, Date.now());
pushSnapshots(record);
return buildViewFor(record, userId);
}
for (const other of matches.values()) {
if (
other.id !== record.id &&
seatOf(other, userId) !== null &&
other.state.phase !== "complete"
) {
throw new Error("You are already in another match. Leave it first.");
}
}
if (record.roster.length >= MAX_SEATS) throw new Error("This match is full.");
if (record.state.phase !== "lobby") throw new Error("This match has already started.");
record.roster.push({ userId, name: displayName });
rebuildLobbyState(record);
record.lastActivityAt = Date.now();
record.version += 1;
record.viewers.set(userId, Date.now());
pushSnapshots(record);
return buildViewFor(record, userId);
}
/** Snapshot for a poller. Non-seated users get a read-only spectator view. */
export function getSnapshotFor(matchId: string, userId: number): BomperatorView {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
record.lastActivityAt = Date.now();
// Register as a viewer so subsequent ticks push snapshots to us too (players
// are always recipients; this is how spectators opt in).
record.viewers.set(userId, Date.now());
return buildViewFor(record, userId);
}
export function startMatch(matchId: string, userId: number): BomperatorView {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
if (seatOf(record, userId) === null) throw new Error("You are not in this match.");
if (record.state.phase !== "lobby") throw new Error("This match has already started.");
if (record.roster.length < MIN_TO_START) {
throw new Error(`Need at least ${MIN_TO_START} technicians to start.`);
}
rebuildLobbyState(record);
record.state = startRound(record.state);
record.lastActivityAt = Date.now();
record.version += 1;
startTickLoop(record);
pushSnapshots(record);
return buildViewFor(record, userId);
}
export function submitInput(
matchId: string,
userId: number,
input: BomperatorInput,
): void {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
const seat = seatOf(record, userId);
if (seat === null) throw new Error("You are not in this match.");
if (!record.state.players[seat]?.connected) throw new Error("Your seat is not active.");
// Rate limit: reject more than INPUT_RATE_LIMIT_PER_S inputs in a second.
const now = Date.now();
const window = record.inputWindow.get(seat) ?? { count: 0, windowStart: now };
if (now - window.windowStart >= 1000) {
window.count = 0;
window.windowStart = now;
}
window.count += 1;
if (window.count > INPUT_RATE_LIMIT_PER_S) {
record.inputWindow.set(seat, window);
throw new Error("Too many inputs. Slow down.");
}
record.inputWindow.set(seat, window);
record.state = applyInput(record.state, seat, input);
record.lastActivityAt = now;
}
export function leaveMatch(matchId: string, userId: number): void {
const record = matches.get(matchId);
if (!record) return;
const seat = seatOf(record, userId);
if (seat === null) return;
// A finished drill has nothing to reconnect to: remove it outright so nobody
// stays "joined" and blocked from starting a new one until the idle sweep.
if (record.state.phase === "complete") {
disposeMatch(record);
return;
}
if (record.state.phase === "lobby") {
record.roster.splice(seat, 1);
rebuildLobbyState(record);
record.version += 1;
if (record.roster.length === 0) {
disposeMatch(record);
return;
}
record.lastActivityAt = Date.now();
pushSnapshots(record);
return;
}
// Mid-match: hold the seat for a reconnect rather than dropping it outright.
record.state = withPresence(record.state, seat, false, Date.now());
record.version += 1;
record.lastActivityAt = Date.now();
pushSnapshots(record);
// If that was the last connected technician, end the match now instead of
// leaving a zombie board that only clears after the reconnect window lapses
// (and never clears at all if the tick loop died on a server restart).
if (!record.state.players.some((player) => player.connected)) {
record.state = dissolveMatch(record.state);
disposeMatch(record);
}
}
/**
* Hard stop: dissolve and remove the match immediately so nobody is stranded in
* a drill that cannot finish. Any seated technician may call it (a forfeit beats
* being stuck); spectators may not. Awards whatever has been earned.
*/
export function endMatch(matchId: string, userId: number): void {
const record = matches.get(matchId);
if (!record) return; // already gone
if (seatOf(record, userId) === null && record.hostUserId !== userId) {
throw new Error("Only a technician in the drill can end it.");
}
notifyTerminated(record, userId);
if (record.state.phase !== "complete") {
record.state = dissolveMatch(record.state);
}
disposeMatch(record);
}
/**
* Tell every seated technician and active spectator (except the one who ended it)
* that the drill was ended by its host, over the SSE bus. Mirrors blackjack's
* terminated event; the client also falls back to a neutral toast when its poll
* later finds the match gone, so a dropped push still surfaces an explanation.
*/
function notifyTerminated(record: BomperatorMatchRecord, actorUserId: number): void {
const hostName =
record.roster.find((entry) => entry.userId === actorUserId)?.name ??
record.roster.find((entry) => entry.userId === record.hostUserId)?.name ??
null;
const recipients = new Set<number>();
for (const entry of record.roster) recipients.add(entry.userId);
for (const viewerId of record.viewers.keys()) recipients.add(viewerId);
recipients.delete(actorUserId); // the host initiated it; no need to tell them
for (const recipient of recipients) {
broadcastToUser("bomperator-terminated", recipient, {
matchId: record.id,
reason: "host-ended",
hostName,
});
}
}
export function forceExpireMatch(matchId: string): void {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
disposeMatch(record);
}
function disposeMatch(record: BomperatorMatchRecord): void {
stopTickLoop(record);
awardCompleted(record);
matches.delete(record.id);
}
function sweepExpiredMatches(): void {
const now = Date.now();
for (const record of [...matches.values()]) {
if (now - record.lastActivityAt <= BOMP_MATCH_EXPIRY_MS) continue;
disposeMatch(record);
}
}
const sweepInterval = setInterval(sweepExpiredMatches, BOMP_SWEEP_INTERVAL_MS);
sweepInterval.unref?.();
/** Test-only helper: drop every match and timer without awards. */
export function clearMatchesForTests(): void {
for (const record of matches.values()) stopTickLoop(record);
matches.clear();
}
/** Test-only: disable wall-clock ticking so tests can drive steps manually. */
export function setAutoTickForTests(enabled: boolean): void {
autoTickEnabled = enabled;
}
/** Test-only: run N simulation steps for a match, optionally at a fixed clock. */
export function advanceForTests(matchId: string, ticks = 1, now?: number): void {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
for (let i = 0; i < ticks; i += 1) step(record, now ?? Date.now());
}
export { MAX_SEATS, MIN_TO_START };
export type { BomperatorView, BomperatorMatchSummary, BomperatorInput };

View file

@ -0,0 +1,144 @@
/**
* Ordnance Disposal: XP + profile-stats awarding (Payload-dependent,
* server-only). The match registry calls `awardBomperatorResult` when a match
* completes. Never throws: per-user failures are logged and skipped so one
* broken profile cannot break the match record.
*/
import type { Payload } from "payload";
import { chipsForXp } from "@/lib/minigames/chips";
import { broadcastToUser } from "@/lib/realtime/bus";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { BOMP_XP_LOSS, BOMP_XP_PER_KILL, BOMP_XP_WIN } from "./constants";
export interface BomperatorMatchResult {
userId: number;
won: boolean;
kills: number;
roundsWon: number;
}
export interface BomperatorStats {
matchesPlayed: number;
matchWins: number;
roundsWon: number;
kills: number;
xpEarned: number;
}
/** XP for a completed match: win/loss base plus a bounty per technician removed. */
export function xpForBomperator(won: boolean, kills: number): number {
return (won ? BOMP_XP_WIN : BOMP_XP_LOSS) + kills * BOMP_XP_PER_KILL;
}
/** Defensive reader for `progression.minigames.bomperator`. */
export function readBomperatorStats(profile: unknown): BomperatorStats {
const group =
(
profile as { progression?: { minigames?: { bomperator?: Partial<BomperatorStats> } } }
)?.progression?.minigames?.bomperator ?? {};
return {
matchesPlayed: group.matchesPlayed ?? 0,
matchWins: group.matchWins ?? 0,
roundsWon: group.roundsWon ?? 0,
kills: group.kills ?? 0,
xpEarned: group.xpEarned ?? 0,
};
}
/** Pure stat transition for one finished match. */
export function computeBomperatorStatsDelta(
current: BomperatorStats,
result: BomperatorMatchResult,
): BomperatorStats {
const xp = xpForBomperator(result.won, result.kills);
return {
matchesPlayed: current.matchesPlayed + 1,
matchWins: current.matchWins + (result.won ? 1 : 0),
roundsWon: current.roundsWon + result.roundsWon,
kills: current.kills + result.kills,
xpEarned: current.xpEarned + xp,
};
}
/**
* Award XP, chips, and Ordnance Disposal stats for every seated technician of a
* finished match. Emits a single event log entry naming the winner.
*/
export async function awardBomperatorResult(
payload: Payload,
matchId: string,
results: BomperatorMatchResult[],
): Promise<{ xpByUser: Record<number, number> }> {
const xpByUser: Record<number, number> = {};
for (const result of results) {
const xp = xpForBomperator(result.won, result.kills);
xpByUser[result.userId] = xp;
try {
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: result.userId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const profile = profileRes.docs[0];
if (!profile) {
payload.logger.error(`Ordnance Disposal: no profile for user ${result.userId}`);
continue;
}
const current = readBomperatorStats(profile);
const next = computeBomperatorStatsDelta(current, result);
const progression = (profile.progression ?? {}) as Record<string, unknown>;
const minigames = (progression.minigames ?? {}) as Record<string, unknown>;
const chipBank = Math.max(
0,
((progression.chipBank as number | undefined) ?? 0) + chipsForXp(xp),
);
await payload.update({
collection: "profiles",
id: profile.id,
data: {
progression: {
...progression,
chipBank,
minigames: { ...minigames, bomperator: next },
},
},
overrideAccess: true,
depth: 0,
});
broadcastToUser("profile-update", result.userId, {
reason: "xp",
xpGained: xp,
chipBank,
profileId: profile.id,
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
payload.logger.error(
`Ordnance Disposal: failed to award result for user ${result.userId}: ${message}`,
);
}
}
const winner = results.find((result) => result.won);
await emitGameEvent(payload, {
type: EventTypes.MinigameBomperator,
message: winner
? `cleared the depot in Ordnance Disposal (match ${matchId.slice(0, 8)})`
: `ran an Ordnance Disposal drill to no decisive winner (match ${matchId.slice(0, 8)})`,
actor: (winner ?? results[0])?.userId,
targetCollection: "users",
targetId: (winner ?? results[0])?.userId,
data: { matchId, results, xpByUser },
});
return { xpByUser };
}

View file

@ -0,0 +1,205 @@
/**
* Types for Ordnance Disposal (internal key `bomperator`). Pure and client-safe.
*
* The full simulation state lives on the server (the registry owns live match
* records and runs the tick loop). Because free-for-all has no hidden
* information, `views.ts` hands every viewer the same board; spectators simply
* get `seat: null` and cannot submit input.
*/
/** The four classic power-ups hidden under crates. */
export type PowerUpKind = "bomb" | "range" | "speed" | "kick";
/** Static terrain of a single grid cell. */
export type CellType = "empty" | "solid" | "crate";
/** A direction vector, one axis at a time, or null for idle. */
export type Dir = "up" | "down" | "left" | "right";
/** A live charge sitting on the grid. */
export interface Bomb {
readonly id: string;
/** Seat that placed it (owner gets credit for kills its flames cause). */
readonly ownerSeat: number;
readonly x: number;
readonly y: number;
/** Ticks until detonation. */
readonly fuseTicks: number;
/** Flame reach when it goes off. */
readonly range: number;
/** Whether the owner holds kick (a flame can shove this charge along). */
readonly kickable: boolean;
}
/** A burning grid cell after a detonation. */
export interface Flame {
readonly x: number;
readonly y: number;
readonly ticksLeft: number;
/** Seat credited for damage from this flame, or null (sudden death). */
readonly sourceSeat: number | null;
}
/** An exposed power-up on the ground (revealed when its crate is destroyed). */
export interface Drop {
readonly x: number;
readonly y: number;
readonly kind: PowerUpKind;
}
/** One technician on the grid. */
export interface Player {
readonly seat: number;
readonly userId: number;
readonly name: string;
/** Float position in cell-center coordinates (cell + fractional offset). */
readonly x: number;
readonly y: number;
readonly dir: Dir;
readonly alive: boolean;
/** Ticks of spawn protection remaining. */
readonly invulnerableTicks: number;
/** Round-scoped power-up stats (reset every round). */
readonly bombsMax: number;
readonly range: number;
/** Movement speed in cells per second. */
readonly speed: number;
readonly kick: boolean;
/** Match-scoped counters (persist across rounds). */
readonly kills: number;
readonly deaths: number;
readonly roundsWon: number;
/** Latest queued input, consumed by the next tick. */
readonly inputDir: Dir | null;
readonly wantDrop: boolean;
/** Registry-managed presence flags (engine ignores these for rules). */
readonly connected: boolean;
readonly disconnectedAt: number | null;
}
/** A transient event the client can turn into a sound or animation. */
export type BomperatorEvent =
| { readonly type: "explosion"; readonly x: number; readonly y: number }
| { readonly type: "crateBroken"; readonly x: number; readonly y: number }
| { readonly type: "pickup"; readonly seat: number; readonly kind: PowerUpKind }
| { readonly type: "death"; readonly seat: number; readonly killerSeat: number | null }
| { readonly type: "roundEnd"; readonly roundIndex: number; readonly winnerSeat: number | null }
| { readonly type: "suddenDeath" };
/** An event with a monotonic id so a polling client never misses one. */
export type SequencedEvent = BomperatorEvent & { readonly id: number };
export type BomperatorPhase = "lobby" | "countdown" | "battle" | "roundEnd" | "complete";
export interface BomperatorState {
readonly phase: BomperatorPhase;
/** First to this many round-wins takes the match. */
readonly roundTarget: number;
/** Zero-based index of the round currently in play. */
readonly roundIndex: number;
/** Seed for the current round's grid + sudden-death draws. */
readonly gridSeed: number;
/** Monotonic tick counter since the match began. */
readonly tickCount: number;
/** RNG state carried across ticks so sudden death is reproducible. */
readonly rngState: number;
/** Flat GRID_W*GRID_H terrain array (index = y*GRID_W + x). */
readonly grid: readonly CellType[];
/** Hidden power-up under each crate cell, or null (index-aligned to grid). */
readonly hidden: readonly (PowerUpKind | null)[];
readonly players: readonly Player[];
readonly bombs: readonly Bomb[];
readonly flames: readonly Flame[];
readonly drops: readonly Drop[];
/** Ticks remaining in the countdown phase. */
readonly countdownTicks: number;
/** Ticks remaining on the round timer during battle. */
readonly roundTimerTicks: number;
/** Ticks remaining to hold the round-end screen before the next round. */
readonly roundEndHoldTicks: number;
/** Whether sudden death is active this round. */
readonly suddenDeath: boolean;
/** Ticks until the next sudden-death explosion. */
readonly suddenDeathTicks: number;
/** Explosions spawned in sudden death this round (draw-guard counter). */
readonly suddenDeathExplosions: number;
/** Seat that won the current round, or null (in play / draw). */
readonly roundWinnerSeat: number | null;
/** Seat that won the match, or null (in play / draw). */
readonly matchWinnerSeat: number | null;
/** Why the match ended. */
readonly endReason: "rounds" | "dissolved" | null;
/** Rolling buffer of recent events for the client to replay. */
readonly events: readonly SequencedEvent[];
readonly lastEventId: number;
}
/* ------------------------------------------------------------------ views */
/** A player as any viewer sees them. */
export interface PlayerView {
readonly seat: number;
readonly userId: number;
readonly name: string;
readonly x: number;
readonly y: number;
readonly dir: Dir;
readonly alive: boolean;
readonly invulnerable: boolean;
readonly bombsMax: number;
readonly bombsActive: number;
readonly range: number;
readonly speed: number;
readonly kick: boolean;
readonly kills: number;
readonly roundsWon: number;
readonly connected: boolean;
}
/** The complete per-poll snapshot the registry serves. */
export interface BomperatorView {
readonly matchId: string;
readonly name: string | null;
readonly version: number;
/** Seat of the requesting user, or null for a spectator. */
readonly yourSeat: number | null;
readonly phase: BomperatorPhase;
readonly roundTarget: number;
readonly roundIndex: number;
readonly gridW: number;
readonly gridH: number;
/** Compact terrain codes: 0 empty, 1 solid, 2 crate. Length GRID_W*GRID_H. */
readonly grid: readonly number[];
readonly bombs: readonly Bomb[];
readonly flames: readonly Flame[];
readonly drops: readonly Drop[];
readonly players: readonly PlayerView[];
readonly aliveCount: number;
readonly countdownTicks: number;
readonly roundTimerTicks: number;
readonly suddenDeath: boolean;
readonly roundWinnerSeat: number | null;
readonly matchWinnerSeat: number | null;
readonly endReason: "rounds" | "dissolved" | null;
/** Events with id > since that the client has not yet seen. */
readonly events: readonly SequencedEvent[];
readonly lastEventId: number;
}
/** Lobby row. */
export interface BomperatorMatchSummary {
readonly matchId: string;
readonly name: string | null;
readonly hostName: string;
readonly seatedCount: number;
readonly maxSeats: number;
readonly phase: BomperatorPhase | "waiting";
readonly roundTarget: number;
readonly createdAt: string;
readonly joined: boolean;
}

View file

@ -0,0 +1,86 @@
/**
* Projection helpers for Ordnance Disposal. Free-for-all has no hidden
* information, so every viewer receives the same board; a spectator passes
* `yourSeat: null` and simply cannot submit input. The grid is emitted as a
* compact numeric array (0 empty, 1 solid, 2 crate) to keep snapshots small.
*/
import { GRID_H, GRID_W } from "./constants";
import type { BomperatorState, BomperatorView, CellType, PlayerView } from "./types";
const CELL_CODE: Record<CellType, number> = { empty: 0, solid: 1, crate: 2 };
function encodeGrid(grid: readonly CellType[]): number[] {
const out = new Array<number>(grid.length);
for (let i = 0; i < grid.length; i += 1) out[i] = CELL_CODE[grid[i]];
return out;
}
export interface BuildViewOptions {
readonly matchId: string;
readonly name: string | null;
readonly version: number;
/** Seat of the requesting user, or null for a spectator. */
readonly yourSeat: number | null;
}
/** Build the full snapshot the registry serves to one poller. */
export function buildBomperatorView(
state: BomperatorState,
options: BuildViewOptions,
): BomperatorView {
const players: PlayerView[] = state.players.map((p) => ({
seat: p.seat,
userId: p.userId,
name: p.name,
x: round3(p.x),
y: round3(p.y),
dir: p.dir,
alive: p.alive,
invulnerable: p.invulnerableTicks > 0,
bombsMax: p.bombsMax,
bombsActive: countBombs(state, p.seat),
range: p.range,
speed: round3(p.speed),
kick: p.kick,
kills: p.kills,
roundsWon: p.roundsWon,
connected: p.connected,
}));
return {
matchId: options.matchId,
name: options.name,
version: options.version,
yourSeat: options.yourSeat,
phase: state.phase,
roundTarget: state.roundTarget,
roundIndex: state.roundIndex,
gridW: GRID_W,
gridH: GRID_H,
grid: encodeGrid(state.grid),
bombs: state.bombs,
flames: state.flames,
drops: state.drops,
players,
aliveCount: state.players.filter((p) => p.alive).length,
countdownTicks: state.countdownTicks,
roundTimerTicks: Math.max(0, state.roundTimerTicks),
suddenDeath: state.suddenDeath,
roundWinnerSeat: state.roundWinnerSeat,
matchWinnerSeat: state.matchWinnerSeat,
endReason: state.endReason,
events: state.events,
lastEventId: state.lastEventId,
};
}
function countBombs(state: BomperatorState, seat: number): number {
let n = 0;
for (const b of state.bombs) if (b.ownerSeat === seat) n += 1;
return n;
}
function round3(value: number): number {
return Math.round(value * 1000) / 1000;
}

View file

@ -169,6 +169,20 @@ export const BUILTIN_MINIGAMES: BuiltinMinigame[] = [
countsForPeriods: false,
scoreLabel: "Score",
},
{
key: "bomperator",
label: "Ordnance Disposal",
description:
"Multiplayer charge-clearing drill: blow your rivals off the depot grid. Last technician standing wins the round.",
route: "/minigames/bomperator",
icon: "Bomb",
category: "multiplayer",
status: "upcoming",
order: 10,
countsForPeriods: false,
scoreLabel: "Rounds",
estimatedReleaseDate: "2026-11-01T20:00:00.000Z",
},
];
/** Anchor for Period 1: the Monday 00:00 UTC the feature goes live. */
@ -221,6 +235,7 @@ export const MINIGAME_PROFILE_GAME_KEYS: Record<string, string> = {
opord: "opordRecall",
callForFire: "callForFire",
callForFireVersus: "callForFireVersus",
bomperator: "bomperator",
poker: "poker",
blackjack: "blackjack",
};

View file

@ -5,7 +5,21 @@ export interface SSEEventClient {
presenceChannel?: string;
}
const clients = new Set<SSEEventClient>();
/**
* The connected-client set is anchored on `globalThis`, not module scope. Next.js
* dev bundles server packages per route (`devBundleServerPackages`), so a plain
* module-level Set forks into one copy per bundle: a broadcast issued from a
* server-action or registry bundle would never reach a client subscribed through
* the `/api/realtime` route bundle. Sharing it via `globalThis` (the same trick
* the blackjack/poker stores use, and how Payload caches its instance) unifies
* every bundle within the single dev process. In production there is one module
* instance anyway, so this is a no-op there.
*/
interface BusRegistry {
__ptfSseClients?: Set<SSEEventClient>;
}
const globalBus = globalThis as typeof globalThis & BusRegistry;
const clients: Set<SSEEventClient> = (globalBus.__ptfSseClients ??= new Set<SSEEventClient>());
export function subscribe(client: SSEEventClient): () => void {
clients.add(client);

View file

@ -0,0 +1,28 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from "@payloadcms/db-postgres";
/**
* Adds the `progression.minigames.bomperator` column group to `profiles` for the
* Ordnance Disposal minigame (matchesPlayed, matchWins, roundsWon, kills,
* xpEarned). Authored by hand because the local dev database carried unrelated
* migration drift that the generator would otherwise bundle in; scoped strictly
* to the five new columns. Idempotent via IF NOT EXISTS, safe to re-run.
*/
export async function up({ db }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "profiles" ADD COLUMN IF NOT EXISTS "progression_minigames_bomperator_matches_played" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN IF NOT EXISTS "progression_minigames_bomperator_match_wins" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN IF NOT EXISTS "progression_minigames_bomperator_rounds_won" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN IF NOT EXISTS "progression_minigames_bomperator_kills" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN IF NOT EXISTS "progression_minigames_bomperator_xp_earned" numeric DEFAULT 0;
`);
}
export async function down({ db }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "profiles" DROP COLUMN IF EXISTS "progression_minigames_bomperator_matches_played";
ALTER TABLE "profiles" DROP COLUMN IF EXISTS "progression_minigames_bomperator_match_wins";
ALTER TABLE "profiles" DROP COLUMN IF EXISTS "progression_minigames_bomperator_rounds_won";
ALTER TABLE "profiles" DROP COLUMN IF EXISTS "progression_minigames_bomperator_kills";
ALTER TABLE "profiles" DROP COLUMN IF EXISTS "progression_minigames_bomperator_xp_earned";
`);
}

View file

@ -139,6 +139,7 @@ import * as migration_20261014_135614_add_analytics_permission_enum_value from '
import * as migration_20261014_140500_add_minigame_phasing_out_status from './20261014_140500_add_minigame_phasing_out_status';
import * as migration_20261014_192950_add_npc_dialogue_states from './20261014_192950_add_npc_dialogue_states';
import * as migration_20261014_203529_add_event_log_discord_fields from './20261014_203529_add_event_log_discord_fields';
import * as migration_20261015_120000_add_bomperator_minigame_stats from './20261015_120000_add_bomperator_minigame_stats';
export const migrations = [
{
@ -846,4 +847,9 @@ export const migrations = [
down: migration_20261014_203529_add_event_log_discord_fields.down,
name: '20261014_203529_add_event_log_discord_fields'
},
{
up: migration_20261015_120000_add_bomperator_minigame_stats.up,
down: migration_20261015_120000_add_bomperator_minigame_stats.down,
name: '20261015_120000_add_bomperator_minigame_stats'
},
];

View file

@ -3433,6 +3433,13 @@ export interface Profile {
bestScore?: number | null;
xpEarned?: number | null;
};
bomperator?: {
matchesPlayed?: number | null;
matchWins?: number | null;
roundsWon?: number | null;
kills?: number | null;
xpEarned?: number | null;
};
poker?: {
gamesPlayed?: number | null;
wins?: number | null;
@ -9291,6 +9298,15 @@ export interface ProfilesSelect<T extends boolean = true> {
bestScore?: T;
xpEarned?: T;
};
bomperator?:
| T
| {
matchesPlayed?: T;
matchWins?: T;
roundsWon?: T;
kills?: T;
xpEarned?: T;
};
poker?:
| T
| {

View file

@ -81,6 +81,7 @@ export const EventTypes = {
MinigameOpordRecall: "minigame:opord-recall",
MinigameCallForFire: "minigame:call-for-fire",
MinigameCallForFireVersus: "minigame:call-for-fire-versus",
MinigameBomperator: "minigame:bomperator",
MinigamePoker: "minigame:poker",
MinigameBlackjack: "minigame:blackjack",
MinigameCustomEodCreate: "minigame:custom-eod-create",

View file

@ -0,0 +1,413 @@
import { describe, expect, it } from "vitest";
import {
BASE_SPEED_CELLS_PER_S,
BOMB_FUSE_TICKS,
CELL_COUNT,
CRATE_DENSITY,
FLAME_LIFETIME_TICKS,
GRID_H,
GRID_W,
MAX_SUDDEN_DEATH_EXPLOSIONS,
ROUND_END_HOLD_TICKS,
ROUND_TIMER_TICKS,
SPAWN_POINTS,
SUDDEN_DEATH_INTERVAL_TICKS,
applyInput,
createMatchState,
generateGrid,
idx,
tick,
type BomperatorState,
type Bomb,
type CellType,
type Dir,
type Player,
type PowerUpKind,
type SeatDescriptor,
} from "@/lib/minigames/bomperator";
/* ------------------------------------------------------------- test helpers */
/** All-open interior terrain; walls/crates are added explicitly per test. */
function blankGrid(walls: readonly (readonly [number, number])[] = []): CellType[] {
const grid: CellType[] = new Array(CELL_COUNT).fill("empty");
for (const [x, y] of walls) grid[idx(x, y)] = "solid";
return grid;
}
function mkPlayer(seat: number, x: number, y: number, over: Partial<Player> = {}): Player {
return {
seat,
userId: 100 + seat,
name: `P${seat}`,
x,
y,
dir: "down",
alive: true,
invulnerableTicks: 0,
bombsMax: 1,
range: 1,
speed: BASE_SPEED_CELLS_PER_S,
kick: false,
kills: 0,
deaths: 0,
roundsWon: 0,
inputDir: null,
wantDrop: false,
connected: true,
disconnectedAt: null,
...over,
};
}
/** A battle-phase state on a controlled grid, ready to tick. */
function battleState(
players: readonly Player[],
opts: {
grid?: CellType[];
hidden?: (PowerUpKind | null)[];
bombs?: Bomb[];
drops?: BomperatorState["drops"];
roundTimerTicks?: number;
roundTarget?: number;
} = {},
): BomperatorState {
const seats: SeatDescriptor[] = players.map((p) => ({ seat: p.seat, userId: p.userId, name: p.name }));
const base = createMatchState(seats, opts.roundTarget ?? 3, 1234);
return {
...base,
phase: "battle",
grid: opts.grid ?? blankGrid(),
hidden: opts.hidden ?? new Array(CELL_COUNT).fill(null),
players,
bombs: opts.bombs ?? [],
drops: opts.drops ?? [],
roundTimerTicks: opts.roundTimerTicks ?? ROUND_TIMER_TICKS,
};
}
function mkBomb(id: string, ownerSeat: number, x: number, y: number, over: Partial<Bomb> = {}): Bomb {
return {
id,
ownerSeat,
x,
y,
fuseTicks: BOMB_FUSE_TICKS,
range: 1,
kickable: false,
...over,
};
}
const flameAt = (state: BomperatorState, x: number, y: number) =>
state.flames.some((f) => f.x === x && f.y === y);
const bombAt = (state: BomperatorState, x: number, y: number) =>
state.bombs.find((b) => b.x === x && b.y === y);
/** A far-corner bystander so non-combat tests do not end the round on a count of one. */
function idle(seat: number): Player {
return mkPlayer(seat, GRID_W - 2, GRID_H - 2);
}
/* ------------------------------------------------------------- grid layout */
describe("bomperator engine: grid generation", () => {
it("is deterministic for a seed and differs across seeds", () => {
const a = generateGrid(42);
const b = generateGrid(42);
expect(a.grid).toEqual(b.grid);
expect(a.hidden).toEqual(b.hidden);
const c = generateGrid(999);
expect(c.grid).not.toEqual(a.grid);
});
it("lays solid borders and even/even pillars", () => {
const { grid } = generateGrid(7);
expect(grid[idx(0, 0)]).toBe("solid");
expect(grid[idx(GRID_W - 1, GRID_H - 1)]).toBe("solid");
expect(grid[idx(2, 2)]).toBe("solid"); // interior pillar
expect(grid[idx(1, 1)]).toBe("empty"); // lane
});
it("keeps every spawn cell and its escape corridor crate-free", () => {
const { grid } = generateGrid(3);
for (const spawn of SPAWN_POINTS) {
expect(grid[idx(spawn.x, spawn.y)]).toBe("empty");
for (const [dx, dy] of [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
]) {
const x = spawn.x + dx;
const y = spawn.y + dy;
if (x <= 0 || y <= 0 || x >= GRID_W - 1 || y >= GRID_H - 1) continue;
if (x % 2 === 0 && y % 2 === 0) continue; // pillar, allowed solid
expect(grid[idx(x, y)]).not.toBe("crate");
}
}
});
it("hides exactly one power-up under each crate and roughly hits density", () => {
const { grid, hidden } = generateGrid(11);
let crates = 0;
let passable = 0;
for (let i = 0; i < CELL_COUNT; i += 1) {
if (grid[i] === "crate") {
crates += 1;
expect(hidden[i]).not.toBeNull();
} else {
expect(hidden[i]).toBeNull();
}
if (grid[i] !== "solid") passable += 1;
}
// Crates should be a meaningful but not overwhelming share of open ground.
expect(crates / passable).toBeGreaterThan(0.1);
expect(crates / passable).toBeLessThan(CRATE_DENSITY + 0.25);
});
});
/* ---------------------------------------------------------------- movement */
describe("bomperator engine: movement", () => {
it("advances across an open lane and stops flush at a wall", () => {
let state = battleState([mkPlayer(0, 1, 1), idle(1)], { grid: blankGrid([[3, 1]]) });
state = applyInput(state, 0, { dir: "right" as Dir });
// 7 cells/s * 0.05s = 0.35 cells/tick; reaches the wall-adjacent cell 2 quickly.
for (let i = 0; i < 3; i += 1) state = tick(state);
expect(Math.round(state.players[0].x)).toBe(2);
// Keep ticking toward the wall at x=3; must never enter it.
for (let i = 0; i < 20; i += 1) state = tick(state);
expect(state.players[0].x).toBeLessThan(3);
expect(Math.round(state.players[0].x)).toBe(2);
});
it("blocks on a charge without kick, but a kick technician shoves it along", () => {
const bomb = mkBomb("b0", 1, 2, 1);
let blocked = battleState([mkPlayer(0, 1, 1), idle(1)], { bombs: [bomb] });
blocked = applyInput(blocked, 0, { dir: "right" as Dir });
for (let i = 0; i < 10; i += 1) blocked = tick(blocked);
expect(Math.round(blocked.players[0].x)).toBe(1);
expect(bombAt(blocked, 2, 1)).toBeDefined();
let kicker = battleState([mkPlayer(0, 1, 1, { kick: true }), idle(1)], { bombs: [bomb] });
kicker = applyInput(kicker, 0, { dir: "right" as Dir });
kicker = tick(kicker); // one shove
// The charge slid one cell ahead to x=3; the technician is still entering x=2.
expect(bombAt(kicker, 3, 1)).toBeDefined();
expect(bombAt(kicker, 2, 1)).toBeUndefined();
expect(kicker.players[0].x).toBeGreaterThan(1);
expect(kicker.players[0].x).toBeLessThan(2);
});
});
/* -------------------------------------------------------------------- slip */
describe("bomperator engine: slip (glide to rest)", () => {
it("glides forward to the next cell center after releasing mid-stride", () => {
// Off-center heading right, no active input: must complete to cell 2 and stop.
let state = battleState([mkPlayer(0, 1.4, 1, { dir: "right" as Dir }), idle(1)]);
for (let i = 0; i < 10; i += 1) state = tick(state);
expect(state.players[0].x).toBe(2);
expect(state.players[0].y).toBe(1);
expect(Number.isInteger(state.players[0].x)).toBe(true);
});
it("settles back onto the cell being left when the next cell is blocked", () => {
// Wall at x=2 ahead of a rightward slip: never enter it, rest centered on x=1.
let state = battleState([mkPlayer(0, 1.4, 1, { dir: "right" as Dir }), idle(1)], {
grid: blankGrid([[2, 1]]),
});
for (let i = 0; i < 10; i += 1) state = tick(state);
expect(state.players[0].x).toBe(1);
expect(Number.isInteger(state.players[0].x)).toBe(true);
});
it("does not glide when already centered with no input", () => {
let state = battleState([mkPlayer(0, 3, 1, { dir: "right" as Dir }), idle(1)]);
for (let i = 0; i < 5; i += 1) state = tick(state);
expect(state.players[0].x).toBe(3);
expect(state.players[0].y).toBe(1);
});
it("glides vertically and finishes perpendicular alignment before resting", () => {
// Heading down but still drifting onto the lane (x fractional): must end on a
// whole cell, never left between squares.
let state = battleState([mkPlayer(0, 5.4, 5.3, { dir: "down" as Dir }), idle(1)]);
for (let i = 0; i < 20; i += 1) state = tick(state);
expect(Number.isInteger(state.players[0].x)).toBe(true);
expect(Number.isInteger(state.players[0].y)).toBe(true);
expect(state.players[0].y).toBeGreaterThan(5.3);
});
});
/* -------------------------------------------------------------- detonation */
describe("bomperator engine: fuses and detonation", () => {
it("detonates a charge after its fuse and paints a cross flame", () => {
let state = battleState([mkPlayer(0, 7, 9), idle(1)], { bombs: [mkBomb("b0", 0, 7, 6, { range: 1 })] });
for (let i = 0; i < BOMB_FUSE_TICKS - 1; i += 1) state = tick(state);
expect(state.flames.length).toBe(0); // not yet
state = tick(state);
expect(flameAt(state, 7, 6)).toBe(true);
expect(flameAt(state, 6, 6)).toBe(true);
expect(flameAt(state, 8, 6)).toBe(true);
expect(flameAt(state, 7, 5)).toBe(true);
expect(flameAt(state, 7, 7)).toBe(true);
expect(bombAt(state, 7, 6)).toBeUndefined();
});
it("stops a flame arm at a solid wall and destroys the first crate", () => {
const grid = blankGrid([[4, 6]]);
grid[idx(2, 6)] = "crate";
let state = battleState([mkPlayer(0, 7, 9), idle(1)], { grid, hidden: hiddenWith({ "2,6": "range" }) });
state = { ...state, bombs: [mkBomb("b0", 0, 3, 6, { range: 3 })] };
for (let i = 0; i < BOMB_FUSE_TICKS; i += 1) state = tick(state);
// Left arm: crate at (2,6) burns then stops; (1,6) untouched.
expect(flameAt(state, 2, 6)).toBe(true);
expect(flameAt(state, 1, 6)).toBe(false);
// Right arm: wall at (4,6) stops before it.
expect(flameAt(state, 4, 6)).toBe(false);
// The crate is gone and its power-up is exposed as a drop.
expect(state.grid[idx(2, 6)]).toBe("empty");
expect(state.drops.some((d) => d.x === 2 && d.y === 6 && d.kind === "range")).toBe(true);
});
it("chain-detonates a neighbouring charge", () => {
let state = battleState([mkPlayer(0, 7, 9), idle(1)], {
bombs: [
mkBomb("a", 0, 5, 5, { range: 2, fuseTicks: 1 }),
mkBomb("b", 1, 6, 5, { range: 1, fuseTicks: 99 }),
],
});
state = tick(state); // 'a' pops, its arm reaches 'b', 'b' chains
expect(bombAt(state, 5, 5)).toBeUndefined();
expect(bombAt(state, 6, 5)).toBeUndefined();
expect(flameAt(state, 7, 5)).toBe(true); // reached via b's own blast
});
it("shoves a kickable charge instead of detonating it when a flame hits from behind", () => {
let state = battleState([mkPlayer(0, 7, 9), idle(1)], {
bombs: [
mkBomb("a", 0, 5, 5, { range: 3, fuseTicks: 1 }),
mkBomb("b", 1, 6, 5, { range: 1, fuseTicks: 99, kickable: true }),
],
});
state = tick(state);
// 'b' survived and slid to (8,5); only 'a' exploded.
expect(bombAt(state, 8, 5)).toBeDefined();
expect(state.events.filter((e) => e.type === "explosion")).toHaveLength(1);
});
});
/* ------------------------------------------------------------------ combat */
describe("bomperator engine: kills and pickups", () => {
it("kills an exposed technician and credits the bomb owner", () => {
let state = battleState([mkPlayer(0, 3, 5), mkPlayer(1, 6, 5)]);
state = { ...state, bombs: [mkBomb("a", 0, 6, 5, { range: 1, fuseTicks: 1 })] };
state = tick(state);
expect(state.players[1].alive).toBe(false);
expect(state.players[0].kills).toBe(1);
expect(state.players[1].deaths).toBe(1);
});
it("spares a technician still under spawn protection", () => {
let state = battleState([mkPlayer(0, 3, 5), mkPlayer(1, 6, 5, { invulnerableTicks: 5 })]);
state = { ...state, bombs: [mkBomb("a", 0, 6, 5, { range: 1, fuseTicks: 1 })] };
state = tick(state);
expect(state.players[1].alive).toBe(true);
});
it("applies a pickup when walking onto an exposed drop and it persists", () => {
let state = battleState([mkPlayer(0, 5, 5), idle(1)], { drops: [{ x: 6, y: 5, kind: "range" }] });
state = applyInput(state, 0, { dir: "right" as Dir });
for (let i = 0; i < 3; i += 1) state = tick(state);
expect(state.players[0].range).toBe(2);
expect(state.drops.length).toBe(0);
// Persists across further ticks (until the round resets).
state = tick(state);
expect(state.players[0].range).toBe(2);
});
});
/* ------------------------------------------------------- rounds and match */
describe("bomperator engine: round and match resolution", () => {
it("ends the round when one technician remains and awards it", () => {
let state = battleState([mkPlayer(0, 5, 5), mkPlayer(1, 9, 9)]);
state = { ...state, bombs: [mkBomb("a", 0, 9, 9, { range: 1, fuseTicks: 1 })] };
state = tick(state);
expect(state.phase).toBe("roundEnd");
expect(state.roundWinnerSeat).toBe(0);
expect(state.players[0].roundsWon).toBe(1);
});
it("completes the match once a technician reaches the round target", () => {
const champ = mkPlayer(0, 5, 5, { roundsWon: 2 });
let state = battleState([champ, mkPlayer(1, 9, 9)], { roundTarget: 3 });
state = { ...state, bombs: [mkBomb("a", 0, 9, 9, { range: 1, fuseTicks: 1 })] };
state = tick(state);
expect(state.phase).toBe("complete");
expect(state.matchWinnerSeat).toBe(0);
expect(state.endReason).toBe("rounds");
});
it("advances to a fresh countdown round after the end hold", () => {
let state = battleState([mkPlayer(0, 5, 5), mkPlayer(1, 9, 9)]);
state = { ...state, bombs: [mkBomb("a", 0, 9, 9, { range: 1, fuseTicks: 1 })] };
state = tick(state); // -> roundEnd
expect(state.phase).toBe("roundEnd");
const roundIndexBefore = state.roundIndex;
for (let i = 0; i < ROUND_END_HOLD_TICKS + 5 && state.phase === "roundEnd"; i += 1)
state = tick(state);
expect(state.phase).toBe("countdown");
expect(state.roundIndex).toBe(roundIndexBefore + 1);
// Fresh grid: crates exist again and everyone is alive at spawn.
expect(state.players.every((p) => p.alive)).toBe(true);
});
});
/* ------------------------------------------------------------ sudden death */
describe("bomperator engine: sudden death", () => {
it("enters sudden death when the round timer expires and spawns explosions", () => {
let state = battleState([mkPlayer(0, 1, 1), mkPlayer(1, GRID_W - 2, GRID_H - 2)], {
roundTimerTicks: 2,
});
state = tick(state); // timer 1
expect(state.suddenDeath).toBe(false);
state = tick(state); // timer 0 -> sudden death
expect(state.suddenDeath).toBe(true);
// Run past one sudden-death interval; an explosion should have fired.
for (let i = 0; i < SUDDEN_DEATH_INTERVAL_TICKS + 5; i += 1) state = tick(state);
expect(state.suddenDeathExplosions).toBeGreaterThanOrEqual(1);
});
it("calls a draw once the sudden-death explosion budget is exhausted", () => {
// Two technicians far apart with a huge timer already spent in sudden death.
let state = battleState([mkPlayer(0, 1, 1), mkPlayer(1, GRID_W - 2, GRID_H - 2)], {
roundTimerTicks: 1,
});
state = { ...state, suddenDeath: true, suddenDeathExplosions: MAX_SUDDEN_DEATH_EXPLOSIONS };
// Force the guard: keep ticking; the round must resolve rather than loop.
for (let i = 0; i < 5 && state.phase === "battle"; i += 1) state = tick(state);
expect(state.phase).not.toBe("battle");
if (state.phase === "roundEnd") expect(state.roundWinnerSeat).toBeNull();
});
});
/* ----------------------------------------------------------------- helpers */
function hiddenWith(entries: Record<string, PowerUpKind>): (PowerUpKind | null)[] {
const hidden: (PowerUpKind | null)[] = new Array(CELL_COUNT).fill(null);
for (const [key, kind] of Object.entries(entries)) {
const [x, y] = key.split(",").map(Number);
hidden[idx(x, y)] = kind;
}
return hidden;
}
// Silence unused-import lint for constants referenced only in some branches.
void FLAME_LIFETIME_TICKS;

View file

@ -0,0 +1,309 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { getPayload, type Payload } from "payload";
import config from "@payload-config";
import {
INTER_ROUND_COUNTDOWN_TICKS,
MAX_SEATS,
MIN_TO_START,
RECONNECT_WINDOW_MS,
} from "@/lib/minigames/bomperator/constants";
import {
advanceForTests,
clearMatchesForTests,
createMatch,
endMatch,
forceExpireMatch,
getSnapshotFor,
joinMatch,
leaveMatch,
listMatchSummaries,
setAutoTickForTests,
startMatch,
submitInput,
} from "@/lib/minigames/bomperator/registry";
import {
awardBomperatorResult,
computeBomperatorStatsDelta,
readBomperatorStats,
xpForBomperator,
} from "@/lib/minigames/bomperator/stats";
beforeEach(() => {
setAutoTickForTests(false); // drive the sim manually; no wall-clock intervals
clearMatchesForTests();
});
afterEach(() => clearMatchesForTests());
afterAll(() => {
clearMatchesForTests();
setAutoTickForTests(true);
});
/** Bring a freshly started match out of the countdown and into battle. */
function toBattle(matchId: string): void {
advanceForTests(matchId, INTER_ROUND_COUNTDOWN_TICKS + 1);
}
describe("bomperator registry: lobby", () => {
it("seats the host and reports a waiting match", () => {
const matchId = createMatch(9001, "Host");
const summary = listMatchSummaries(9001).find((row) => row.matchId === matchId);
expect(summary?.phase).toBe("waiting");
expect(summary?.seatedCount).toBe(1);
expect(summary?.joined).toBe(true);
expect(listMatchSummaries(9002).find((row) => row.matchId === matchId)?.joined).toBe(false);
});
it("fills seats up to the cap and rejects an extra player", () => {
const matchId = createMatch(9101, "Host");
for (let seat = 1; seat < MAX_SEATS; seat += 1) joinMatch(matchId, 9101 + seat, `P${seat}`);
expect(() => joinMatch(matchId, 9999, "Overflow")).toThrow("full");
});
it("stops a user seating at two matches at once", () => {
createMatch(9201, "Host");
const second = createMatch(9202, "Other");
expect(() => joinMatch(second, 9201, "Host")).toThrow("already in another match");
});
it("lets a non-seated user read a spectator snapshot with no seat", () => {
const matchId = createMatch(9301, "Host");
const view = getSnapshotFor(matchId, 9302);
expect(view.yourSeat).toBeNull();
expect(view.players[0].name).toBe("Host");
});
});
describe("bomperator registry: start gating", () => {
it("refuses to start below the minimum and starts at the minimum", () => {
const matchId = createMatch(9401, "Host");
expect(() => startMatch(matchId, 9401)).toThrow(`at least ${MIN_TO_START}`);
joinMatch(matchId, 9402, "Guest");
const view = startMatch(matchId, 9401);
expect(view.phase).toBe("countdown");
});
it("rejects starting twice", () => {
const matchId = createMatch(9501, "Host");
joinMatch(matchId, 9502, "Guest");
startMatch(matchId, 9501);
expect(() => startMatch(matchId, 9501)).toThrow("already started");
});
});
describe("bomperator registry: input + ticking", () => {
it("applies a queued movement input over subsequent ticks", () => {
const matchId = createMatch(9601, "Host");
joinMatch(matchId, 9602, "Guest");
startMatch(matchId, 9601);
toBattle(matchId);
const before = getSnapshotFor(matchId, 9601);
expect(before.phase).toBe("battle");
expect(before.players[before.yourSeat!].x).toBeCloseTo(1, 3);
submitInput(matchId, 9601, { dir: "right" });
advanceForTests(matchId, 6);
const after = getSnapshotFor(matchId, 9601);
expect(after.players[after.yourSeat!].x).toBeGreaterThan(1.5);
});
it("rejects inputs from a non-seated user", () => {
const matchId = createMatch(9701, "Host");
joinMatch(matchId, 9702, "Guest");
startMatch(matchId, 9701);
expect(() => submitInput(matchId, 9799, { dir: "left" })).toThrow("not in this match");
});
});
describe("bomperator registry: disconnect and dissolve", () => {
it("holds a seat on leave and restores it on rejoin", () => {
const matchId = createMatch(9801, "Host");
joinMatch(matchId, 9802, "Guest");
startMatch(matchId, 9801);
toBattle(matchId);
leaveMatch(matchId, 9801);
expect(getSnapshotFor(matchId, 9802).players[0].connected).toBe(false);
joinMatch(matchId, 9801, "Host"); // rejoin within the window
expect(getSnapshotFor(matchId, 9802).players[0].connected).toBe(true);
});
it("dissolves the match once a held seat's reconnect window lapses", () => {
const matchId = createMatch(9901, "Host");
joinMatch(matchId, 9902, "Guest");
startMatch(matchId, 9901);
toBattle(matchId);
leaveMatch(matchId, 9901); // host walks away
// Advance with a clock past the reconnect window: the seat expires and the
// match drops below two active technicians.
advanceForTests(matchId, 1, Date.now() + RECONNECT_WINDOW_MS + 5_000);
const view = getSnapshotFor(matchId, 9902);
expect(view.phase).toBe("complete");
expect(view.endReason).toBe("dissolved");
});
});
describe("bomperator registry: exit paths", () => {
it("ends the match as soon as the last connected technician leaves", () => {
const matchId = createMatch(9951, "Host");
joinMatch(matchId, 9952, "Guest");
startMatch(matchId, 9951);
toBattle(matchId);
leaveMatch(matchId, 9951); // host walks; guest still connected -> alive
expect(() => getSnapshotFor(matchId, 9952)).not.toThrow();
leaveMatch(matchId, 9952); // last connected leaves -> dissolve + dispose now
expect(() => getSnapshotFor(matchId, 9952)).toThrow("Match not found.");
});
it("lets a seated technician end the drill, but not a stranger", () => {
const matchId = createMatch(9961, "Host");
joinMatch(matchId, 9962, "Guest");
startMatch(matchId, 9961);
toBattle(matchId);
expect(() => endMatch(matchId, 9999)).toThrow("Only a technician");
endMatch(matchId, 9962); // guest can end it
expect(() => getSnapshotFor(matchId, 9961)).toThrow("Match not found.");
});
});
describe("bomperator registry: disposal", () => {
it("force-expiring removes the match", () => {
const matchId = createMatch(9911, "Host");
forceExpireMatch(matchId);
expect(() => getSnapshotFor(matchId, 9911)).toThrow("Match not found.");
});
it("clearing for tests isolates subsequent specs", () => {
createMatch(9921, "Host");
clearMatchesForTests();
expect(listMatchSummaries()).toHaveLength(0);
});
});
describe("bomperator: stat math", () => {
it("reads defaults and accumulates a finished match", () => {
expect(readBomperatorStats({})).toEqual({
matchesPlayed: 0,
matchWins: 0,
roundsWon: 0,
kills: 0,
xpEarned: 0,
});
const win = computeBomperatorStatsDelta(readBomperatorStats({}), {
userId: 1,
won: true,
kills: 3,
roundsWon: 2,
});
expect(win).toEqual({
matchesPlayed: 1,
matchWins: 1,
roundsWon: 2,
kills: 3,
xpEarned: xpForBomperator(true, 3),
});
const loss = computeBomperatorStatsDelta(win, {
userId: 1,
won: false,
kills: 1,
roundsWon: 0,
});
expect(loss.matchesPlayed).toBe(2);
expect(loss.matchWins).toBe(1);
expect(loss.roundsWon).toBe(2);
expect(loss.kills).toBe(4);
});
it("scores XP as a base plus a per-kill bounty", () => {
expect(xpForBomperator(false, 0)).toBeLessThan(xpForBomperator(true, 0));
expect(xpForBomperator(true, 2) - xpForBomperator(true, 1)).toBe(
xpForBomperator(false, 1) - xpForBomperator(false, 0),
);
});
});
describe("bomperator: awards write to the profile (DB round-trip)", () => {
let payload: Payload;
const createdUserIds: number[] = [];
beforeAll(async () => {
payload = await getPayload({ config });
}, 30_000);
afterAll(async () => {
// Order matters: event logs reference the user (actor FK), profiles too.
for (const userId of createdUserIds) {
const events = await payload.find({
collection: "game-event-logs",
where: { actor: { equals: userId } },
limit: 200,
depth: 0,
overrideAccess: true,
});
for (const e of events.docs) {
await payload.delete({ collection: "game-event-logs", id: e.id, overrideAccess: true });
}
const profiles = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 50,
depth: 0,
overrideAccess: true,
});
for (const p of profiles.docs) {
await payload.delete({ collection: "profiles", id: p.id, overrideAccess: true });
}
await payload.delete({ collection: "users", id: userId, overrideAccess: true });
}
});
it("persists stats and derives chips from XP", async () => {
const username = `bomp_${Date.now().toString(36)}_${Math.floor(Math.random() * 1e6)}`;
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: `Bomp ${username}`,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
createdUserIds.push(user.id);
const result = await awardBomperatorResult(payload, "match-abc12345", [
{ userId: user.id, won: true, kills: 2, roundsWon: 1 },
]);
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: user.id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const group = profileRes.docs[0]?.progression?.minigames?.bomperator;
expect(group).toMatchObject({
matchesPlayed: 1,
matchWins: 1,
roundsWon: 1,
kills: 2,
xpEarned: xpForBomperator(true, 2),
});
// Chips are auto-derived at 10 per XP, so the bank must have grown.
expect((profileRes.docs[0]?.progression?.chipBank ?? 0)).toBeGreaterThan(0);
expect(result.xpByUser[user.id]).toBe(xpForBomperator(true, 2));
});
});