1
0
Fork 0
polaris-task-force/src/components/frontend/minigames/bomperator/BomperatorArena.tsx
Z8MB1E 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

292 lines
10 KiB
TypeScript

"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>
);
}