1
0
Fork 0

feat(minigames): add Call for Fire: Versus multiplayer artillery duel

Head-to-head artillery duel in a new "multiplayer" registry category
(out of periods). Each operator hides a fire-base fleet on a 10x10 grid,
then takes turns calling fire: the first mission is a grid designation,
every later shot adjusts from that operator's last impact using the
single-player range/deflection controls. First to reduce every enemy
emplacement wins; a cap decides on emplacements then cells.

Pure engine in src/lib/minigames/call-for-fire-versus (engine, views,
types, constants) is client-safe and unit-tested. The server-only
registry mirrors the blackjack table pattern (globalThis-anchored Map,
lobby, per-turn timeout, expiry sweep, single-instance only); its views
are built per viewer so the opponent's fleet layout never leaves the
server. The client polls the match snapshot (the in-memory SSE bus is
unreliable across dev module copies). Rewards on completion update the
callForFireVersus profile group, pay XP and chips, and emit
minigame:call-for-fire-versus.

Wires the game into the registry (new multiplayer category + enum
migration), the sidebar grouping, the command palette, and the profile
XP aggregation. The registry row seed is split into its own migration
because Postgres forbids using a freshly added enum value in the same
transaction.

Verified: 21 new tests (engine + registry) plus the wider minigame suite
pass; tsc clean; a live two-player award run confirmed XP, chips, and
the event.
This commit is contained in:
Jason Fraley 2026-10-11 21:55:39 -04:00
parent 3e9449971f
commit 005ff0e5df
29 changed files with 83004 additions and 3 deletions

View file

@ -0,0 +1,157 @@
"use server";
/**
* Server-action surface for the Call for Fire versus mode.
* All match logic lives in the registry
* (src/lib/minigames/call-for-fire-versus/registry.ts).
*/
import config from "@payload-config";
import { getPayload } from "payload";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import type {
VersusMatchSummary,
VersusMatchView,
} from "@/lib/minigames/call-for-fire-versus/types";
import type { FobPlacement } from "@/lib/minigames/call-for-fire-versus/constants";
import type { VersusShotInput } from "@/lib/minigames/call-for-fire-versus/engine";
import {
createMatch,
fireShotFor,
forceExpireMatch,
getSnapshotFor,
joinMatch,
leaveMatch,
listMatchSummaries,
placeFleetFor,
} from "@/lib/minigames/call-for-fire-versus/registry";
export type { VersusMatchSummary, VersusMatchView, VersusShotInput, FobPlacement };
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 createVersusMatch(): Promise<ActionResult<{ matchId: string }>> {
try {
const { user } = await authenticate();
const matchId = createMatch(Number(user.id), userName(user));
return { success: true, data: { matchId } };
} catch (error) {
return toError(error);
}
}
export async function listVersusMatches(): Promise<ActionResult<VersusMatchSummary[]>> {
try {
const { user } = await authenticate();
return { success: true, data: listMatchSummaries(Number(user.id)) };
} catch (error) {
return toError(error);
}
}
export async function joinVersusMatch(matchId: string): Promise<ActionResult<VersusMatchView>> {
try {
const { user } = await authenticate();
return { success: true, data: joinMatch(matchId, Number(user.id), userName(user)) };
} catch (error) {
return toError(error);
}
}
export async function fetchVersusMatch(matchId: string): Promise<ActionResult<VersusMatchView>> {
try {
const { user } = await authenticate();
return { success: true, data: getSnapshotFor(matchId, Number(user.id)) };
} catch (error) {
return toError(error);
}
}
export async function placeVersusFleet(
matchId: string,
placements: FobPlacement[],
): Promise<ActionResult<VersusMatchView>> {
try {
const { user } = await authenticate();
return { success: true, data: placeFleetFor(matchId, Number(user.id), placements) };
} catch (error) {
return toError(error);
}
}
export async function fireVersusShot(
matchId: string,
input: VersusShotInput,
): Promise<ActionResult<VersusMatchView>> {
try {
const { user } = await authenticate();
return { success: true, data: fireShotFor(matchId, Number(user.id), input) };
} catch (error) {
return toError(error);
}
}
export async function leaveVersusMatch(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 forceExpireVersusMatch(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,83 @@
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 { Swords } from "lucide-react";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { CallForFireVersusArena } from "@/components/frontend/minigames/call-for-fire-versus/CallForFireVersusArena";
export const metadata: Metadata = {
title: "Call for Fire: Versus (Polaris Task Force)",
description:
"Head-to-head artillery duel: emplace your fire bases, then bracket the enemy's before they bracket yours.",
};
interface VersusPageProps {
searchParams: Promise<{
match?: string | string[];
}>;
}
export default async function CallForFireVersusPage({ searchParams }: VersusPageProps) {
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/call-for-fire-versus")}`);
}
const release = await getMinigameReleaseState(payload, "callForFireVersus");
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 versus = profileRes.docs[0]?.progression?.minigames?.callForFireVersus ?? {};
const stats = {
gamesPlayed: versus.gamesPlayed ?? 0,
wins: versus.wins ?? 0,
losses: versus.losses ?? 0,
bestScore: versus.bestScore ?? 0,
xpEarned: versus.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">
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<Swords className="size-5 text-muted-foreground" />
<h1 className="text-lg font-semibold">Call for Fire: Versus</h1>
</div>
<p className="text-sm text-muted-foreground">
Emplace your fire bases, then bracket the enemy&apos;s before they bracket yours. First
to reduce every emplacement wins.
</p>
</div>
<CallForFireVersusArena
initialStats={stats}
currentUserId={Number(user.id)}
initialMatchId={initialMatchId}
/>
</div>
);
}

View file

@ -60,6 +60,7 @@ export const Minigames: CollectionConfig = {
options: [
{ label: "Core", value: "core" },
{ label: "Cardtable", value: "cardtable" },
{ label: "Multiplayer", value: "multiplayer" },
],
},
{

View file

@ -133,6 +133,7 @@ export const Profiles: CollectionConfig = {
aimTrainer?: { xpEarned?: number | null };
opordRecall?: { xpEarned?: number | null };
callForFire?: { xpEarned?: number | null };
callForFireVersus?: { xpEarned?: number | null };
poker?: { xpEarned?: number | null };
blackjack?: { xpEarned?: number | null };
};
@ -153,6 +154,8 @@ export const Profiles: CollectionConfig = {
const aimTrainerXp = progressionData?.minigames?.aimTrainer?.xpEarned ?? 0;
const opordRecallXp = progressionData?.minigames?.opordRecall?.xpEarned ?? 0;
const callForFireXp = progressionData?.minigames?.callForFire?.xpEarned ?? 0;
const callForFireVersusXp =
progressionData?.minigames?.callForFireVersus?.xpEarned ?? 0;
const pokerXp = progressionData?.minigames?.poker?.xpEarned ?? 0;
const blackjackXp = progressionData?.minigames?.blackjack?.xpEarned ?? 0;
const voiceoverXp = progressionData?.voiceover?.xpEarned ?? 0;
@ -201,6 +204,8 @@ export const Profiles: CollectionConfig = {
xpAcc += opordRecallXp;
// Call for Fire: XP from effective artillery adjustments
xpAcc += callForFireXp;
// Call for Fire versus: XP from artillery duels
xpAcc += callForFireVersusXp;
// Poker sit-and-go: XP from placement payouts
xpAcc += pokerXp;
// Blackjack sessions: XP from profit-based payouts
@ -716,6 +721,43 @@ export const Profiles: CollectionConfig = {
},
],
},
{
name: "callForFireVersus",
label: "Call for Fire: Versus",
type: "group",
fields: [
{
name: "gamesPlayed",
label: "Matches Played",
type: "number",
defaultValue: 0,
},
{
name: "wins",
label: "Duels Won",
type: "number",
defaultValue: 0,
},
{
name: "losses",
label: "Duels Lost",
type: "number",
defaultValue: 0,
},
{
name: "bestScore",
label: "Best Duel Score",
type: "number",
defaultValue: 0,
},
{
name: "xpEarned",
label: "XP Earned",
type: "number",
defaultValue: 0,
},
],
},
{
name: "poker",
label: "Poker",

View file

@ -28,6 +28,7 @@ import {
Spade,
Club,
Target,
Swords,
} from "lucide-react";
export interface NavigationCommand {
@ -279,6 +280,13 @@ export const navigationCommands: NavigationCommand[] = [
href: "/minigames/call-for-fire",
keywords: ["minigame", "artillery", "fire mission", "observer", "bracket", "training"],
},
{
id: "nav:call-for-fire-versus",
label: "Call for Fire: Versus",
icon: Swords,
href: "/minigames/call-for-fire-versus",
keywords: ["minigame", "multiplayer", "artillery", "duel", "versus", "pvp", "training"],
},
{
id: "nav:poker",
label: "Poker",

View file

@ -37,6 +37,7 @@ export function NavMinigames({ games }: { games: RegistryGame[] }) {
const visible = games.filter((game) => game.status !== "retired");
const coreGames = visible.filter((game) => game.category === "core");
const multiplayerGames = visible.filter((game) => game.category === "multiplayer");
const cardtableGames = visible.filter((game) => game.category === "cardtable");
const renderGame = (game: RegistryGame) => {
@ -94,6 +95,20 @@ export function NavMinigames({ games }: { games: RegistryGame[] }) {
<DropdownMenuLabel>Core</DropdownMenuLabel>
{coreGames.map(renderGame)}
</DropdownMenuGroup>
{multiplayerGames.length > 0 && (
<>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuLabel className="flex flex-col">
<span>Multiplayer</span>
<span className="text-xs font-normal text-muted-foreground">
Head-to-head duels against other operators
</span>
</DropdownMenuLabel>
{multiplayerGames.map(renderGame)}
</DropdownMenuGroup>
</>
)}
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuLabel className="flex flex-col">

View file

@ -0,0 +1,169 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import {
fetchVersusMatch,
leaveVersusMatch,
type VersusMatchView,
} from "@/app/(frontend)/minigames/call-for-fire-versus/actions";
import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { VersusLobby } from "./VersusLobby";
import { VersusMatch } from "./VersusMatch";
export interface VersusStats {
gamesPlayed: number;
wins: number;
losses: number;
bestScore: number;
xpEarned: number;
}
const STAT_ITEMS = [
["Matches", "gamesPlayed"],
["Duels won", "wins"],
["Duels lost", "losses"],
["Best score", "bestScore"],
["XP earned", "xpEarned"],
] as const satisfies readonly (readonly [string, keyof VersusStats])[];
type ArenaView = "lobby" | "match";
export function CallForFireVersusArena({
initialStats,
currentUserId,
initialMatchId,
}: {
initialStats: VersusStats;
currentUserId: number | string;
initialMatchId?: string;
}) {
const [view, setView] = useState<ArenaView>(initialMatchId ? "match" : "lobby");
const [match, setMatch] = useState<VersusMatchView | null>(null);
const [matchId, setMatchId] = useState<string | null>(initialMatchId ?? null);
const [error, setError] = useState<string | null>(null);
const resetToLobby = useCallback(() => {
setView("lobby");
setMatch(null);
setMatchId(null);
setError(null);
if (typeof window !== "undefined") {
window.history.replaceState(null, "", "/minigames/call-for-fire-versus");
}
}, []);
const applyMatch = useCallback((next: VersusMatchView) => {
setMatch(next);
setMatchId(next.matchId);
setView("match");
setError(null);
if (typeof window !== "undefined" && next.matchId) {
window.history.replaceState(
null,
"",
`/minigames/call-for-fire-versus?match=${encodeURIComponent(next.matchId)}`,
);
}
}, []);
// Deep link into a match.
useEffect(() => {
if (!initialMatchId) return;
let cancelled = false;
void fetchVersusMatch(initialMatchId)
.then((result) => {
if (cancelled) return;
if (result.success && result.data) {
setMatch(result.data);
setView("match");
} else {
setError(result.error ?? "This match was not found.");
}
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [initialMatchId]);
// Polling is the correctness path (the in-memory SSE bus cannot be relied on
// across Next dev module copies, same as the blackjack table).
useEffect(() => {
if (view !== "match" || matchId === null) return;
let cancelled = false;
const poll = window.setInterval(() => {
void fetchVersusMatch(matchId)
.then((result) => {
if (cancelled) return;
if (result.success && result.data) {
setMatch(result.data);
} else if (result.error === "Match not found.") {
resetToLobby();
}
})
.catch(() => undefined);
}, 1500);
return () => {
cancelled = true;
window.clearInterval(poll);
};
}, [view, matchId, resetToLobby]);
const leave = useCallback(async () => {
if (matchId) {
try {
await leaveVersusMatch(matchId);
} catch {
// Leaving is best-effort; resetting the view is what matters.
}
}
resetToLobby();
}, [matchId, resetToLobby]);
const inMatch = view === "match" && matchId !== null;
const operatorsOnline = useRealtimePresence("callForFireVersus", inMatch, true);
return (
<div className="flex flex-col gap-6">
<Card>
<CardHeader className="border-b p-4">
<CardTitle className="text-sm">Your duel record</CardTitle>
<p className="text-sm text-muted-foreground">Rewards are granted when a duel ends.</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" ? (
<VersusLobby onOpenMatch={applyMatch} currentUserId={currentUserId} />
) : match ? (
<VersusMatch
match={match}
currentUserId={currentUserId}
onMatch={applyMatch}
onLeave={leave}
operatorsOnline={operatorsOnline.map((participant) => participant.name)}
/>
) : (
<p className="text-sm text-muted-foreground">Loading match…</p>
)}
</div>
);
}

View file

@ -0,0 +1,146 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { Plus, RefreshCw, Swords } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
createVersusMatch,
fetchVersusMatch,
joinVersusMatch,
listVersusMatches,
type VersusMatchSummary,
type VersusMatchView,
} from "@/app/(frontend)/minigames/call-for-fire-versus/actions";
const PHASE_LABELS: Record<VersusMatchSummary["phase"], string> = {
waiting: "Waiting for an opponent",
placing: "Emplacement",
battle: "In progress",
complete: "Finished",
};
export function VersusLobby({
onOpenMatch,
currentUserId,
}: {
onOpenMatch: (match: VersusMatchView) => void;
currentUserId: number | string;
}) {
const [matches, setMatches] = useState<VersusMatchSummary[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const refresh = useCallback(() => {
void listVersusMatches()
.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 createVersusMatch();
if (!created.success || !created.data) {
setBusyId(null);
setError(created.error ?? "Could not create a match.");
return;
}
const snapshot = await fetchVersusMatch(created.data.matchId);
setBusyId(null);
if (snapshot.success && snapshot.data) onOpenMatch(snapshot.data);
else refresh();
}, [onOpenMatch, refresh]);
const enter = useCallback(
async (matchId: string) => {
setBusyId(matchId);
setError(null);
const result = await joinVersusMatch(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">
<Swords className="size-4 text-muted-foreground" />
Artillery duels
</CardTitle>
<p className="text-sm text-muted-foreground">
Open a match and share the link, or join one below.
</p>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={refresh} disabled={busyId !== null}>
<RefreshCw /> Refresh
</Button>
<Button size="sm" onClick={create} disabled={busyId !== null}>
<Plus /> New duel
</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 matches. Start one and send the link to your opponent.
</p>
) : (
<ul className="divide-y divide-border">
{matches.map((match) => (
<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 ?? "Artillery duel"}
</span>
<span className="text-xs text-muted-foreground">
{match.hostName}
{match.guestName ? ` vs ${match.guestName}` : " vs open seat"} ·{" "}
{match.seatedCount}/{match.maxSeats} · {PHASE_LABELS[match.phase]}
</span>
</div>
<Button
size="sm"
variant={match.joined || match.seatedCount < 2 ? "default" : "outline"}
disabled={busyId !== null || (!match.joined && match.seatedCount >= 2)}
onClick={() => enter(match.matchId)}
>
{match.joined ? "Rejoin" : match.seatedCount < 2 ? "Join" : "Full"}
</Button>
</li>
))}
</ul>
)}
</CardContent>
</Card>
);
}

View file

@ -0,0 +1,805 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Crosshair, Clock, RotateCcw, Shuffle, Target, Trophy, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
fireVersusShot,
placeVersusFleet,
type VersusMatchView,
type VersusShotInput,
} from "@/app/(frontend)/minigames/call-for-fire-versus/actions";
import { gridDesignation, METERS_PER_CELL, type GridPoint } from "@/lib/minigames/call-for-fire";
import {
FOB_FLEET,
VERSUS_WAITING_USER_ID,
type FobOrientation,
type FobPlacement,
} from "@/lib/minigames/call-for-fire-versus/constants";
import { cellsForPlacement } from "@/lib/minigames/call-for-fire-versus/engine";
import type { VersusFobView, VersusShotView } from "@/lib/minigames/call-for-fire-versus/types";
import { cn } from "@/lib/utils";
const BOARD = 10;
const CORRECTION_STEP = 50;
function key(point: GridPoint): string {
return `${point.x},${point.y}`;
}
function useNow(intervalMs = 1000): number {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const id = window.setInterval(() => setNow(Date.now()), intervalMs);
return () => window.clearInterval(id);
}, [intervalMs]);
return now;
}
function cellLabel(x: number, y: number): string {
return gridDesignation({ x, y });
}
/* --------------------------------------------------------------- placement */
function randomFleet(): Record<string, FobPlacement> {
const placements: Record<string, FobPlacement> = {};
const occupied = new Set<string>();
for (const definition of FOB_FLEET) {
for (let attempt = 0; attempt < 800; attempt += 1) {
const orientation: FobOrientation = Math.random() < 0.5 ? "h" : "v";
const origin = {
x: Math.floor(Math.random() * BOARD),
y: Math.floor(Math.random() * BOARD),
};
const cells = cellsForPlacement(origin, orientation, definition.size, BOARD);
if (!cells) continue;
if (cells.some((cell) => occupied.has(key(cell)))) continue;
cells.forEach((cell) => occupied.add(key(cell)));
placements[definition.id] = { assetId: definition.id, origin, orientation };
break;
}
}
return placements;
}
function PlacementPhase({
match,
onMatch,
waiting,
}: {
match: VersusMatchView;
onMatch: (next: VersusMatchView) => void;
waiting: boolean;
}) {
const [placements, setPlacements] = useState<Record<string, FobPlacement>>(() => {
const initial: Record<string, FobPlacement> = {};
for (const fob of match.you.fleet) {
const origin = fob.cells[0];
if (!origin) continue;
const orientation: FobOrientation =
fob.size > 1 && fob.cells[1] && fob.cells[1].x !== origin.x ? "h" : "v";
initial[fob.id] = { assetId: fob.id, origin, orientation };
}
return initial;
});
const [selectedId, setSelectedId] = useState<string>(FOB_FLEET[0].id);
const [orientation, setOrientation] = useState<FobOrientation>("h");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const occupied = useMemo(() => {
const map = new Map<string, { assetId: string; isNew: boolean }>();
for (const definition of FOB_FLEET) {
const placement = placements[definition.id];
if (!placement) continue;
const cells = cellsForPlacement(placement.origin, placement.orientation, definition.size, BOARD);
if (!cells) continue;
for (const cell of cells) map.set(key(cell), { assetId: definition.id, isNew: false });
}
return map;
}, [placements]);
const selectedPlacement = placements[selectedId];
const previewCells = selectedPlacement
? (cellsForPlacement(selectedPlacement.origin, selectedPlacement.orientation, FOB_FLEET.find((f) => f.id === selectedId)!.size, BOARD) ?? [])
: [];
const placeAt = useCallback(
(x: number, y: number) => {
const definition = FOB_FLEET.find((f) => f.id === selectedId);
if (!definition) return;
const origin: GridPoint = { x, y };
const cells = cellsForPlacement(origin, orientation, definition.size, BOARD);
setError(cells ? null : `${definition.label} does not fit there.`);
setPlacements((current) => {
const next = { ...current };
// Drop any other asset occupying these cells.
if (cells) {
for (const cell of cells) {
for (const otherId of Object.keys(next)) {
if (otherId === selectedId) continue;
const other = next[otherId];
const otherCells = cellsForPlacement(
other.origin,
other.orientation,
FOB_FLEET.find((f) => f.id === otherId)!.size,
BOARD,
);
if (otherCells?.some((c) => c.x === cell.x && c.y === cell.y)) delete next[otherId];
}
}
}
next[selectedId] = { assetId: selectedId, origin, orientation };
return next;
});
const nextUnplaced = FOB_FLEET.find((f) => f.id !== selectedId && !placements[f.id]);
if (nextUnplaced) setSelectedId(nextUnplaced.id);
},
[orientation, placements, selectedId],
);
const allPlaced = FOB_FLEET.every((definition) => placements[definition.id]);
const confirm = useCallback(async () => {
if (!allPlaced) {
setError("Place every emplacement before confirming.");
return;
}
setBusy(true);
setError(null);
const payload: FobPlacement[] = FOB_FLEET.map((definition) => placements[definition.id]);
const result = await placeVersusFleet(match.matchId, payload);
setBusy(false);
if (result.success && result.data) onMatch(result.data);
else setError(result.error ?? "Could not confirm your emplacements.");
}, [allPlaced, match.matchId, onMatch, placements]);
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">
<Target className="size-4 text-amber-500" />
Emplace your fire bases
{match.you.ready && (
<span className="rounded-sm bg-emerald-600/20 px-2 py-0.5 text-xs font-medium text-emerald-300">
Emplacements confirmed
</span>
)}
</CardTitle>
<p className="text-sm text-muted-foreground">
{waiting
? "Place your emplacements while you wait, then share the match link with your opponent."
: "Place each emplacement on your board. Your opponent cannot see it."}
</p>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => {
setPlacements(randomFleet());
setError(null);
}}
>
<Shuffle /> Auto-deploy
</Button>
<Button size="sm" onClick={confirm} disabled={busy || !allPlaced}>
Confirm emplacements
</Button>
</div>
</div>
</CardHeader>
<CardContent className="flex flex-col gap-4 p-4">
{error && (
<p className="text-sm text-destructive" role="alert">
{error}
</p>
)}
<div className="flex flex-wrap gap-2">
{FOB_FLEET.map((definition) => {
const placed = Boolean(placements[definition.id]);
return (
<button
key={definition.id}
type="button"
onClick={() => setSelectedId(definition.id)}
className={cn(
"rounded-md border px-3 py-1.5 text-left text-xs transition-colors",
selectedId === definition.id
? "border-primary bg-accent"
: "border-border hover:border-primary/50",
)}
aria-pressed={selectedId === definition.id}
>
<span className="block font-medium">{definition.label}</span>
<span className="block text-muted-foreground">
{definition.size} cell{definition.size === 1 ? "" : "s"} ·{" "}
{placed ? "placed" : "unplaced"}
</span>
</button>
);
})}
<Button
variant="outline"
size="sm"
className="h-auto"
onClick={() => setOrientation((value) => (value === "h" ? "v" : "h"))}
>
<RotateCcw /> {orientation === "h" ? "Horizontal" : "Vertical"}
</Button>
</div>
<div className="overflow-auto rounded-lg border border-border bg-background p-3">
<div
className="grid gap-1"
style={{ gridTemplateColumns: `repeat(${BOARD + 1}, minmax(1.5rem, 1fr))` }}
>
<div />
{Array.from({ length: BOARD }, (_, x) => (
<div
key={`c${x}`}
className="flex items-center justify-center font-mono text-[10px] text-muted-foreground"
>
{String.fromCharCode(65 + x)}
</div>
))}
{Array.from({ length: BOARD }, (_, y) => (
<PlacementRow
key={`r${y}`}
y={y}
occupied={occupied}
preview={new Set(previewCells.map(key))}
disabled={false}
onPlace={placeAt}
/>
))}
</div>
</div>
<p className="text-xs text-muted-foreground">
Select an emplacement, then click a cell to set its anchor. Toggle orientation for the
longer assets.
</p>
</CardContent>
</Card>
);
}
function PlacementRow({
y,
occupied,
preview,
disabled,
onPlace,
}: {
y: number;
occupied: Map<string, { assetId: string; isNew: boolean }>;
preview: Set<string>;
disabled: boolean;
onPlace: (x: number, y: number) => void;
}) {
return (
<>
<div className="flex items-center justify-center font-mono text-[10px] text-muted-foreground">
{y + 1}
</div>
{Array.from({ length: BOARD }, (_, x) => {
const cell = occupied.get(`${x},${y}`);
const isPreview = preview.has(`${x},${y}`);
return (
<button
key={`${x}-${y}`}
type="button"
disabled={disabled}
aria-label={`grid ${cellLabel(x, y)}`}
onClick={() => onPlace(x, y)}
className={cn(
"flex aspect-square items-center justify-center rounded-sm border text-[10px] font-semibold transition-colors",
cell
? "border-emerald-500/70 bg-emerald-600/50 text-emerald-50"
: "border-border bg-card hover:border-primary/60",
isPreview && !cell && "border-sky-400/70 bg-sky-500/20",
disabled && "cursor-not-allowed opacity-60",
)}
>
{cell ? "▣" : ""}
</button>
);
})}
</>
);
}
/* ------------------------------------------------------------------ battle */
function buildBoards(you: VersusMatchView["you"]) {
const myCells = new Map<string, VersusFobView>();
for (const fob of you.fleet) {
for (const cell of fob.cells) myCells.set(key(cell), fob);
}
const incoming = new Map<string, VersusShotView>();
for (const shot of you.incoming) incoming.set(key(shot.grid), shot);
const myShots = new Map<string, VersusShotView>();
for (const shot of you.shots) myShots.set(key(shot.grid), shot);
return { myCells, incoming, myShots };
}
function BattlePhase({
match,
currentUserId,
onMatch,
}: {
match: VersusMatchView;
currentUserId: number | string;
onMatch: (next: VersusMatchView) => void;
}) {
const you = match.you;
const now = useNow();
const [rangeM, setRangeM] = useState(0);
const [deflectionM, setDeflectionM] = useState(0);
const [pendingGrid, setPendingGrid] = useState<GridPoint | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const yourTurn = match.turnUserId !== null && String(match.turnUserId) === String(currentUserId);
const boards = buildBoards(you);
const firstShot = you.lastImpact === null;
const secondsLeft =
match.turnDeadline === null
? null
: Math.max(0, Math.round((Date.parse(match.turnDeadline) - now) / 1000));
const fire = useCallback(async () => {
setBusy(true);
setError(null);
const input: VersusShotInput = firstShot
? pendingGrid
? { kind: "grid", grid: pendingGrid }
: { kind: "grid", grid: { x: 0, y: 0 } }
: { kind: "correction", rangeM, deflectionM };
if (firstShot && !pendingGrid) {
setBusy(false);
setError("Click the enemy grid to designate a target reference.");
return;
}
const result = await fireVersusShot(match.matchId, input);
setBusy(false);
if (result.success && result.data) {
onMatch(result.data);
setPendingGrid(null);
setRangeM(0);
setDeflectionM(0);
} else {
setError(result.error ?? "The fire mission was rejected.");
}
}, [
deflectionM,
firstShot,
match.matchId,
onMatch,
pendingGrid,
rangeM,
]);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-card px-4 py-3">
<div className="flex items-center gap-2 text-sm">
<Users className="size-4 text-muted-foreground" />
<span className="font-medium">
You vs {you.opponentName}
</span>
</div>
<div className="flex items-center gap-3 text-sm">
{yourTurn ? (
<span className="font-semibold text-emerald-400">Your turn: call fire</span>
) : (
<span className="text-muted-foreground">Waiting for {you.opponentName}…</span>
)}
{secondsLeft !== null && (
<span className="flex items-center gap-1 font-mono tabular-nums text-muted-foreground">
<Clock className="size-4" />
{secondsLeft}s
</span>
)}
</div>
</div>
{error && (
<p className="text-sm text-destructive" role="alert">
{error}
</p>
)}
<div className="grid gap-4 lg:grid-cols-2">
<BoardPanel
title="Your fire bases"
subtitle="Incoming rounds are marked. Emplacements turn red when reduced."
>
{Array.from({ length: BOARD }, (_, y) => (
<ReadOnlyRow key={y} y={y}>
{Array.from({ length: BOARD }, (_, x) => {
const fob = boards.myCells.get(`${x},${y}`);
const hit = boards.incoming.get(`${x},${y}`);
const destroyed = fob ? fob.hitCells.length >= fob.size : false;
return (
<ReadOnlyCell
key={`${x}-${y}`}
label={`grid ${cellLabel(x, y)}`}
className={cn(
fob && "border-emerald-500/70 bg-emerald-600/40 text-emerald-50",
destroyed && "border-red-500/70 bg-red-600/50 text-red-50",
)}
>
{fob ? "▣" : ""}
{hit && (
<span
className={cn(
"absolute text-[11px] font-bold",
hit.outcome === "miss" ? "text-sky-300" : "text-red-300",
)}
>
{hit.outcome === "miss" ? "•" : "✕"}
</span>
)}
</ReadOnlyCell>
);
})}
</ReadOnlyRow>
))}
</BoardPanel>
<BoardPanel
title="Enemy sector"
subtitle={
firstShot
? "Click a cell to designate your first target."
: "Markers show where your rounds have landed."
}
>
{Array.from({ length: BOARD }, (_, y) => (
<ReadOnlyRow key={y} y={y}>
{Array.from({ length: BOARD }, (_, x) => {
const shot = boards.myShots.get(`${x},${y}`);
const pending = pendingGrid && pendingGrid.x === x && pendingGrid.y === y;
return (
<ReadOnlyCell
key={`${x}-${y}`}
label={`grid ${cellLabel(x, y)}`}
className={cn(
(shot?.outcome === "hit" || shot?.outcome === "destroyed") &&
"border-amber-500/70 bg-amber-500/20 text-amber-200",
shot?.outcome === "destroyed" && "border-red-500/70 bg-red-600/40 text-red-50",
pending && "border-sky-400 ring-2 ring-sky-400/60",
)}
interactive={Boolean(yourTurn && firstShot)}
onClick={() => setPendingGrid({ x, y })}
>
{pending ? "◉" : shot ? (shot.outcome === "miss" ? "•" : "✕") : ""}
</ReadOnlyCell>
);
})}
</ReadOnlyRow>
))}
</BoardPanel>
</div>
<Card>
<CardHeader className="border-b p-4">
<CardTitle className="flex items-center gap-2 text-sm">
<Crosshair className="size-4 text-amber-500" />
{firstShot ? "First fire mission" : "Adjust fire"}
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 p-4">
{firstShot ? (
<p className="text-sm text-muted-foreground">
{pendingGrid
? `Target reference ${cellLabel(pendingGrid.x, pendingGrid.y)} selected.`
: "Click a cell on the enemy sector to set your first target reference."}
</p>
) : (
<>
<CorrectionField
id="versus-range"
label="Range (+ ADD / - DROP)"
value={rangeM}
disabled={!yourTurn}
onChange={setRangeM}
/>
<CorrectionField
id="versus-deflection"
label="Deflection (+ RIGHT / - LEFT)"
value={deflectionM}
disabled={!yourTurn}
onChange={setDeflectionM}
/>
<p className="text-[10px] text-muted-foreground">
1 cell = {METERS_PER_CELL}m. Adjust from your last impact at{" "}
{you.lastImpact ? cellLabel(you.lastImpact.x, you.lastImpact.y) : "—"}.
</p>
</>
)}
<Button onClick={fire} disabled={!yourTurn || busy}>
Fire mission
</Button>
</CardContent>
</Card>
<ShotLog shots={you.shots} />
</div>
);
}
function BoardPanel({
title,
subtitle,
children,
}: {
title: string;
subtitle: string;
children: React.ReactNode;
}) {
return (
<Card>
<CardHeader className="border-b p-3">
<CardTitle className="text-sm">{title}</CardTitle>
<p className="text-xs text-muted-foreground">{subtitle}</p>
</CardHeader>
<CardContent className="p-3">
<div
className="grid gap-1"
style={{ gridTemplateColumns: `repeat(${BOARD + 1}, minmax(1.4rem, 1fr))` }}
>
<div />
{Array.from({ length: BOARD }, (_, x) => (
<div
key={`c${x}`}
className="flex items-center justify-center font-mono text-[10px] text-muted-foreground"
>
{String.fromCharCode(65 + x)}
</div>
))}
{children}
</div>
</CardContent>
</Card>
);
}
function ReadOnlyRow({ y, children }: { y: number; children: React.ReactNode }) {
return (
<>
<div className="flex items-center justify-center font-mono text-[10px] text-muted-foreground">
{y + 1}
</div>
{children}
</>
);
}
function ReadOnlyCell({
label,
className,
interactive,
children,
onClick,
}: {
label: string;
className?: string;
interactive?: boolean;
children?: React.ReactNode;
onClick?: () => void;
}) {
return (
<button
type="button"
aria-label={label}
disabled={!interactive}
onClick={onClick}
className={cn(
"relative flex aspect-square items-center justify-center rounded-sm border border-border bg-card text-[10px] transition-colors",
interactive && "hover:border-primary/60",
className,
)}
>
{children}
</button>
);
}
function ShotLog({ shots }: { shots: VersusShotView[] }) {
return (
<Card>
<CardHeader className="border-b p-3">
<CardTitle className="text-sm">Fire mission log</CardTitle>
</CardHeader>
<CardContent className="p-3">
{shots.length === 0 ? (
<p className="text-xs text-muted-foreground">No rounds fired yet.</p>
) : (
<ul className="space-y-1 font-mono text-xs tabular-nums">
{[...shots].reverse().map((shot, index) => (
<li
key={`${index}-${shot.grid.x}-${shot.grid.y}`}
className={cn(
shot.outcome === "miss" ? "text-muted-foreground" : "text-amber-300",
shot.outcome === "destroyed" && "font-semibold text-red-400",
)}
>
&gt; {cellLabel(shot.grid.x, shot.grid.y)} ·{" "}
{shot.outcome === "miss"
? "miss"
: shot.outcome === "destroyed"
? "emplacement destroyed"
: "hit"}
</li>
))}
</ul>
)}
</CardContent>
</Card>
);
}
function CorrectionField({
id,
label,
value,
disabled,
onChange,
}: {
id: string;
label: string;
value: number;
disabled: boolean;
onChange: (next: number) => void;
}) {
const clamp = (next: number) => Math.min(2000, Math.max(-2000, next));
return (
<div className="flex flex-col gap-1">
<label htmlFor={id} className="text-xs text-muted-foreground">
{label}
</label>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="sm"
className="size-8 shrink-0 p-0"
disabled={disabled}
aria-label={`Decrease ${label}`}
onClick={() => onChange(clamp(value - CORRECTION_STEP))}
>
-{CORRECTION_STEP}
</Button>
<Input
id={id}
type="number"
step={CORRECTION_STEP}
value={value}
disabled={disabled}
className="h-8 text-center font-mono tabular-nums"
onChange={(event) => {
const parsed = Number(event.target.value);
onChange(Number.isFinite(parsed) ? clamp(Math.round(parsed)) : 0);
}}
/>
<Button
type="button"
variant="outline"
size="sm"
className="size-8 shrink-0 p-0"
disabled={disabled}
aria-label={`Increase ${label}`}
onClick={() => onChange(clamp(value + CORRECTION_STEP))}
>
+{CORRECTION_STEP}
</Button>
</div>
</div>
);
}
/* ------------------------------------------------------------------ result */
function ResultPanel({
match,
currentUserId,
onLeave,
}: {
match: VersusMatchView;
currentUserId: number | string;
onLeave: () => void;
}) {
const you = match.you;
const result = match.result;
const won = result?.winnerUserId !== null && String(result?.winnerUserId) === String(currentUserId);
const draw = result?.winnerUserId === null;
return (
<Card className={cn(won ? "border-emerald-500/40" : draw ? "border-border" : "border-destructive/40")}>
<CardHeader className="border-b p-4">
<CardTitle className="flex items-center gap-2 text-sm">
<Trophy className="size-4 text-amber-400" />
{draw ? "Draw" : won ? "Victory" : "Defeat"}
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 p-4">
<p className="text-sm">
{draw
? "Both sectors held. No victor on points."
: won
? `You reduced ${you.opponentName}'s sector.`
: `${you.opponentName} reduced your sector.`}
</p>
<div className="flex flex-wrap gap-4 text-sm text-muted-foreground">
<span>
Emplacements destroyed:{" "}
<span className="font-semibold text-foreground">{you.fobsDestroyed}</span>
</span>
<span>
Cells struck:{" "}
<span className="font-semibold text-foreground">{you.cellsHit}</span>
</span>
<span>
Rounds fired:{" "}
<span className="font-semibold text-foreground">{you.shots.length}</span>
</span>
</div>
<div>
<Button onClick={onLeave}>Return to lobby</Button>
</div>
</CardContent>
</Card>
);
}
/* ------------------------------------------------------------------- shell */
export function VersusMatch({
match,
currentUserId,
onMatch,
onLeave,
operatorsOnline,
}: {
match: VersusMatchView;
currentUserId: number | string;
onMatch: (next: VersusMatchView) => void;
onLeave: () => void;
operatorsOnline: string[];
}) {
const waiting = match.you.opponentUserId === VERSUS_WAITING_USER_ID;
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-sm font-semibold">{match.name ?? "Artillery duel"}</h2>
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<span>
{operatorsOnline.length} operator{operatorsOnline.length === 1 ? "" : "s"} on the net
</span>
<Button variant="outline" size="sm" onClick={onLeave}>
Leave match
</Button>
</div>
</div>
{match.phase === "placing" ? (
<PlacementPhase match={match} onMatch={onMatch} waiting={waiting} />
) : match.phase === "complete" ? (
<ResultPanel match={match} currentUserId={currentUserId} onLeave={onLeave} />
) : (
<BattlePhase match={match} currentUserId={currentUserId} onMatch={onMatch} />
)}
</div>
);
}

View file

@ -7,6 +7,7 @@ import {
Gamepad2,
Radio,
Spade,
Swords,
Target,
type LucideIcon,
} from "lucide-react";
@ -25,6 +26,7 @@ const ICONS: Record<string, LucideIcon> = {
Crosshair,
FileTextIcon,
Target,
Swords,
Spade,
Club,
Gamepad2,

View file

@ -9,6 +9,7 @@ Five XP-earning minigames under one parent: routes live at `/minigames/*` (moved
- **Radio Traffic**: `/minigames/radio`, sprint + watch modes, procedural message generation (`src/components/frontend/minigames/radio/messageGenerator.ts`). Action `submitRadioResult` emits `minigame:radio-traffic`; stats under `progression.minigames.radioTraffic` (incl. `bestSprintTimeMs`).
- **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`).
- 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,62 @@
/**
* Tunables for the Call for Fire versus mode (head-to-head artillery duel).
* Pure and client-safe: no Payload or Node imports.
*/
import type { GridPoint } from "@/lib/minigames/call-for-fire";
/** Board is size x size cells; one cell is one 50m grid square (see the CFF lib). */
export const VERSUS_BOARD_SIZE = 10;
/** Seconds a player has to call their next fire mission before the turn is skipped. */
export const VERSUS_TURN_SECONDS = 60;
export const VERSUS_TURN_TIMEOUT_MS = VERSUS_TURN_SECONDS * 1000;
/** Safety cap on rounds each player may fire before the match ends on points. */
export const VERSUS_MAX_SHOTS_PER_PLAYER = 40;
/** Live matches: registry cap and idle expiry (mirrors the blackjack registry). */
export const VERSUS_MAX_MATCHES = 20;
export const VERSUS_MATCH_EXPIRY_MS = 5 * 60_000;
export const VERSUS_SWEEP_INTERVAL_MS = 30_000;
/** Longest match name accepted by the rename/create path. */
export const VERSUS_MAX_NAME_LENGTH = 40;
/** Sentinel userId for the empty seat in a waiting match (never a real user). */
export const VERSUS_WAITING_USER_ID = 0;
export interface FobDefinition {
readonly id: string;
readonly label: string;
/** Occupied cells when placed, laid out in a straight line. */
readonly size: number;
}
/**
* The emplacement fleet each player hides. A shorter list keeps a duel brisk;
* total occupied cells are 8 of 100, so rounds matter without dragging.
*/
export const FOB_FLEET: readonly FobDefinition[] = [
{ id: "command-post", label: "Command Post", size: 3 },
{ id: "ammo-depot", label: "Ammo Depot", size: 2 },
{ id: "radar-site", label: "Radar Site", size: 2 },
{ id: "fob", label: "Forward Operating Base", size: 1 },
];
export type FobOrientation = "h" | "v";
export interface FobPlacement {
readonly assetId: string;
readonly origin: GridPoint;
readonly orientation: FobOrientation;
}
/** Scoring: emplacements destroyed dominate; cells struck break ties. */
export const VERSUS_SCORE_PER_FOB = 100;
export const VERSUS_SCORE_PER_CELL = 1;
/** XP payout on match completion. */
export const VERSUS_XP_WIN = 40;
export const VERSUS_XP_LOSS = 10;
export const VERSUS_XP_PER_FOB = 5;

View file

@ -0,0 +1,307 @@
/**
* Pure rules for the Call for Fire versus mode. No I/O, no timers, no Payload:
* the server registry (./registry.ts) owns live match records and calls these
* functions, and unit tests drive them directly.
*
* Every mutator returns a NEW state; the registry assigns `record.state`.
*/
import { applyCorrection, clampPoint, type GridPoint } from "@/lib/minigames/call-for-fire";
import {
FOB_FLEET,
VERSUS_BOARD_SIZE,
VERSUS_MAX_SHOTS_PER_PLAYER,
VERSUS_SCORE_PER_CELL,
VERSUS_SCORE_PER_FOB,
type FobOrientation,
type FobPlacement,
} from "./constants";
import type {
ShotOutcome,
VersusEndReason,
VersusFob,
VersusPlayerState,
VersusShot,
VersusState,
} from "./types";
export type VersusShotInput =
| { readonly kind: "grid"; readonly grid: GridPoint }
| { readonly kind: "correction"; readonly rangeM: number; readonly deflectionM: number };
function freshPlayer(userId: number, name: string): VersusPlayerState {
return {
userId,
name,
fleet: null,
ready: false,
lastImpact: null,
shots: [],
cellsHit: 0,
fobsDestroyed: 0,
};
}
/** A fresh match in the placement phase (both players emplace their fleets). */
export function createVersusState(
a: { userId: number; name: string },
b: { userId: number; name: string },
): VersusState {
return {
boardSize: VERSUS_BOARD_SIZE,
phase: "placing",
players: [freshPlayer(a.userId, a.name), freshPlayer(b.userId, b.name)],
turn: null,
winner: null,
reason: null,
shotsFired: 0,
startedAt: null,
completedAt: null,
};
}
/** Cells a straight-line emplacement covers, or null when it runs off the board. */
export function cellsForPlacement(
origin: GridPoint,
orientation: FobOrientation,
size: number,
boardSize: number,
): GridPoint[] | null {
const cells: GridPoint[] = [];
for (let i = 0; i < size; i += 1) {
const x = orientation === "h" ? origin.x + i : origin.x;
const y = orientation === "v" ? origin.y + i : origin.y;
if (x < 0 || y < 0 || x >= boardSize || y >= boardSize) return null;
cells.push({ x, y });
}
return cells;
}
function cellKey(point: GridPoint): string {
return `${point.x},${point.y}`;
}
/** Validate a full fleet placement and build the hidden fleet. */
export function buildFleet(
placements: readonly FobPlacement[],
boardSize: number,
): { fleet: VersusFob[] } | { error: string } {
const byId = new Map(placements.map((placement) => [placement.assetId, placement]));
const occupied = new Set<string>();
const fleet: VersusFob[] = [];
for (const definition of FOB_FLEET) {
const placement = byId.get(definition.id);
if (!placement) return { error: `Missing emplacement: ${definition.label}.` };
const cells = cellsForPlacement(
placement.origin,
placement.orientation,
definition.size,
boardSize,
);
if (!cells) return { error: `${definition.label} does not fit there.` };
for (const cell of cells) {
const key = cellKey(cell);
if (occupied.has(key)) return { error: "Emplacements cannot overlap." };
occupied.add(key);
}
fleet.push({
id: definition.id,
label: definition.label,
size: definition.size,
cells,
hitCells: [],
});
}
const unknown = placements.find(
(placement) => !FOB_FLEET.some((definition) => definition.id === placement.assetId),
);
if (unknown) return { error: `Unknown emplacement: ${unknown.assetId}.` };
return { fleet };
}
function replacePlayers(
state: VersusState,
index: 0 | 1,
override: Partial<VersusPlayerState>,
): [VersusPlayerState, VersusPlayerState] {
const updated = { ...state.players[index], ...override };
return index === 0 ? [updated, state.players[1]] : [state.players[0], updated];
}
/** Emplace a player's fleet; the battle starts once both are ready. */
export function placeFleet(
state: VersusState,
index: 0 | 1,
placements: readonly FobPlacement[],
now: Date = new Date(),
): { state: VersusState } | { error: string } {
if (state.phase !== "placing") return { error: "Emplacement is closed." };
const built = buildFleet(placements, state.boardSize);
if ("error" in built) return { error: built.error };
const players = replacePlayers(state, index, { fleet: built.fleet, ready: true });
let next: VersusState = { ...state, players };
if (next.players[0].ready && next.players[1].ready) {
next = { ...next, phase: "battle", turn: 0, startedAt: now.toISOString() };
}
return { state: next };
}
/** Seat (or re-seat) a player in a slot, clearing any prior fleet. */
export function seatPlayer(
state: VersusState,
index: 0 | 1,
user: { userId: number; name: string },
): VersusState {
const players = replacePlayers(state, index, {
userId: user.userId,
name: user.name,
fleet: null,
ready: false,
});
return { ...state, players };
}
/** Score a player's performance this match: emplacements destroyed then cells. */export function scoreOf(player: VersusPlayerState): number {
return player.fobsDestroyed * VERSUS_SCORE_PER_FOB + player.cellsHit * VERSUS_SCORE_PER_CELL;
}
function decideWinnerByScore(players: [VersusPlayerState, VersusPlayerState]): 0 | 1 | null {
const zero = scoreOf(players[0]);
const one = scoreOf(players[1]);
if (zero === one) return null;
return zero > one ? 0 : 1;
}
function complete(
state: VersusState,
winner: 0 | 1 | null,
reason: VersusEndReason,
now: Date,
): VersusState {
return {
...state,
phase: "complete",
turn: null,
winner,
reason,
completedAt: now.toISOString(),
};
}
/**
* Resolve one fire mission for the acting player. The first shot of a match is
* a grid designation; every shot after adjusts from that player's last impact
* (range + deflection), matching the single-player Call for Fire controls.
*
* Hits are exact-cell: a round lands on an emplacement cell. The opponent's
* layout never leaves this function except as the returned outcome.
*/
export function fireShot(
state: VersusState,
index: 0 | 1,
input: VersusShotInput,
now: Date = new Date(),
): { state: VersusState; shot: VersusShot } | { error: string } {
if (state.phase !== "battle") return { error: "The battle is not underway." };
if (state.turn !== index) return { error: "It is not your turn." };
const player = state.players[index];
const opponentIndex: 0 | 1 = index === 0 ? 1 : 0;
const opponent = state.players[opponentIndex];
if (!opponent.fleet) return { error: "The opponent has not emplaced a fleet." };
let impact: GridPoint;
if (player.lastImpact === null) {
if (input.kind !== "grid") {
return { error: "Call a grid reference for your first fire mission." };
}
impact = clampPoint(input.grid, state.boardSize);
} else {
if (input.kind !== "correction") {
return { error: "Adjust from your last impact using range and deflection." };
}
impact = applyCorrection(
player.lastImpact,
{ rangeM: input.rangeM, deflectionM: input.deflectionM },
state.boardSize,
);
}
const targetIndex = opponent.fleet.findIndex((fob) =>
fob.cells.some((cell) => cell.x === impact.x && cell.y === impact.y),
);
let outcome: ShotOutcome = "miss";
let assetId: string | null = null;
let newCell = false;
let destroyedNow = false;
let nextFleet = opponent.fleet;
if (targetIndex >= 0) {
const target = opponent.fleet[targetIndex];
assetId = target.id;
const alreadyHit = target.hitCells.some((cell) => cell.x === impact.x && cell.y === impact.y);
if (alreadyHit) {
outcome = "hit";
} else {
newCell = true;
const hitCells = [...target.hitCells, impact];
destroyedNow = hitCells.length >= target.size;
outcome = destroyedNow ? "destroyed" : "hit";
nextFleet = opponent.fleet.map((fob, i) => (i === targetIndex ? { ...fob, hitCells } : fob));
}
}
const shot: VersusShot = { grid: impact, outcome, assetId };
const updatedPlayer: VersusPlayerState = {
...player,
lastImpact: impact,
shots: [...player.shots, shot],
cellsHit: player.cellsHit + (newCell ? 1 : 0),
fobsDestroyed: player.fobsDestroyed + (destroyedNow ? 1 : 0),
};
const updatedOpponent: VersusPlayerState = { ...opponent, fleet: nextFleet };
const players: [VersusPlayerState, VersusPlayerState] =
index === 0 ? [updatedPlayer, updatedOpponent] : [updatedOpponent, updatedPlayer];
let next: VersusState = { ...state, players, shotsFired: state.shotsFired + 1 };
const opponentDead = (updatedOpponent.fleet ?? []).every(
(fob) => fob.hitCells.length >= fob.size,
);
if (opponentDead) {
return { state: complete(next, index, "eliminated", now), shot };
}
if (next.shotsFired >= VERSUS_MAX_SHOTS_PER_PLAYER * 2) {
return { state: complete(next, decideWinnerByScore(players), "cap", now), shot };
}
next = { ...next, turn: opponentIndex };
return { state: next, shot };
}
/** Pass the turn (turn timeout). No shot is fired. */
export function skipTurn(state: VersusState): VersusState {
if (state.phase !== "battle" || state.turn === null) return state;
return { ...state, turn: state.turn === 0 ? 1 : 0 };
}
/** Concede: the opponent wins. */
export function resign(
state: VersusState,
index: 0 | 1,
now: Date = new Date(),
): { state: VersusState } | { error: string } {
if (state.phase === "complete") return { error: "The match is already over." };
const opponentIndex: 0 | 1 = index === 0 ? 1 : 0;
return { state: complete(state, opponentIndex, "resigned", now) };
}
/** True when every emplacement in a fleet has been reduced. */
export function isFleetDestroyed(fleet: readonly VersusFob[]): boolean {
return fleet.every((fob) => fob.hitCells.length >= fob.size);
}

View file

@ -0,0 +1,10 @@
/**
* Public API of the pure Call for Fire versus 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,351 @@
/**
* Server-side match registry for the Call for Fire versus mode.
*
* 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; the SSE pipeline it pushes through has the same limitation.
*
* The pure engine (./engine, ./views) never touches timers or I/O. This wrapper
* owns turn timeouts, lobby broadcasts, per-user snapshot pushes, match
* completion rewards, and the expiry sweep.
*/
import { getPayload } from "payload";
import type { Payload } from "payload";
import { broadcast, broadcastToUser } from "@/lib/realtime/bus";
import { generateTableName } from "@/lib/minigames/tableNames";
import {
VERSUS_MAX_MATCHES,
VERSUS_MAX_NAME_LENGTH,
VERSUS_MATCH_EXPIRY_MS,
VERSUS_SWEEP_INTERVAL_MS,
VERSUS_TURN_TIMEOUT_MS,
VERSUS_WAITING_USER_ID,
type FobPlacement,
} from "./constants";
import {
createVersusState,
fireShot,
placeFleet,
resign,
seatPlayer,
skipTurn,
type VersusShotInput,
} from "./engine";
import { awardVersusResult, type VersusMatchResult } from "./stats";
import type { VersusMatchSummary, VersusMatchView, VersusState } from "./types";
import { buildVersusView } from "./views";
const MAX_SEATS = 2;
interface VersusMatchRecord {
id: string;
name: string | null;
version: number;
hostUserId: number;
seatMap: [number | null, number | null];
state: VersusState;
userNames: Map<number, string>;
awarded: boolean;
turnTimer: ReturnType<typeof setTimeout> | null;
turnTimerVersion: number | null;
turnDeadlineAt: string | null;
createdAt: string;
lastActivityAt: number;
}
type VersusMatchesStore = Map<string, VersusMatchRecord>;
interface VersusGlobalRegistry {
__cffVersusMatches?: VersusMatchesStore;
}
const globalRegistry = globalThis as typeof globalThis & VersusGlobalRegistry;
const matches: VersusMatchesStore = (globalRegistry.__cffVersusMatches ??= new Map());
function indexOfUser(record: VersusMatchRecord, userId: number): 0 | 1 | null {
if (record.seatMap[0] === userId) return 0;
if (record.seatMap[1] === userId) return 1;
return null;
}
function seatedCountOf(record: VersusMatchRecord): number {
return record.seatMap.filter((id) => id !== null).length;
}
async function getPayloadOrNull(): Promise<Payload | null> {
try {
const config = (await import("@payload-config")).default;
return await getPayload({ config });
} catch {
return null;
}
}
function clearTurnTimer(record: VersusMatchRecord): void {
if (record.turnTimer) clearTimeout(record.turnTimer);
record.turnTimer = null;
record.turnTimerVersion = null;
record.turnDeadlineAt = null;
}
function scheduleTurnTimer(record: VersusMatchRecord): void {
clearTurnTimer(record);
if (record.state.phase !== "battle" || record.state.turn === null) return;
record.turnTimerVersion = record.version;
record.turnDeadlineAt = new Date(Date.now() + VERSUS_TURN_TIMEOUT_MS).toISOString();
record.turnTimer = setTimeout(() => onTurnTimeout(record), VERSUS_TURN_TIMEOUT_MS);
}
function onTurnTimeout(record: VersusMatchRecord): void {
const scheduledVersion = record.turnTimerVersion;
record.turnTimer = null;
record.turnTimerVersion = null;
record.turnDeadlineAt = null;
if (scheduledVersion === null || scheduledVersion !== record.version) return;
record.state = skipTurn(record.state);
record.version += 1;
afterMutation(record);
}
function matchResults(state: VersusState): VersusMatchResult[] {
return state.players
.filter((player) => player.userId !== VERSUS_WAITING_USER_ID)
.map((player) => ({
userId: player.userId,
won: state.winner !== null && state.players[state.winner].userId === player.userId,
fobsDestroyed: player.fobsDestroyed,
cellsHit: player.cellsHit,
}));
}
/** Fire-and-forget reward for a completed match; idempotent per record. */
function awardCompleted(record: VersusMatchRecord): 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 awardVersusResult(payload, record.id, results);
})();
}
function afterMutation(record: VersusMatchRecord): void {
if (record.state.phase === "battle") {
scheduleTurnTimer(record);
} else {
clearTurnTimer(record);
}
if (record.state.phase === "complete") awardCompleted(record);
push(record);
}
function buildView(record: VersusMatchRecord, index: 0 | 1): VersusMatchView {
return {
matchId: record.id,
name: record.name,
version: record.version,
turnDeadline: record.turnDeadlineAt,
...buildVersusView(record.state, index),
};
}
function listSummaries(viewerId?: number): VersusMatchSummary[] {
return [...matches.values()].map((record) => ({
matchId: record.id,
name: record.name,
hostName: record.userNames.get(record.hostUserId) ?? "Unknown",
guestName:
record.seatMap[1] !== null ? (record.userNames.get(record.seatMap[1]) ?? null) : null,
seatedCount: seatedCountOf(record),
maxSeats: MAX_SEATS,
phase: seatedCountOf(record) < 2 ? "waiting" : record.state.phase,
createdAt: record.createdAt,
joined: viewerId !== undefined && indexOfUser(record, viewerId) !== null,
}));
}
function push(record: VersusMatchRecord): void {
for (const userId of record.seatMap) {
if (userId === null || userId === VERSUS_WAITING_USER_ID) continue;
const index = indexOfUser(record, userId);
if (index === null) continue;
broadcastToUser("cff-versus-match", userId, {
matchId: record.id,
view: buildView(record, index),
});
}
broadcast("cff-versus-matches", { matches: listSummaries() });
}
function disposeMatch(record: VersusMatchRecord): void {
clearTurnTimer(record);
awardCompleted(record);
matches.delete(record.id);
broadcast("cff-versus-matches", { matches: listSummaries() });
}
/* ------------------------------------------------------------------ public */
export function createMatch(userId: number, displayName: string): string {
if (matches.size >= VERSUS_MAX_MATCHES) {
throw new Error("The maximum number of live matches exists. Try again later.");
}
for (const existing of matches.values()) {
if (indexOfUser(existing, userId) !== null) {
throw new Error("You are already in a match. Leave it first.");
}
}
const record: VersusMatchRecord = {
id: crypto.randomUUID(),
name: generateTableName(),
version: 1,
hostUserId: userId,
seatMap: [userId, null],
state: createVersusState(
{ userId, name: displayName },
{ userId: VERSUS_WAITING_USER_ID, name: "Waiting for an opponent" },
),
userNames: new Map([[userId, displayName]]),
awarded: false,
turnTimer: null,
turnTimerVersion: null,
turnDeadlineAt: null,
createdAt: new Date().toISOString(),
lastActivityAt: Date.now(),
};
matches.set(record.id, record);
push(record);
return record.id;
}
export function listMatchSummaries(viewerId?: number): VersusMatchSummary[] {
return listSummaries(viewerId);
}
export function joinMatch(matchId: string, userId: number, displayName: string): VersusMatchView {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
const existing = indexOfUser(record, userId);
if (existing !== null) return buildView(record, existing);
for (const other of matches.values()) {
if (other.id !== record.id && indexOfUser(other, userId) !== null) {
throw new Error("You are already in another match. Leave it first.");
}
}
if (record.seatMap[1] !== null) throw new Error("This match is already full.");
if (record.state.phase !== "placing") throw new Error("This match has already started.");
record.seatMap[1] = userId;
record.userNames.set(userId, displayName);
record.state = seatPlayer(record.state, 1, { userId, name: displayName });
record.lastActivityAt = Date.now();
record.version += 1;
push(record);
return buildView(record, 1);
}
export function getSnapshotFor(matchId: string, userId: number): VersusMatchView {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
const index = indexOfUser(record, userId);
if (index === null) throw new Error("You are not in this match.");
record.lastActivityAt = Date.now();
return buildView(record, index);
}
export function placeFleetFor(
matchId: string,
userId: number,
placements: readonly FobPlacement[],
): VersusMatchView {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
const index = indexOfUser(record, userId);
if (index === null) throw new Error("You are not in this match.");
const result = placeFleet(record.state, index, placements);
if ("error" in result) throw new Error(result.error);
record.state = result.state;
record.lastActivityAt = Date.now();
record.version += 1;
afterMutation(record);
return buildView(record, index);
}
export function fireShotFor(
matchId: string,
userId: number,
input: VersusShotInput,
): VersusMatchView {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
const index = indexOfUser(record, userId);
if (index === null) throw new Error("You are not in this match.");
const result = fireShot(record.state, index, input);
if ("error" in result) throw new Error(result.error);
record.state = result.state;
record.lastActivityAt = Date.now();
record.version += 1;
afterMutation(record);
return buildView(record, index);
}
export function leaveMatch(matchId: string, userId: number): void {
const record = matches.get(matchId);
if (!record) return;
const index = indexOfUser(record, userId);
if (index === null) return;
if (record.state.phase === "battle") {
const resigned = resign(record.state, index);
if (!("error" in resigned)) {
record.state = resigned.state;
record.version += 1;
}
}
record.seatMap[index] = null;
record.userNames.delete(userId);
record.lastActivityAt = Date.now();
record.version += 1;
if (seatedCountOf(record) === 0) {
disposeMatch(record);
return;
}
afterMutation(record);
}
export function forceExpireMatch(matchId: string): void {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
disposeMatch(record);
}
function sweepExpiredMatches(): void {
const now = Date.now();
let expired = false;
for (const record of [...matches.values()]) {
if (now - record.lastActivityAt <= VERSUS_MATCH_EXPIRY_MS) continue;
disposeMatch(record);
expired = true;
}
if (expired) broadcast("cff-versus-matches", { matches: listSummaries() });
}
const sweepInterval = setInterval(sweepExpiredMatches, VERSUS_SWEEP_INTERVAL_MS);
sweepInterval.unref?.();
/** Test-only helper: drop every match without awards. */
export function clearMatchesForTests(): void {
for (const record of matches.values()) clearTurnTimer(record);
matches.clear();
}
export { VERSUS_MAX_NAME_LENGTH };
export type { VersusMatchView, VersusMatchSummary };

View file

@ -0,0 +1,151 @@
/**
* Call for Fire versus: XP + profile-stats awarding (Payload-dependent,
* server-only). The match registry calls `awardVersusResult` 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 {
VERSUS_SCORE_PER_CELL,
VERSUS_SCORE_PER_FOB,
VERSUS_XP_LOSS,
VERSUS_XP_PER_FOB,
VERSUS_XP_WIN,
} from "./constants";
export interface VersusMatchResult {
userId: number;
won: boolean;
fobsDestroyed: number;
cellsHit: number;
}
export interface VersusStats {
gamesPlayed: number;
wins: number;
losses: number;
bestScore: number;
xpEarned: number;
}
/** Match performance score: emplacements destroyed then cells struck. */
export function versusScore(fobsDestroyed: number, cellsHit: number): number {
return fobsDestroyed * VERSUS_SCORE_PER_FOB + cellsHit * VERSUS_SCORE_PER_CELL;
}
/** XP for a completed match: win/loss base plus a bounty per emplacement destroyed. */
export function xpForVersus(won: boolean, fobsDestroyed: number): number {
return (won ? VERSUS_XP_WIN : VERSUS_XP_LOSS) + fobsDestroyed * VERSUS_XP_PER_FOB;
}
/** Defensive reader for `progression.minigames.callForFireVersus`. */
export function readVersusStats(profile: unknown): VersusStats {
const group =
(
profile as {
progression?: { minigames?: { callForFireVersus?: Partial<VersusStats> } };
}
)?.progression?.minigames?.callForFireVersus ?? {};
return {
gamesPlayed: group.gamesPlayed ?? 0,
wins: group.wins ?? 0,
losses: group.losses ?? 0,
bestScore: group.bestScore ?? 0,
xpEarned: group.xpEarned ?? 0,
};
}
/** Pure stat transition for one finished match. */
export function computeVersusStatsDelta(current: VersusStats, result: VersusMatchResult): VersusStats {
const xp = xpForVersus(result.won, result.fobsDestroyed);
return {
gamesPlayed: current.gamesPlayed + 1,
wins: current.wins + (result.won ? 1 : 0),
losses: current.losses + (result.won ? 0 : 1),
bestScore: Math.max(current.bestScore, versusScore(result.fobsDestroyed, result.cellsHit)),
xpEarned: current.xpEarned + xp,
};
}
/**
* Award XP, chips, and versus stats for both players of a finished match.
* Emits a single event log entry naming the winner.
*/
export async function awardVersusResult(
payload: Payload,
matchId: string,
results: VersusMatchResult[],
): Promise<{ xpByUser: Record<number, number> }> {
const xpByUser: Record<number, number> = {};
for (const result of results) {
const xp = xpForVersus(result.won, result.fobsDestroyed);
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(`Call for Fire versus: no profile for user ${result.userId}`);
continue;
}
const current = readVersusStats(profile);
const next = computeVersusStatsDelta(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, callForFireVersus: 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(
`Call for Fire versus: failed to award result for user ${result.userId}: ${message}`,
);
}
}
const winner = results.find((result) => result.won);
await emitGameEvent(payload, {
type: EventTypes.MinigameCallForFireVersus,
message: winner
? `won an artillery duel (match ${matchId.slice(0, 8)})`
: `fought an artillery duel to a draw (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,128 @@
/**
* Types for the Call for Fire versus mode. Pure and client-safe.
*
* The full match state (both players' hidden emplacement fleets) lives only on
* the server. Clients receive `VersusStateView`, which exposes the viewer's own
* fleet and both shot logs but NEVER the opponent's fleet layout.
*/
import type { GridPoint } from "@/lib/minigames/call-for-fire";
export type VersusPhase = "placing" | "battle" | "complete";
export type ShotOutcome = "miss" | "hit" | "destroyed";
export type VersusEndReason = "eliminated" | "resigned" | "cap";
/** A hidden emplacement on one player's board. */
export interface VersusFob {
readonly id: string;
readonly label: string;
readonly size: number;
readonly cells: GridPoint[];
/** Distinct cells struck so far. */
readonly hitCells: GridPoint[];
}
export interface VersusShot {
/** Where the round landed. */
readonly grid: GridPoint;
readonly outcome: ShotOutcome;
/** Emplacement struck, or null on a miss. */
readonly assetId: string | null;
}
export interface VersusPlayerState {
readonly userId: number;
readonly name: string;
/** Null until the player has em-placed their fleet. */
readonly fleet: VersusFob[] | null;
readonly ready: boolean;
/** The player's current point of impact (their next shot adjusts from here). */
readonly lastImpact: GridPoint | null;
/** Shots this player fired at the opponent. */
readonly shots: VersusShot[];
/** Distinct enemy cells struck by this player (score input). */
readonly cellsHit: number;
/** Enemy emplacements destroyed by this player (score input). */
readonly fobsDestroyed: number;
}
export interface VersusState {
readonly boardSize: number;
readonly phase: VersusPhase;
readonly players: [VersusPlayerState, VersusPlayerState];
/** Whose turn it is; null before the battle or once complete. */
readonly turn: 0 | 1 | null;
/** Winning player index, or null on a draw / before completion. */
readonly winner: 0 | 1 | null;
readonly reason: VersusEndReason | null;
/** Total shots resolved across both players (cap guard). */
readonly shotsFired: number;
readonly startedAt: string | null;
readonly completedAt: string | null;
}
/* ------------------------------------------------------------------ views */
export interface VersusFobView {
readonly id: string;
readonly label: string;
readonly size: number;
readonly cells: GridPoint[];
readonly hitCells: GridPoint[];
readonly destroyed: boolean;
}
export interface VersusShotView {
readonly grid: GridPoint;
readonly outcome: ShotOutcome;
}
export interface VersusYouView {
readonly userId: number;
readonly opponentUserId: number;
readonly opponentName: string;
readonly ready: boolean;
readonly fleet: VersusFobView[];
readonly lastImpact: GridPoint | null;
/** Shots you fired at the enemy, in order. */
readonly shots: VersusShotView[];
/** Shots the enemy fired at you, in order (your own board's battle damage). */
readonly incoming: VersusShotView[];
readonly cellsHit: number;
readonly fobsDestroyed: number;
}
/** State-derived view, before the registry adds match/version/timeout fields. */
export interface VersusStateView {
readonly boardSize: number;
readonly phase: VersusPhase;
readonly yourIndex: 0 | 1;
readonly opponentReady: boolean;
readonly turnUserId: number | null;
readonly you: VersusYouView;
readonly result: { readonly winnerUserId: number | null; readonly reason: VersusEndReason } | null;
}
/** The complete per-user snapshot the registry pushes and serves. */
export interface VersusMatchView extends VersusStateView {
readonly matchId: string;
readonly name: string | null;
readonly version: number;
readonly turnDeadline: string | null;
}
/** Lobby row. */
export interface VersusMatchSummary {
readonly matchId: string;
readonly name: string | null;
readonly hostName: string;
readonly guestName: string | null;
readonly seatedCount: number;
readonly maxSeats: number;
readonly phase: VersusPhase | "waiting";
readonly createdAt: string;
/** True when the requesting user already holds a seat in this match. */
readonly joined: boolean;
}

View file

@ -0,0 +1,62 @@
/**
* Projection helpers for the versus mode. The full state (both hidden fleets)
* must never leave the server, so every snapshot is built per viewer:
*
* - `you.fleet` is the viewer's OWN emplacement board (with the enemy's hits).
* - `you.shots` is where the viewer's rounds landed (the viewer's knowledge).
* - `you.incoming` is where the enemy's rounds landed on the viewer's board.
*
* The opponent's fleet layout is deliberately absent from every field.
*/
import type { VersusFob, VersusShot, VersusState, VersusStateView, VersusShotView } from "./types";
import type { VersusFobView } from "./types";
export function projectFob(fob: VersusFob): VersusFobView {
return {
id: fob.id,
label: fob.label,
size: fob.size,
cells: fob.cells,
hitCells: fob.hitCells,
destroyed: fob.hitCells.length >= fob.size,
};
}
function projectShots(shots: readonly VersusShot[]): VersusShotView[] {
return shots.map((shot) => ({ grid: shot.grid, outcome: shot.outcome }));
}
/** Build the safe, per-viewer view of a match. */
export function buildVersusView(state: VersusState, index: 0 | 1): VersusStateView {
const viewer = state.players[index];
const opponentIndex: 0 | 1 = index === 0 ? 1 : 0;
const opponent = state.players[opponentIndex];
return {
boardSize: state.boardSize,
phase: state.phase,
yourIndex: index,
opponentReady: opponent.ready,
turnUserId: state.turn === null ? null : state.players[state.turn].userId,
you: {
userId: viewer.userId,
opponentUserId: opponent.userId,
opponentName: opponent.name,
ready: viewer.ready,
fleet: (viewer.fleet ?? []).map(projectFob),
lastImpact: viewer.lastImpact,
shots: projectShots(viewer.shots),
incoming: projectShots(opponent.shots),
cellsHit: viewer.cellsHit,
fobsDestroyed: viewer.fobsDestroyed,
},
result:
state.phase === "complete"
? {
winnerUserId: state.winner === null ? null : state.players[state.winner].userId,
reason: state.reason ?? "eliminated",
}
: null,
};
}

View file

@ -11,7 +11,7 @@
* panel without shipping new code.
*/
export type MinigameCategory = "core" | "cardtable";
export type MinigameCategory = "core" | "cardtable" | "multiplayer";
export type MinigameStatus = "active" | "retired" | "upcoming";
/** The six period-scoring games. Poker and Blackjack stay out of periods. */
@ -150,6 +150,19 @@ export const BUILTIN_MINIGAMES: BuiltinMinigame[] = [
countsForPeriods: false,
scoreLabel: "Chips",
},
{
key: "callForFireVersus",
label: "Call for Fire: Versus",
description:
"Head-to-head artillery duel. Emplace your fire bases, then bracket the enemy's before they bracket yours.",
route: "/minigames/call-for-fire-versus",
icon: "Swords",
category: "multiplayer",
status: "active",
order: 9,
countsForPeriods: false,
scoreLabel: "Score",
},
];
/** Anchor for Period 1: the Monday 00:00 UTC the feature goes live. */
@ -201,6 +214,7 @@ export const MINIGAME_PROFILE_GAME_KEYS: Record<string, string> = {
qualification: "aimTrainer",
opord: "opordRecall",
callForFire: "callForFire",
callForFireVersus: "callForFireVersus",
poker: "poker",
blackjack: "blackjack",
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,26 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TYPE "public"."enum_minigames_category" ADD VALUE 'multiplayer';
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_versus_games_played" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_versus_wins" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_versus_losses" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_versus_best_score" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_versus_xp_earned" numeric DEFAULT 0;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "minigames" ALTER COLUMN "category" SET DATA TYPE text;
ALTER TABLE "minigames" ALTER COLUMN "category" SET DEFAULT 'core'::text;
DROP TYPE "public"."enum_minigames_category";
CREATE TYPE "public"."enum_minigames_category" AS ENUM('core', 'cardtable');
ALTER TABLE "minigames" ALTER COLUMN "category" SET DEFAULT 'core'::"public"."enum_minigames_category";
ALTER TABLE "minigames" ALTER COLUMN "category" SET DATA TYPE "public"."enum_minigames_category" USING "category"::"public"."enum_minigames_category";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_versus_games_played";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_versus_wins";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_versus_losses";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_versus_best_score";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_versus_xp_earned";`)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,20 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
/**
* Seed the Call for Fire: Versus registry row.
*
* Split from the schema migration because it references the 'multiplayer'
* enum value added there: Postgres forbids using a newly added enum value in
* the same transaction, and Payload runs each migration in one.
*/
export async function up({ db }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
INSERT INTO "minigames" ("key", "label", "description", "route", "icon", "category", "status", "order", "counts_for_periods", "score_label") VALUES
('callForFireVersus', 'Call for Fire: Versus', 'Head-to-head artillery duel. Emplace your fire bases, then bracket the enemy''s before they bracket yours.', '/minigames/call-for-fire-versus', 'Swords', 'multiplayer', 'active', 9, false, 'Score')
ON CONFLICT ("key") DO NOTHING;`)
}
export async function down({ db }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DELETE FROM "minigames" WHERE "key" = 'callForFireVersus';`)
}

View file

@ -124,6 +124,8 @@ import * as migration_20261011_195306_add_minigame_periods from './20261011_1953
import * as migration_20261011_201531_add_minigame_entry_occurred_at from './20261011_201531_add_minigame_entry_occurred_at';
import * as migration_20261011_221111_add_call_for_fire_minigame from './20261011_221111_add_call_for_fire_minigame';
import * as migration_20261011_221250_add_minigame_estimated_release_date from './20261011_221250_add_minigame_estimated_release_date';
import * as migration_20261012_014741_add_call_for_fire_versus from './20261012_014741_add_call_for_fire_versus';
import * as migration_20261012_015000_seed_call_for_fire_versus_registry from './20261012_015000_seed_call_for_fire_versus_registry';
export const migrations = [
{
@ -756,4 +758,14 @@ export const migrations = [
down: migration_20261011_221250_add_minigame_estimated_release_date.down,
name: '20261011_221250_add_minigame_estimated_release_date',
},
{
up: migration_20261012_014741_add_call_for_fire_versus.up,
down: migration_20261012_014741_add_call_for_fire_versus.down,
name: '20261012_014741_add_call_for_fire_versus'
},
{
up: migration_20261012_015000_seed_call_for_fire_versus_registry.up,
down: migration_20261012_015000_seed_call_for_fire_versus_registry.down,
name: '20261012_015000_seed_call_for_fire_versus_registry'
},
];

View file

@ -1525,7 +1525,11 @@ export const enum_custom_radio_test_scores_mode = pgEnum("enum_custom_radio_test
"sprint",
"watch",
]);
export const enum_minigames_category = pgEnum("enum_minigames_category", ["core", "cardtable"]);
export const enum_minigames_category = pgEnum("enum_minigames_category", [
"core",
"cardtable",
"multiplayer",
]);
export const enum_minigames_status = pgEnum("enum_minigames_status", [
"active",
"upcoming",
@ -3056,6 +3060,26 @@ export const profiles = pgTable(
"progression_minigames_call_for_fire_best_compound_missions",
{ mode: "number" },
).default(0),
progression_minigames_callForFireVersus_gamesPlayed: numeric(
"progression_minigames_call_for_fire_versus_games_played",
{ mode: "number" },
).default(0),
progression_minigames_callForFireVersus_wins: numeric(
"progression_minigames_call_for_fire_versus_wins",
{ mode: "number" },
).default(0),
progression_minigames_callForFireVersus_losses: numeric(
"progression_minigames_call_for_fire_versus_losses",
{ mode: "number" },
).default(0),
progression_minigames_callForFireVersus_bestScore: numeric(
"progression_minigames_call_for_fire_versus_best_score",
{ mode: "number" },
).default(0),
progression_minigames_callForFireVersus_xpEarned: numeric(
"progression_minigames_call_for_fire_versus_xp_earned",
{ mode: "number" },
).default(0),
progression_minigames_poker_gamesPlayed: numeric("progression_minigames_poker_games_played", {
mode: "number",
}).default(0),
@ -7304,6 +7328,11 @@ export const minigames = pgTable(
icon: varchar("icon").default("Gamepad2"),
category: enum_minigames_category("category").notNull().default("core"),
status: enum_minigames_status("status").notNull().default("active"),
estimatedReleaseDate: timestamp("estimated_release_date", {
mode: "string",
withTimezone: true,
precision: 3,
}),
order: numeric("order", { mode: "number" }).notNull().default(0),
countsForPeriods: boolean("counts_for_periods").default(false),
scoreLabel: varchar("score_label").default("Score"),

View file

@ -3317,6 +3317,13 @@ export interface Profile {
bestCheckpointMissions?: number | null;
bestCompoundMissions?: number | null;
};
callForFireVersus?: {
gamesPlayed?: number | null;
wins?: number | null;
losses?: number | null;
bestScore?: number | null;
xpEarned?: number | null;
};
poker?: {
gamesPlayed?: number | null;
wins?: number | null;
@ -6003,7 +6010,7 @@ export interface Minigame {
* lucide-react icon name, mapped in the client.
*/
icon?: string | null;
category: 'core' | 'cardtable';
category: 'core' | 'cardtable' | 'multiplayer';
status: 'active' | 'upcoming' | 'retired';
/**
* Optional target for an upcoming game. Shown as a countdown in the sidebar and on the game page. Display only: the game goes live when status changes to Active.
@ -8987,6 +8994,15 @@ export interface ProfilesSelect<T extends boolean = true> {
bestCheckpointMissions?: T;
bestCompoundMissions?: T;
};
callForFireVersus?:
| T
| {
gamesPlayed?: T;
wins?: T;
losses?: T;
bestScore?: T;
xpEarned?: T;
};
poker?:
| T
| {

View file

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

View file

@ -0,0 +1,148 @@
import { afterAll, beforeEach, describe, expect, it } from "vitest";
import type { FobPlacement } from "@/lib/minigames/call-for-fire-versus/constants";
import {
clearMatchesForTests,
createMatch,
fireShotFor,
getSnapshotFor,
joinMatch,
leaveMatch,
listMatchSummaries,
placeFleetFor,
} from "@/lib/minigames/call-for-fire-versus/registry";
import { computeVersusStatsDelta, readVersusStats, xpForVersus } from "@/lib/minigames/call-for-fire-versus/stats";
function fleetAt(x: number, y: number): FobPlacement[] {
return [
{ assetId: "command-post", origin: { x, y }, orientation: "h" },
{ assetId: "ammo-depot", origin: { x, y: y + 1 }, orientation: "h" },
{ assetId: "radar-site", origin: { x, y: y + 2 }, orientation: "h" },
{ assetId: "fob", origin: { x, y: y + 3 }, orientation: "h" },
];
}
beforeEach(() => {
clearMatchesForTests();
});
afterAll(() => {
clearMatchesForTests();
});
describe("call for fire versus 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);
// A different viewer is not joined.
expect(listMatchSummaries(9002).find((row) => row.matchId === matchId)?.joined).toBe(false);
});
it("seats a guest and rejects a third player", () => {
const matchId = createMatch(9101, "Host");
const view = joinMatch(matchId, 9102, "Guest");
expect(view.yourIndex).toBe(1);
expect(view.you.opponentName).toBe("Host");
expect(() => joinMatch(matchId, 9103, "Third")).toThrow("already full");
});
it("stops a user seating at two matches at once", () => {
const first = createMatch(9201, "Host");
createMatch(9202, "Other");
expect(() => joinMatch(first, 9202, "Other")).toThrow("already in another match");
});
it("rejects snapshots for non-members and unknown matches", () => {
const matchId = createMatch(9301, "Host");
expect(() => getSnapshotFor(matchId, 9302)).toThrow("You are not in this match.");
expect(() => getSnapshotFor("does-not-exist", 9301)).toThrow("Match not found.");
});
});
describe("call for fire versus registry: battle", () => {
it("allows pre-placement while waiting, but does not start the battle", () => {
const matchId = createMatch(9401, "Host");
const view = placeFleetFor(matchId, 9401, fleetAt(0, 0));
expect(view.phase).toBe("placing");
expect(view.you.ready).toBe(true);
expect(view.turnUserId).toBeNull();
});
it("starts the battle after both fleets, host firing first", () => {
const matchId = createMatch(9501, "Host");
joinMatch(matchId, 9502, "Guest");
placeFleetFor(matchId, 9501, fleetAt(4, 4));
const view = placeFleetFor(matchId, 9502, fleetAt(0, 0));
expect(view.phase).toBe("battle");
expect(view.turnUserId).toBe(9501);
expect(view.turnDeadline).not.toBeNull();
});
it("resolves a shot and passes the turn", () => {
const matchId = createMatch(9601, "Host");
joinMatch(matchId, 9602, "Guest");
placeFleetFor(matchId, 9601, fleetAt(4, 4));
placeFleetFor(matchId, 9602, fleetAt(0, 0));
const afterShot = fireShotFor(matchId, 9601, { kind: "grid", grid: { x: 0, y: 0 } });
expect(afterShot.you.shots).toHaveLength(1);
expect(afterShot.you.shots[0].outcome).toBe("hit");
expect(afterShot.turnUserId).toBe(9602);
// The defender sees the incoming round on their own board.
const defender = getSnapshotFor(matchId, 9602);
expect(defender.you.incoming[0].grid).toEqual({ x: 0, y: 0 });
});
it("awards the win to the opponent when a player leaves mid-battle", () => {
const matchId = createMatch(9701, "Host");
joinMatch(matchId, 9702, "Guest");
placeFleetFor(matchId, 9701, fleetAt(4, 4));
placeFleetFor(matchId, 9702, fleetAt(0, 0));
leaveMatch(matchId, 9701);
const guest = getSnapshotFor(matchId, 9702);
expect(guest.phase).toBe("complete");
expect(guest.result?.winnerUserId).toBe(9702);
expect(guest.result?.reason).toBe("resigned");
// The leaver is no longer a member.
expect(() => getSnapshotFor(matchId, 9701)).toThrow("You are not in this match.");
});
it("disposes a match once the last player leaves", () => {
const matchId = createMatch(9801, "Host");
leaveMatch(matchId, 9801);
expect(() => getSnapshotFor(matchId, 9801)).toThrow("Match not found.");
});
});
describe("call for fire versus: stat math", () => {
it("reads defaults and accumulates a finished match", () => {
const current = readVersusStats({});
expect(current).toEqual({ gamesPlayed: 0, wins: 0, losses: 0, bestScore: 0, xpEarned: 0 });
const win = computeVersusStatsDelta(current, {
userId: 1,
won: true,
fobsDestroyed: 4,
cellsHit: 8,
});
expect(win.gamesPlayed).toBe(1);
expect(win.wins).toBe(1);
expect(win.losses).toBe(0);
expect(win.bestScore).toBe(408);
expect(win.xpEarned).toBe(xpForVersus(true, 4));
const loss = computeVersusStatsDelta(win, {
userId: 1,
won: false,
fobsDestroyed: 1,
cellsHit: 3,
});
expect(loss.wins).toBe(1);
expect(loss.losses).toBe(1);
expect(loss.bestScore).toBe(408);
});
});

View file

@ -0,0 +1,185 @@
import { describe, expect, it } from "vitest";
import {
buildFleet,
cellsForPlacement,
createVersusState,
fireShot,
isFleetDestroyed,
placeFleet,
scoreOf,
seatPlayer,
skipTurn,
type FobPlacement,
type VersusState,
} from "@/lib/minigames/call-for-fire-versus";
/** A deterministic, non-overlapping fleet layout anchored at (x, y). */
function fleetAt(x: number, y: number): FobPlacement[] {
return [
{ assetId: "command-post", origin: { x, y }, orientation: "h" },
{ assetId: "ammo-depot", origin: { x, y: y + 1 }, orientation: "h" },
{ assetId: "radar-site", origin: { x, y: y + 2 }, orientation: "h" },
{ assetId: "fob", origin: { x, y: y + 3 }, orientation: "h" },
];
}
function startedState(): VersusState {
let state = createVersusState({ userId: 1, name: "A" }, { userId: 2, name: "B" });
state = expectState(placeFleet(state, 0, fleetAt(4, 4)));
state = expectState(placeFleet(state, 1, fleetAt(0, 0)));
return state;
}
function expectState(result: { state: VersusState } | { error: string }): VersusState {
if ("error" in result) throw new Error(result.error);
return result.state;
}
describe("call for fire versus: fleet placement", () => {
it("lays out straight-line emplacements and rejects off-board ones", () => {
expect(cellsForPlacement({ x: 8, y: 0 }, "h", 3, 10)).toBeNull();
expect(cellsForPlacement({ x: 0, y: 0 }, "v", 3, 10)).toEqual([
{ x: 0, y: 0 },
{ x: 0, y: 1 },
{ x: 0, y: 2 },
]);
});
it("rejects missing, overlapping, and unknown emplacements", () => {
expect(buildFleet([fleetAt(0, 0)[0]], 10)).toEqual({ error: "Missing emplacement: Ammo Depot." });
const overlapping: FobPlacement[] = [
{ assetId: "command-post", origin: { x: 0, y: 0 }, orientation: "h" },
{ assetId: "ammo-depot", origin: { x: 1, y: 0 }, orientation: "h" },
{ assetId: "radar-site", origin: { x: 0, y: 3 }, orientation: "h" },
{ assetId: "fob", origin: { x: 0, y: 4 }, orientation: "h" },
];
expect(buildFleet(overlapping, 10)).toEqual({ error: "Emplacements cannot overlap." });
const unknown = [...fleetAt(0, 0), { assetId: "nuke", origin: { x: 9, y: 9 }, orientation: "h" as const }];
expect("error" in buildFleet(unknown, 10)).toBe(true);
});
it("starts the battle once both fleets are placed, host first", () => {
let state = createVersusState({ userId: 1, name: "A" }, { userId: 2, name: "B" });
state = expectState(placeFleet(state, 0, fleetAt(0, 0)));
expect(state.phase).toBe("placing");
state = expectState(placeFleet(state, 1, fleetAt(0, 5)));
expect(state.phase).toBe("battle");
expect(state.turn).toBe(0);
expect(state.startedAt).not.toBeNull();
});
});
describe("call for fire versus: firing", () => {
it("requires a grid reference first, then corrections only", () => {
const state = startedState();
expect("error" in fireShot(state, 0, { kind: "correction", rangeM: 0, deflectionM: 0 })).toBe(true);
const first = fireShot(state, 0, { kind: "grid", grid: { x: 0, y: 0 } });
expect("state" in first).toBe(true);
if (!("state" in first)) return;
expect(first.shot.outcome).toBe("hit");
expect(first.state.turn).toBe(1);
// Player 1's own first shot may also be a grid designation.
const guestFirst = fireShot(first.state, 1, { kind: "grid", grid: { x: 9, y: 9 } });
expect("state" in guestFirst).toBe(true);
if (!("state" in guestFirst)) return;
// Back to player 0, who has already fired: only a correction is legal now.
const second = fireShot(guestFirst.state, 0, { kind: "grid", grid: { x: 5, y: 5 } });
expect("error" in second).toBe(true);
});
it("rejects shots out of turn and once the match is over", () => {
const state = startedState();
expect("error" in fireShot(state, 1, { kind: "grid", grid: { x: 5, y: 5 } })).toBe(true);
});
it("reports misses, hits, and destroyed emplacements", () => {
let state = startedState();
// Miss.
state = expectState(fireShot(state, 0, { kind: "grid", grid: { x: 7, y: 7 } }));
expect(state.players[0].shots.at(-1)?.outcome).toBe("miss");
// Hit the command post's first cell.
state = expectState(fireShot(state, 1, { kind: "grid", grid: { x: 9, y: 9 } }));
state = expectState(fireShot(state, 0, { kind: "correction", rangeM: 350, deflectionM: -350 }));
const last = state.players[0].shots.at(-1);
expect(last?.outcome).toBe("hit");
expect(state.players[0].cellsHit).toBe(1);
});
it("ends the match when every emplacement is reduced", () => {
// Player 0 walks fire across player 1's whole fleet; player 1 always misses.
let state = startedState();
const moves: Array<{ i: 0 | 1; input: Parameters<typeof fireShot>[2] }> = [
{ i: 0, input: { kind: "grid", grid: { x: 0, y: 0 } } },
{ i: 1, input: { kind: "grid", grid: { x: 9, y: 9 } } },
{ i: 0, input: { kind: "correction", rangeM: 0, deflectionM: 50 } },
{ i: 1, input: { kind: "correction", rangeM: 0, deflectionM: 0 } },
{ i: 0, input: { kind: "correction", rangeM: 0, deflectionM: 50 } },
{ i: 1, input: { kind: "correction", rangeM: 0, deflectionM: 0 } },
{ i: 0, input: { kind: "correction", rangeM: -50, deflectionM: -100 } },
{ i: 1, input: { kind: "correction", rangeM: 0, deflectionM: 0 } },
{ i: 0, input: { kind: "correction", rangeM: 0, deflectionM: 50 } },
{ i: 1, input: { kind: "correction", rangeM: 0, deflectionM: 0 } },
{ i: 0, input: { kind: "correction", rangeM: -50, deflectionM: -50 } },
{ i: 1, input: { kind: "correction", rangeM: 0, deflectionM: 0 } },
{ i: 0, input: { kind: "correction", rangeM: 0, deflectionM: 50 } },
{ i: 1, input: { kind: "correction", rangeM: 0, deflectionM: 0 } },
{ i: 0, input: { kind: "correction", rangeM: -50, deflectionM: -50 } },
];
for (const move of moves) {
state = expectState(fireShot(state, move.i, move.input));
}
expect(state.phase).toBe("complete");
expect(state.winner).toBe(0);
expect(state.reason).toBe("eliminated");
expect(state.players[0].fobsDestroyed).toBe(4);
expect(isFleetDestroyed(state.players[1].fleet ?? [])).toBe(true);
});
it("passes the turn on a timeout", () => {
const state = startedState();
const skipped = skipTurn(state);
expect(skipped.turn).toBe(1);
});
});
describe("call for fire versus: views", () => {
it("never exposes the opponent's fleet layout", async () => {
const { buildVersusView } = await import("@/lib/minigames/call-for-fire-versus/views");
const state = startedState();
const view = buildVersusView(state, 0);
const serialized = JSON.stringify(view);
// Player 1's fleet sits at (0,0)..(0,3); player 0 has fired nothing, so
// none of those cells may appear in player 0's view.
expect(serialized).not.toContain('{"x":0,"y":0}');
expect(serialized).not.toContain('{"x":1,"y":0}');
expect(serialized).not.toContain('"fobsDestroyed":4');
// The viewer's own fleet is present.
expect(view.you.fleet).toHaveLength(4);
});
it("reports the outcome to the shooter only after a shot", async () => {
const { buildVersusView } = await import("@/lib/minigames/call-for-fire-versus/views");
let state = startedState();
state = expectState(fireShot(state, 0, { kind: "grid", grid: { x: 0, y: 0 } }));
const shooter = buildVersusView(state, 0);
const target = buildVersusView(state, 1);
expect(shooter.you.shots).toHaveLength(1);
expect(shooter.you.shots[0].outcome).toBe("hit");
// The defender sees the incoming round on their own board.
expect(target.you.incoming).toHaveLength(1);
expect(target.you.incoming[0].grid).toEqual({ x: 0, y: 0 });
});
});
describe("call for fire versus: helpers", () => {
it("seats a player and scores by emplacements then cells", () => {
const state = createVersusState({ userId: 1, name: "A" }, { userId: 0, name: "Waiting" });
const seated = seatPlayer(state, 1, { userId: 2, name: "B" });
expect(seated.players[1].userId).toBe(2);
expect(seated.players[1].name).toBe("B");
expect(scoreOf(seated.players[0])).toBe(0);
});
});