1
0
Fork 0

Compare commits

..

No commits in common. "c984f08ea0a07bf39b783c26f7907352c3c164cb" and "3e9449971f639cee06d8da4ebe68dc364c539dc8" have entirely different histories.

41 changed files with 11 additions and 124112 deletions

View file

@ -1,20 +1,5 @@
# Changelog
# v0.8.13
A new multiplayer duel joins the minigames, and the command palette gains the destinations and shortcuts it was missing.
### Features
- **Call for Fire: Versus.** A head-to-head artillery duel for two operators. Each player secretly lays out four fire bases (a 2x2 Command Post, an L-shaped Ammo Depot, a Radar Site and a Forward Operating Base) on a 10x10 grid, then takes turns calling fire. Open with a grid reference, then adjust range and deflection from your last impact to walk rounds onto the enemy's structures; the first to level every one wins. Includes a lobby with shareable match links, a live turn clock, color-coded structures that rotate around a fixed anchor, hit explosions and procedural sound effects, and a per-operator duel record that pays XP and chips.
- **More command palette destinations.** World Map, Event Log, Operations, Ops Ledger, Reservations, Supply Boxes, Promotions, Leaderboard, Minigame Leaderboards, Chronicle and Surveys are now searchable, alongside a Toggle Mini XP Display action and an Open Unassigned Tickets shortcut. The Notifications and Admin entries now show their G N and G A shortcuts, and Create Support Ticket opens the compose dialog directly.
### Improvements
- **Duel placement controls.** Select a structure and click a cell to place it, click a placed structure to pick it up and move it, and rotate it with a double-click or the rotate toggle. Placing is refused with a message if it would overlap another structure, and your opponent never sees your layout.
---
# v0.8.12
Games that are not ready yet now wait quietly in the sidebar with a countdown to their estimated release.

View file

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

View file

@ -29,15 +29,7 @@ function HelpdeskDisabled() {
);
}
export default async function HelpdeskPage({
searchParams,
}: {
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
const params = await searchParams;
const compose = params.compose === "1" || params.compose === "true";
const view = typeof params.view === "string" ? params.view : undefined;
export default async function HelpdeskPage() {
const headers = await nextHeaders();
const payload = await getPayload({ config });
const { user } = await payload.auth({
@ -82,14 +74,7 @@ export default async function HelpdeskPage({
<p className="text-sm text-muted-foreground">Submit and track support requests.</p>
</div>
<TicketsView
key={`${compose ? "compose" : "list"}:${view ?? "default"}`}
tickets={tickets}
voteSummaries={voteSummaries}
isStaff={isStaff}
initialCompose={compose}
initialView={view}
/>
<TicketsView tickets={tickets} voteSummaries={voteSummaries} isStaff={isStaff} />
</div>
);
}

View file

@ -1,157 +0,0 @@
"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

@ -1,83 +0,0 @@
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: place your fire bases, then target the enemy's before they target 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">
Place your fire bases, then target the enemy&apos;s before they target yours. First
to reduce every structure wins.
</p>
</div>
<CallForFireVersusArena
initialStats={stats}
currentUserId={Number(user.id)}
initialMatchId={initialMatchId}
/>
</div>
);
}

View file

@ -1943,64 +1943,6 @@
accent-color: var(--poker-trim);
}
/* Call for Fire: Versus */
.versus-sound-toggle {
display: flex;
align-items: center;
gap: 0.4rem;
}
.versus-sound-volume {
width: 4.5rem;
accent-color: #f59e0b;
}
.versus-explosion {
position: absolute;
inset: -25%;
z-index: 2;
border-radius: 9999px;
pointer-events: none;
background: radial-gradient(
circle,
rgba(254, 240, 138, 0.95) 0%,
rgba(249, 115, 22, 0.85) 42%,
rgba(239, 68, 68, 0) 72%
);
animation: versus-explosion 650ms ease-out both;
}
.versus-explosion-destroyed {
background: radial-gradient(
circle,
#ffffff 0%,
rgba(248, 113, 113, 0.95) 38%,
rgba(185, 28, 28, 0) 74%
);
}
@keyframes versus-explosion {
0% {
opacity: 0;
transform: scale(0.3);
}
25% {
opacity: 1;
transform: scale(0.85);
}
100% {
opacity: 0;
transform: scale(1.9);
}
}
@media (prefers-reduced-motion: reduce) {
.versus-explosion {
animation: none;
opacity: 0;
}
}
.poker-action-console:not(.poker-action-console-complete) {
grid-template-columns: minmax(0, 1.5fr) minmax(10rem, 0.8fr);
}

View file

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

View file

@ -133,7 +133,6 @@ 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 };
};
@ -154,8 +153,6 @@ 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;
@ -204,8 +201,6 @@ 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
@ -721,43 +716,6 @@ 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

@ -146,26 +146,6 @@ export function CommandPalette({
}
break;
}
case "toggleMiniXp": {
const result = await updatePreferences({
mutedAll: preferences?.notifications?.mutedAll ?? false,
mutedTypes: preferences?.notifications?.mutedTypes ?? [],
showCallsign: preferences?.display?.showCallsign ?? false,
showVersionOverlay: preferences?.display?.showVersionOverlay ?? true,
showBackgroundTexture: preferences?.display?.showBackgroundTexture ?? true,
leadOrActual: preferences?.display?.leadOrActual ?? "lead",
discordEnabled: preferences?.discord?.enabled ?? false,
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
xpDisplayMini: !(preferences?.display?.xpDisplayMini ?? false),
});
if (result.success) {
toast.success("XP display toggled");
router.refresh();
} else {
toast.error(result.error ?? "Failed to update preferences");
}
break;
}
case "copyPageLink": {
try {
await navigator.clipboard.writeText(window.location.href);

View file

@ -8,8 +8,6 @@ import {
Wallpaper,
Tag,
Link2,
Inbox,
Sparkles,
} from "lucide-react";
export interface ActionCommand {
@ -54,14 +52,6 @@ export const actionCommands: ActionCommand[] = [
actionType: "callback",
actionKey: "toggleCallsign",
},
{
id: "action:toggle-mini-xp",
label: "Toggle Mini XP Display",
icon: Sparkles,
keywords: ["display", "xp", "level", "compact", "sidebar", "progress"],
actionType: "callback",
actionKey: "toggleMiniXp",
},
{
id: "action:copy-page-link",
label: "Copy Page Link",
@ -106,16 +96,8 @@ export const actionCommands: ActionCommand[] = [
id: "action:create-ticket",
label: "Create Support Ticket",
icon: UserPlus,
keywords: ["help", "support", "report", "new", "compose"],
keywords: ["help", "support", "report"],
actionType: "navigate",
href: "/helpdesk?compose=1",
},
{
id: "action:open-unassigned-tickets",
label: "Open Unassigned Tickets",
icon: Inbox,
keywords: ["helpdesk", "support", "queue", "backlog", "triage", "staff"],
actionType: "navigate",
href: "/helpdesk?view=unassigned",
href: "/helpdesk",
},
];

View file

@ -28,13 +28,6 @@ import {
Spade,
Club,
Target,
Swords,
Radar,
ClipboardList,
Boxes,
Medal,
Trophy,
ClipboardCheck,
} from "lucide-react";
export interface NavigationCommand {
@ -72,20 +65,6 @@ export const navigationCommands: NavigationCommand[] = [
href: "/transfers",
keywords: ["assignments", "requests", "moves"],
},
{
id: "nav:map",
label: "World Map",
icon: Map,
href: "/map",
keywords: ["tiles", "terrain", "atlas", "geography", "planet"],
},
{
id: "nav:events",
label: "Event Log",
icon: ScrollText,
href: "/events",
keywords: ["activity", "history", "audit", "feed"],
},
{
id: "nav:helpdesk",
label: "Helpdesk",
@ -109,28 +88,6 @@ export const navigationCommands: NavigationCommand[] = [
keywords: ["find", "query", "issues"],
},
{
id: "nav:operations",
label: "Operations",
icon: Radar,
href: "/operations",
keywords: ["ops", "overview", "theater", "campaign map"],
},
{
id: "nav:operations-ledger",
label: "Ops Ledger",
icon: ClipboardList,
href: "/operations/ledger",
keywords: ["operations", "history", "records", "log"],
},
{
id: "nav:operations-reservations",
label: "Reservations",
icon: CalendarDays,
href: "/operations/reservations",
keywords: ["operations", "slots", "bookings", "schedule"],
},
{
id: "nav:campaigns",
label: "Campaigns",
@ -224,14 +181,6 @@ export const navigationCommands: NavigationCommand[] = [
keywords: ["active", "field"],
requires: "logistics",
},
{
id: "nav:supply-boxes",
label: "Supply Boxes",
icon: Boxes,
href: "/logistics/supply-boxes",
keywords: ["logistics", "crates", "storage", "supplies"],
requires: "logistics",
},
{
id: "nav:banking",
label: "Banking",
@ -265,14 +214,6 @@ export const navigationCommands: NavigationCommand[] = [
href: "/personnel/statistics",
keywords: ["personnel", "stats", "vendors", "distribution"],
},
{
id: "nav:promotions",
label: "Promotions",
icon: Medal,
href: "/personnel/promotions",
keywords: ["personnel", "rank", "advancement", "nominations", "medals"],
requires: "logistics",
},
{
id: "nav:locker",
@ -289,13 +230,6 @@ export const navigationCommands: NavigationCommand[] = [
href: "/awards",
keywords: ["medals", "decorations", "commendations"],
},
{
id: "nav:contributions",
label: "Leaderboard",
icon: Trophy,
href: "/contributions",
keywords: ["contributions", "rankings", "top", "scoreboard", "standings"],
},
{
id: "nav:voiceover",
label: "Voiceover Scripts",
@ -345,13 +279,6 @@ 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",
@ -366,27 +293,6 @@ export const navigationCommands: NavigationCommand[] = [
href: "/minigames/blackjack",
keywords: ["minigame", "blackjack", "21", "cards", "training"],
},
{
id: "nav:minigame-leaderboards",
label: "Minigame Leaderboards",
icon: Trophy,
href: "/minigames/leaderboards",
keywords: ["minigame", "leaderboards", "standings", "scores", "rankings", "training"],
},
{
id: "nav:story",
label: "Chronicle",
icon: BookOpen,
href: "/story",
keywords: ["lore", "narrative", "story", "history", "beats"],
},
{
id: "nav:surveys",
label: "Surveys",
icon: ClipboardCheck,
href: "/surveys",
keywords: ["feedback", "polls", "questionnaire"],
},
{
id: "nav:account",
label: "Account",
@ -400,7 +306,6 @@ export const navigationCommands: NavigationCommand[] = [
icon: Bell,
href: "/notifications",
keywords: ["alerts", "messages"],
shortcut: "G N",
},
{
@ -410,6 +315,5 @@ export const navigationCommands: NavigationCommand[] = [
href: "/admin",
keywords: ["cms", "manage"],
roles: ["admin", "developer"],
shortcut: "G A",
},
];

View file

@ -37,7 +37,6 @@ 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) => {
@ -95,20 +94,6 @@ 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

@ -21,10 +21,6 @@ interface TicketsViewProps {
readonly tickets: readonly Ticket[];
readonly voteSummaries: readonly TicketVoteSummary[];
readonly isStaff: boolean;
/** Open the create dialog on mount (deep link from the command palette). */
readonly initialCompose?: boolean;
/** Preselect a filter tab on mount (e.g. "unassigned" from the palette). */
readonly initialView?: string;
}
const OPEN_STATUSES: readonly TicketStatus[] = [
@ -59,22 +55,10 @@ function isUnassignedTicket(ticket: Ticket): boolean {
);
}
export function TicketsView({
tickets,
voteSummaries,
isStaff,
initialCompose = false,
initialView,
}: TicketsViewProps) {
const [activeFilter, setActiveFilter] = useState<TicketFilter>(() => {
// Honor ?view= only when it maps to a filter the user may actually see.
if (initialView && isTicketFilter(initialView) && (isStaff || initialView !== "unassigned")) {
return initialView;
}
return "all";
});
export function TicketsView({ tickets, voteSummaries, isStaff }: TicketsViewProps) {
const [activeFilter, setActiveFilter] = useState<TicketFilter>("all");
const [search, setSearch] = useState("");
const [createOpen, setCreateOpen] = useState(initialCompose);
const [createOpen, setCreateOpen] = useState(false);
const votesByTicket = useMemo(
() => new Map(voteSummaries.map((summary) => [summary.ticketId, summary])),
[voteSummaries],

View file

@ -1,169 +0,0 @@
"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

@ -1,146 +0,0 @@
"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: "Placing structures",
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

@ -1,41 +0,0 @@
"use client";
import { Volume2, VolumeX } from "lucide-react";
import { Button } from "@/components/ui/button";
export function VersusSoundToggle({
muted,
volume,
onToggleMuted,
onVolumeChange,
}: {
muted: boolean;
volume: number;
onToggleMuted: () => void;
onVolumeChange: (volume: number) => void;
}) {
return (
<div className="versus-sound-toggle" aria-label="Duel sound controls">
<Button
type="button"
variant="outline"
size="icon"
onClick={onToggleMuted}
aria-label={muted ? "Unmute duel sounds" : "Mute duel sounds"}
title={muted ? "Unmute duel sounds" : "Mute duel sounds"}
>
{muted ? <VolumeX aria-hidden="true" /> : <Volume2 aria-hidden="true" />}
</Button>
<input
type="range"
min={0}
max={1}
step={0.05}
value={muted ? 0 : volume}
onChange={(event) => onVolumeChange(Number(event.target.value))}
aria-label="Duel sound volume"
className="versus-sound-volume"
/>
</div>
);
}

View file

@ -1,196 +0,0 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { VersusMatchView } from "@/app/(frontend)/minigames/call-for-fire-versus/actions";
import { DEFAULT_VERSUS_SOUND_VOLUME, VersusSoundEngine } from "./versusSound";
const SOUND_SETTINGS_KEY = "polaris:call-for-fire-versus-sound";
interface VersusSoundSettings {
readonly muted: boolean;
readonly volume: number;
}
const DEFAULT_SETTINGS: VersusSoundSettings = {
muted: false,
volume: DEFAULT_VERSUS_SOUND_VOLUME,
};
function clampVolume(value: number): number {
if (!Number.isFinite(value)) return DEFAULT_VERSUS_SOUND_VOLUME;
return Math.min(1, Math.max(0, value));
}
function readStoredSettings(): VersusSoundSettings {
if (typeof window === "undefined") return DEFAULT_SETTINGS;
try {
const raw = window.localStorage.getItem(SOUND_SETTINGS_KEY);
if (!raw) return DEFAULT_SETTINGS;
const parsed: unknown = JSON.parse(raw);
if (
typeof parsed !== "object" ||
parsed === null ||
typeof (parsed as { muted?: unknown }).muted !== "boolean" ||
typeof (parsed as { volume?: unknown }).volume !== "number"
) {
return DEFAULT_SETTINGS;
}
return {
muted: (parsed as { muted: boolean }).muted,
volume: clampVolume((parsed as { volume: number }).volume),
};
} catch {
return DEFAULT_SETTINGS;
}
}
function writeStoredSettings(settings: VersusSoundSettings): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(SOUND_SETTINGS_KEY, JSON.stringify(settings));
} catch {
// Storage may be unavailable (private mode); sound still works this session.
}
}
function isExplosive(outcome: string): boolean {
return outcome === "hit" || outcome === "destroyed";
}
export interface VersusSoundControls {
muted: boolean;
volume: number;
toggleMuted: () => void;
setVolume: (volume: number) => void;
/** Call on a shot the player fires (launch sound before the impact lands). */
playFire: () => void;
/** Call on an editor action (place, rotate, auto-deploy). */
playUi: () => void;
}
/**
* Wires the versus sound engine to match transitions: new outgoing/incoming
* shots play an impact, the turn passing to the player plays a chime, and
* completion plays a fanfare. Settings persist per browser.
*/
export function useVersusSounds(
match: VersusMatchView | null,
currentUserId: number | string,
): VersusSoundControls {
const [settings, setSettings] = useState<VersusSoundSettings>(DEFAULT_SETTINGS);
const settingsRef = useRef<VersusSoundSettings>(DEFAULT_SETTINGS);
settingsRef.current = settings;
const engineRef = useRef<VersusSoundEngine | null>(null);
const loadedRef = useRef(false);
const prevOutgoingRef = useRef<number | null>(null);
const prevIncomingRef = useRef<number | null>(null);
const prevTurnRef = useRef<number | null | undefined>(undefined);
const prevPhaseRef = useRef<string | null>(null);
const ensureEngine = useCallback((): VersusSoundEngine => {
const engine = engineRef.current ?? new VersusSoundEngine();
engineRef.current = engine;
engine.setVolume(settingsRef.current.volume);
engine.setMuted(settingsRef.current.muted);
engine.unlock();
return engine;
}, []);
const toggleMuted = useCallback(() => {
const muted = !settingsRef.current.muted;
settingsRef.current = { ...settingsRef.current, muted };
setSettings((current) => ({ ...current, muted }));
ensureEngine();
}, [ensureEngine]);
const setVolume = useCallback(
(volume: number) => {
const next = clampVolume(volume);
settingsRef.current = { ...settingsRef.current, volume: next };
setSettings((current) => ({ ...current, volume: next }));
ensureEngine();
},
[ensureEngine],
);
const playFire = useCallback(() => {
ensureEngine().play({ type: "fire" });
}, [ensureEngine]);
const playUi = useCallback(() => {
ensureEngine().play({ type: "ui" });
}, [ensureEngine]);
useEffect(() => {
setSettings(readStoredSettings());
loadedRef.current = true;
}, []);
useEffect(() => {
if (loadedRef.current) writeStoredSettings(settings);
}, [settings]);
useEffect(() => {
return () => {
engineRef.current?.dispose();
engineRef.current = null;
};
}, []);
useEffect(() => {
if (!match) {
prevOutgoingRef.current = null;
prevIncomingRef.current = null;
prevTurnRef.current = undefined;
prevPhaseRef.current = null;
return;
}
const engine = engineRef.current;
const you = match.you;
const outgoing = you.shots.length;
const incoming = you.incoming.length;
if (engine) {
if (prevOutgoingRef.current !== null && outgoing > prevOutgoingRef.current) {
for (const shot of you.shots.slice(prevOutgoingRef.current)) {
engine.play({ type: "impact", outcome: shot.outcome });
}
}
if (prevIncomingRef.current !== null && incoming > prevIncomingRef.current) {
for (const shot of you.incoming.slice(prevIncomingRef.current)) {
engine.play({ type: "impact", outcome: shot.outcome });
}
}
const turnBecameYours =
prevTurnRef.current !== undefined &&
prevTurnRef.current !== match.turnUserId &&
match.turnUserId !== null &&
String(match.turnUserId) === String(currentUserId) &&
match.phase === "battle";
if (turnBecameYours) engine.play({ type: "your-turn" });
if (prevPhaseRef.current !== null && prevPhaseRef.current !== "complete" && match.phase === "complete") {
const won =
match.result?.winnerUserId !== null &&
match.result?.winnerUserId !== undefined &&
String(match.result.winnerUserId) === String(currentUserId);
engine.play({ type: won ? "victory" : "defeat" });
}
}
prevOutgoingRef.current = outgoing;
prevIncomingRef.current = incoming;
prevTurnRef.current = match.turnUserId;
prevPhaseRef.current = match.phase;
}, [match, currentUserId]);
return {
muted: settings.muted,
volume: settings.volume,
toggleMuted,
setVolume,
playFire,
playUi,
};
}

View file

@ -1,217 +0,0 @@
/**
* Procedural sound effects for the Call for Fire versus mode.
*
* Pure Web Audio, no sampled assets: impacts are synthesized noise bursts and
* notifications are short tones, so nothing new ships in /public. Client-only:
* the AudioContext is created lazily and only resumes after a user gesture.
*/
export const DEFAULT_VERSUS_SOUND_VOLUME = 0.35;
export type VersusImpactOutcome = "miss" | "hit" | "destroyed";
export type VersusSoundEvent =
| { readonly type: "fire" }
| { readonly type: "impact"; readonly outcome: VersusImpactOutcome }
| { readonly type: "your-turn" }
| { readonly type: "victory" }
| { readonly type: "defeat" }
| { readonly type: "ui" };
type Tone = readonly [frequency: number, offset: number, duration: number];
function clampVolume(value: number): number {
if (!Number.isFinite(value)) return DEFAULT_VERSUS_SOUND_VOLUME;
return Math.min(1, Math.max(0, value));
}
export class VersusSoundEngine {
private context: AudioContext | null = null;
private master: GainNode | null = null;
private muted = false;
private volume = DEFAULT_VERSUS_SOUND_VOLUME;
private noiseBuffer: AudioBuffer | null = null;
setMuted(muted: boolean): void {
this.muted = muted;
this.applyGain();
}
setVolume(volume: number): void {
this.volume = clampVolume(volume);
this.applyGain();
}
/** Resume the context; call from a user gesture before expecting audio. */
unlock(): void {
const context = this.ensureContext();
if (!context) return;
if (context.state === "suspended") void context.resume().catch(() => undefined);
}
dispose(): void {
const context = this.context;
this.context = null;
this.master = null;
this.noiseBuffer = null;
if (context) void context.close().catch(() => undefined);
}
play(event: VersusSoundEvent): void {
const context = this.ensureContext();
const master = this.master;
if (!context || this.muted || !master) return;
const now = context.currentTime;
switch (event.type) {
case "fire":
this.playFire(context, now);
return;
case "impact":
this.playImpact(context, now, event.outcome);
return;
case "your-turn":
this.playTones(context, now, [
[880, 0, 0.09],
[1320, 0.1, 0.09],
], "triangle", 0.16);
return;
case "victory":
this.playTones(context, now, [
[523, 0, 0.12],
[659, 0.11, 0.12],
[784, 0.22, 0.14],
[1047, 0.35, 0.24],
], "triangle", 0.2);
return;
case "defeat":
this.playTones(context, now, [
[392, 0, 0.14],
[311, 0.14, 0.16],
[233, 0.3, 0.28],
], "sine", 0.18);
return;
case "ui":
this.playTone(context, now, 720, 0.04, 0.05, "triangle");
return;
}
}
private ensureContext(): AudioContext | null {
if (typeof window === "undefined") return null;
if (this.context) return this.context;
const ctor = (window.AudioContext ??
(window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext) as
| typeof AudioContext
| undefined;
if (!ctor) return null;
try {
const context = new ctor();
const master = context.createGain();
master.gain.value = this.muted ? 0 : this.volume;
master.connect(context.destination);
this.context = context;
this.master = master;
return context;
} catch {
return null;
}
}
private applyGain(): void {
if (this.master && this.context) this.master.gain.value = this.muted ? 0 : this.volume;
}
private playTone(
context: AudioContext,
at: number,
frequency: number,
duration: number,
gain: number,
type: OscillatorType,
endFrequency?: number,
): void {
const master = this.master;
if (!master) return;
const osc = context.createOscillator();
const envelope = context.createGain();
osc.type = type;
osc.frequency.setValueAtTime(frequency, at);
if (endFrequency !== undefined) {
osc.frequency.exponentialRampToValueAtTime(Math.max(1, endFrequency), at + duration);
}
envelope.gain.setValueAtTime(0.0001, at);
envelope.gain.exponentialRampToValueAtTime(gain, at + Math.min(0.015, duration * 0.3));
envelope.gain.exponentialRampToValueAtTime(0.0001, at + duration);
osc.connect(envelope);
envelope.connect(master);
osc.start(at);
osc.stop(at + duration + 0.02);
}
private playTones(
context: AudioContext,
at: number,
tones: readonly Tone[],
type: OscillatorType,
gain: number,
): void {
for (const [frequency, offset, duration] of tones) {
this.playTone(context, at + offset, frequency, duration, gain, type);
}
}
private noise(context: AudioContext): AudioBuffer {
if (this.noiseBuffer) return this.noiseBuffer;
const length = Math.floor(context.sampleRate);
const buffer = context.createBuffer(1, length, context.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < length; i += 1) data[i] = Math.random() * 2 - 1;
this.noiseBuffer = buffer;
return buffer;
}
private playNoise(
context: AudioContext,
at: number,
duration: number,
gain: number,
filterFrequency: number,
): void {
const master = this.master;
if (!master) return;
const source = context.createBufferSource();
source.buffer = this.noise(context);
const filter = context.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.setValueAtTime(filterFrequency, at);
const envelope = context.createGain();
envelope.gain.setValueAtTime(gain, at);
envelope.gain.exponentialRampToValueAtTime(0.0001, at + duration);
source.connect(filter);
filter.connect(envelope);
envelope.connect(master);
source.start(at);
source.stop(at + duration + 0.02);
}
private playFire(context: AudioContext, at: number): void {
this.playTone(context, at, 180, 0.22, 0.26, "sawtooth", 60);
this.playNoise(context, at, 0.14, 0.12, 900);
}
private playImpact(context: AudioContext, at: number, outcome: VersusImpactOutcome): void {
if (outcome === "miss") {
this.playNoise(context, at, 0.22, 0.16, 1400);
this.playTone(context, at, 150, 0.16, 0.11, "sine", 70);
return;
}
const destroyed = outcome === "destroyed";
this.playNoise(context, at, destroyed ? 0.7 : 0.45, destroyed ? 0.46 : 0.32, 2200);
this.playTone(context, at, 120, 0.35, 0.28, "sine", 40);
if (destroyed) {
this.playNoise(context, at + 0.16, 0.5, 0.32, 1600);
this.playTone(context, at + 0.14, 90, 0.4, 0.26, "sine", 32);
}
}
}

View file

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

View file

@ -9,7 +9,6 @@ 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

@ -1,70 +0,0 @@
/**
* 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 type FobShape = "line" | "square" | "l";
export interface FobDefinition {
readonly id: string;
readonly label: string;
/** Occupied cells when placed. */
readonly size: number;
/** "line" is straight, "square" is an NxN block, "l" is a 3-cell corner. */
readonly shape: FobShape;
}
/**
* The emplacement fleet each player hides. Total occupied cells are 10 of 100,
* so rounds matter without dragging.
*/
export const FOB_FLEET: readonly FobDefinition[] = [
{ id: "command-post", label: "Command Post", size: 4, shape: "square" },
{ id: "ammo-depot", label: "Ammo Depot", size: 3, shape: "l" },
{ id: "radar-site", label: "Radar Site", size: 2, shape: "line" },
{ id: "fob", label: "Forward Operating Base", size: 1, shape: "line" },
];
/**
* Quarter-turns clockwise. Lines use 0 (horizontal) and 1 (vertical); the
* square ignores it; the L uses all four.
*/
export type FobRotation = 0 | 1 | 2 | 3;
export interface FobPlacement {
readonly assetId: string;
readonly origin: GridPoint;
readonly orientation: FobRotation;
}
/** 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

@ -1,370 +0,0 @@
/**
* 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 FobDefinition,
type FobPlacement,
type FobRotation,
type FobShape,
} 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,
};
}
/** Rotate an offset vector by `turns` quarter-turns clockwise (screen coords). */
function rotateVector(vector: GridPoint, turns: number): GridPoint {
let x = vector.x;
let y = vector.y;
const normalized = ((turns % 4) + 4) % 4;
for (let t = 0; t < normalized; t += 1) {
const nextX = -y;
const nextY = x;
x = nextX;
y = nextY;
}
return { x, y };
}
/** Relative cells for a shape at a given orientation. */
function relativeCells(
shape: FobShape,
orientation: FobRotation,
size: number,
): GridPoint[] | null {
if (shape === "square") {
const side = Math.round(Math.sqrt(size));
if (side * side !== size) return null;
const cells: GridPoint[] = [];
for (let dy = 0; dy < side; dy += 1) {
for (let dx = 0; dx < side; dx += 1) cells.push({ x: dx, y: dy });
}
return cells;
}
if (shape === "l") {
// Anchored on the elbow (the corner cell), so rotating keeps that cell
// fixed on the board and the two arms swing around it. Orientation 0 looks
// like an L with the elbow at its bottom-left, arms up and to the right.
return [
{ x: 0, y: 0 },
rotateVector({ x: 0, y: -1 }, orientation),
rotateVector({ x: 1, y: 0 }, orientation),
];
}
const horizontal = orientation % 2 === 0;
const cells: GridPoint[] = [];
for (let i = 0; i < size; i += 1) {
cells.push(horizontal ? { x: i, y: 0 } : { x: 0, y: i });
}
return cells;
}
/**
* Cells a placed emplacement covers, or null when it runs off the board. The
* shape drives the footprint and orientation is quarter-turns clockwise.
* `origin` is the anchor kept fixed while rotating: a line's first cell, the
* square's top-left, or the L's elbow. For the L, `origin` is the elbow cell.
*/
export function cellsForPlacement(
origin: GridPoint,
orientation: FobRotation,
size: number,
boardSize: number,
shape: FobShape = "line",
): GridPoint[] | null {
const relative = relativeCells(shape, orientation, size);
if (!relative) return null;
const cells: GridPoint[] = [];
for (const cell of relative) {
const x = origin.x + cell.x;
const y = origin.y + cell.y;
if (x < 0 || y < 0 || x >= boardSize || y >= boardSize) return null;
cells.push({ x, y });
}
return cells;
}
/** Cells for a named emplacement, honoring its shape. */
export function cellsForFob(
definition: FobDefinition,
origin: GridPoint,
orientation: FobRotation,
boardSize: number,
): GridPoint[] | null {
return cellsForPlacement(origin, orientation, definition.size, boardSize, definition.shape);
}
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 structure: ${definition.label}.` };
const cells = cellsForFob(definition, placement.origin, placement.orientation, 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: "Structures 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 structure: ${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: "Placement 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 placed their structures." };
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

@ -1,10 +0,0 @@
/**
* 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

@ -1,351 +0,0 @@
/**
* 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

@ -1,151 +0,0 @@
/**
* 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

@ -1,130 +0,0 @@
/**
* 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;
/** Emplacement type struck (known to the shooter), or null on a miss. */
readonly assetId: string | null;
}
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

@ -1,62 +0,0 @@
/**
* 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, assetId: shot.assetId }));
}
/** 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" | "multiplayer";
export type MinigameCategory = "core" | "cardtable";
export type MinigameStatus = "active" | "retired" | "upcoming";
/** The six period-scoring games. Poker and Blackjack stay out of periods. */
@ -150,19 +150,6 @@ export const BUILTIN_MINIGAMES: BuiltinMinigame[] = [
countsForPeriods: false,
scoreLabel: "Chips",
},
{
key: "callForFireVersus",
label: "Call for Fire: Versus",
description:
"Head-to-head artillery duel. Place your fire bases, then target the enemy's before they target 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. */
@ -214,7 +201,6 @@ 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

@ -1,26 +0,0 @@
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";`)
}

View file

@ -1,20 +0,0 @@
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

@ -1,22 +0,0 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
/**
* Refresh the Call for Fire: Versus registry description to match the updated
* front-end copy (emplace -> place, emplacement -> structure, bracket -> target).
*
* The row was seeded by 20261012_015000; this updates the stored blurb so the
* sidebar and minigame card read the same as the page itself.
*/
export async function up({ db }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
UPDATE "minigames"
SET "description" = 'Head-to-head artillery duel. Place your fire bases, then target the enemy''s before they target yours.'
WHERE "key" = 'callForFireVersus';`)
}
export async function down({ db }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
UPDATE "minigames"
SET "description" = 'Head-to-head artillery duel. Emplace your fire bases, then bracket the enemy''s before they bracket yours.'
WHERE "key" = 'callForFireVersus';`)
}

View file

@ -124,9 +124,6 @@ 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';
import * as migration_20261012_030000_update_call_for_fire_versus_wording from './20261012_030000_update_call_for_fire_versus_wording';
export const migrations = [
{
@ -759,19 +756,4 @@ 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'
},
{
up: migration_20261012_030000_update_call_for_fire_versus_wording.up,
down: migration_20261012_030000_update_call_for_fire_versus_wording.down,
name: '20261012_030000_update_call_for_fire_versus_wording'
},
];

View file

@ -1525,11 +1525,7 @@ 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",
"multiplayer",
]);
export const enum_minigames_category = pgEnum("enum_minigames_category", ["core", "cardtable"]);
export const enum_minigames_status = pgEnum("enum_minigames_status", [
"active",
"upcoming",
@ -3060,26 +3056,6 @@ 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),
@ -7328,11 +7304,6 @@ 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,13 +3317,6 @@ 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;
@ -6010,7 +6003,7 @@ export interface Minigame {
* lucide-react icon name, mapped in the client.
*/
icon?: string | null;
category: 'core' | 'cardtable' | 'multiplayer';
category: 'core' | 'cardtable';
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.
@ -8994,15 +8987,6 @@ 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,7 +80,6 @@ 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

@ -1,148 +0,0 @@
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: 0 },
{ assetId: "ammo-depot", origin: { x, y: y + 3 }, orientation: 0 },
{ assetId: "radar-site", origin: { x, y: y + 4 }, orientation: 0 },
{ assetId: "fob", origin: { x, y: y + 5 }, orientation: 0 },
];
}
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

@ -1,239 +0,0 @@
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):
* a 2x2 Command Post (rows y..y+1), an L Ammo Depot with its elbow at
* (x, y+3) (rows y+2..y+3), a Radar Site line (row y+4) and a 1-cell FOB
* (row y+5).
*/
function fleetAt(x: number, y: number): FobPlacement[] {
return [
{ assetId: "command-post", origin: { x, y }, orientation: 0 },
{ assetId: "ammo-depot", origin: { x, y: y + 3 }, orientation: 0 },
{ assetId: "radar-site", origin: { x, y: y + 4 }, orientation: 0 },
{ assetId: "fob", origin: { x, y: y + 5 }, orientation: 0 },
];
}
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 }, 0, 3, 10)).toBeNull();
expect(cellsForPlacement({ x: 0, y: 0 }, 1, 3, 10)).toEqual([
{ x: 0, y: 0 },
{ x: 0, y: 1 },
{ x: 0, y: 2 },
]);
});
it("lays out a 2x2 square emplacement regardless of orientation", () => {
const square = [
{ x: 0, y: 0 },
{ x: 1, y: 0 },
{ x: 0, y: 1 },
{ x: 1, y: 1 },
];
expect(cellsForPlacement({ x: 0, y: 0 }, 0, 4, 10, "square")).toEqual(square);
expect(cellsForPlacement({ x: 0, y: 0 }, 1, 4, 10, "square")).toEqual(square);
expect(cellsForPlacement({ x: 9, y: 0 }, 0, 4, 10, "square")).toBeNull();
});
it("rotates the 3-cell L around its fixed elbow anchor", () => {
const anchor = { x: 2, y: 2 };
expect(cellsForPlacement(anchor, 0, 3, 10, "l")).toEqual([
{ x: 2, y: 2 },
{ x: 2, y: 1 },
{ x: 3, y: 2 },
]);
expect(cellsForPlacement(anchor, 1, 3, 10, "l")).toEqual([
{ x: 2, y: 2 },
{ x: 3, y: 2 },
{ x: 2, y: 3 },
]);
expect(cellsForPlacement(anchor, 2, 3, 10, "l")).toEqual([
{ x: 2, y: 2 },
{ x: 2, y: 3 },
{ x: 1, y: 2 },
]);
expect(cellsForPlacement(anchor, 3, 3, 10, "l")).toEqual([
{ x: 2, y: 2 },
{ x: 1, y: 2 },
{ x: 2, y: 1 },
]);
// The elbow anchor stays put through every rotation.
for (const turn of [0, 1, 2, 3] as const) {
expect(cellsForPlacement(anchor, turn, 3, 10, "l")).toContainEqual(anchor);
}
// Orientation 0 with the elbow on the top edge runs the up-arm off board.
expect(cellsForPlacement({ x: 0, y: 0 }, 0, 3, 10, "l")).toBeNull();
});
it("rejects missing, overlapping, and unknown emplacements", () => {
expect(buildFleet([fleetAt(0, 0)[0]], 10)).toEqual({ error: "Missing structure: Ammo Depot." });
const overlapping: FobPlacement[] = [
{ assetId: "command-post", origin: { x: 0, y: 0 }, orientation: 0 },
{ assetId: "ammo-depot", origin: { x: 1, y: 1 }, orientation: 0 },
{ assetId: "radar-site", origin: { x: 0, y: 4 }, orientation: 0 },
{ assetId: "fob", origin: { x: 0, y: 5 }, orientation: 0 },
];
expect(buildFleet(overlapping, 10)).toEqual({ error: "Structures cannot overlap." });
const unknown: FobPlacement[] = [
...fleetAt(0, 0),
{ assetId: "nuke", origin: { x: 9, y: 9 }, orientation: 0 },
];
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, 4)));
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: -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 } },
{ i: 1, input: { kind: "correction", rangeM: 0, deflectionM: 0 } },
{ i: 0, input: { kind: "correction", rangeM: -50, deflectionM: 0 } },
{ 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 includes (0,0) and (1,0); 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);
});
});