1
0
Fork 0

feat(minigames): add Call for Fire artillery observer game

Bracket hidden artillery targets across patrol/checkpoint/compound
difficulties. Pure rules in src/lib/minigames/call-for-fire.ts (compass
bearing observer reports, ADD/DROP + RIGHT/LEFT corrections, scoring,
distance-to-target accuracy, injected rng) with a 23-case spec.

Wires the game into the minigame ecosystem: submit action validates the
run, updates the profile callForFire group, pays out XP and chips, emits
minigame:call-for-fire, and records the period ledger entry (accuracy is
distance-to-target on a win, null on a loss). Adds the game page with
period standings and an all-time board, a command palette entry, the
Target icon, and the profiles XP aggregation.

The registry row and regenerated payload types land with the minigame
registry changes in a separate commit.
This commit is contained in:
Jason Fraley 2026-10-11 18:18:02 -04:00
parent ee7fc0b5e6
commit 6d6a5fb0ce
15 changed files with 42002 additions and 1 deletions

View file

@ -0,0 +1,254 @@
"use server";
import config from "@payload-config";
import { getPayload } from "payload";
import { chipsForXp } from "@/lib/minigames/chips";
import {
BEST_MISSIONS_FIELDS,
CALL_FOR_FIRE_DIFFICULTIES,
MAX_MISSIONS_PER_RUN,
METERS_PER_CELL,
calculateAccuracy,
calculateScore,
calculateXp,
isCallForFireDifficulty,
type CallForFireDifficulty,
} from "@/lib/minigames/call-for-fire";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { broadcastToUser } from "@/lib/realtime/bus";
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
interface ActionResult<T = undefined> {
success: boolean;
error?: string;
data?: T;
}
export type { CallForFireDifficulty };
export interface CallForFireStats {
gamesPlayed: number;
wins: number;
losses: number;
bestScore: number;
callForFireXp: number;
xpEarned: number;
bestPatrolMissions: number;
bestCheckpointMissions: number;
bestCompoundMissions: number;
}
export type CallForFireRunInput = {
difficulty: CallForFireDifficulty;
roundsUsed: number;
seconds: number;
finalDistanceM: number;
won: boolean;
};
type BestMissionsField = (typeof BEST_MISSIONS_FIELDS)[CallForFireDifficulty];
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 };
}
export async function submitCallForFireResult(
input: CallForFireRunInput,
): Promise<ActionResult<CallForFireStats>> {
try {
const { payload, user } = await authenticate();
if (!isCallForFireDifficulty(input.difficulty)) {
return { success: false, error: "Invalid result." };
}
const difficulty = input.difficulty;
const difficultyConfig = CALL_FOR_FIRE_DIFFICULTIES[difficulty];
const { roundsUsed, seconds, finalDistanceM, won } = input;
if (
!Number.isInteger(roundsUsed) ||
roundsUsed <= 0 ||
roundsUsed > Math.min(difficultyConfig.maxRounds, MAX_MISSIONS_PER_RUN)
) {
return { success: false, error: "Invalid result." };
}
if (
!Number.isInteger(seconds) ||
seconds <= 0 ||
seconds > difficultyConfig.maxSeconds
) {
return { success: false, error: "Invalid result." };
}
if (
typeof finalDistanceM !== "number" ||
!Number.isFinite(finalDistanceM) ||
finalDistanceM < 0 ||
finalDistanceM > difficultyConfig.size * METERS_PER_CELL
) {
return { success: false, error: "Invalid result." };
}
if (typeof won !== "boolean") {
return { success: false, error: "Invalid result." };
}
if (won && finalDistanceM > difficultyConfig.lethalRadiusM) {
return { success: false, error: "Invalid result." };
}
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: user.id as number } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const profile = profileRes.docs[0];
if (!profile) {
return { success: false, error: "No profile found for this user." };
}
const progression = (profile.progression ?? {}) as {
xp?: unknown;
chipBank?: number | null;
minigames?: {
callForFire?: {
gamesPlayed?: number;
wins?: number;
losses?: number;
bestScore?: number;
xpEarned?: number;
bestPatrolMissions?: number;
bestCheckpointMissions?: number;
bestCompoundMissions?: number;
};
};
};
const current = progression.minigames?.callForFire ?? {};
const score = calculateScore(difficulty, roundsUsed, seconds, finalDistanceM, won);
const accuracy = won ? calculateAccuracy(difficulty, finalDistanceM) : null;
const runXp = calculateXp(score, won);
const gamesPlayed = (current.gamesPlayed ?? 0) + 1;
const wins = (current.wins ?? 0) + (won ? 1 : 0);
const losses = (current.losses ?? 0) + (won ? 0 : 1);
const bestScore = Math.max(current.bestScore ?? 0, score);
const totalXp = (current.xpEarned ?? 0) + runXp;
const bestMissionsField = BEST_MISSIONS_FIELDS[difficulty];
const previousBestMissions = current[bestMissionsField as keyof typeof current] ?? 0;
const isBestRun =
won && (previousBestMissions === 0 || roundsUsed < previousBestMissions);
const bestMissions = isBestRun ? roundsUsed : previousBestMissions;
const { xp: _xp, ...progressionRest } = progression;
const chipBank = Math.max(0, (progression.chipBank ?? 0) + chipsForXp(runXp));
await payload.update({
collection: "profiles",
id: profile.id,
data: {
progression: {
...progressionRest,
chipBank,
minigames: {
...(progressionRest.minigames ?? {}),
callForFire: {
gamesPlayed,
wins,
losses,
bestScore,
xpEarned: totalXp,
bestPatrolMissions: current.bestPatrolMissions ?? 0,
bestCheckpointMissions: current.bestCheckpointMissions ?? 0,
bestCompoundMissions: current.bestCompoundMissions ?? 0,
[bestMissionsField]: bestMissions,
},
},
},
},
overrideAccess: true,
depth: 0,
});
broadcastToUser("profile-update", Number(user.id), {
reason: "xp",
xpGained: runXp,
chipBank,
profileId: profile.id,
});
if (won) {
await emitGameEvent(payload, {
type: EventTypes.MinigameCallForFire,
message: `brought fire onto a ${difficultyConfig.label} target with ${roundsUsed} round(s) (+${runXp} XP)`,
actor: user.id as number,
targetCollection: "users",
targetId: user.id as number,
data: {
difficulty,
roundsUsed,
seconds,
finalDistanceM,
accuracy,
score,
xpEarned: runXp,
},
});
}
await recordMinigameEntry({
payload,
userId: Number(user.id),
game: "callForFire",
score,
accuracy,
durationMs: seconds * 1000,
mode: difficulty,
meta: { roundsUsed, won, finalDistanceM: Math.round(finalDistanceM) },
});
return {
success: true,
data: {
gamesPlayed,
wins,
losses,
bestScore,
callForFireXp: totalXp,
xpEarned: runXp,
bestPatrolMissions:
bestMissionsField === "bestPatrolMissions"
? bestMissions
: (current.bestPatrolMissions ?? 0),
bestCheckpointMissions:
bestMissionsField === "bestCheckpointMissions"
? bestMissions
: (current.bestCheckpointMissions ?? 0),
bestCompoundMissions:
bestMissionsField === "bestCompoundMissions"
? bestMissions
: (current.bestCompoundMissions ?? 0),
},
};
} catch (error) {
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 };
}
}

View file

@ -0,0 +1,75 @@
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 { Target } from "lucide-react";
import { CallForFireArena } from "@/components/frontend/minigames/call-for-fire/CallForFireArena";
import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard";
export const metadata: Metadata = {
title: "Call for Fire (Polaris Task Force)",
description: "Adjust artillery onto a hidden target: fewer fire missions score higher.",
};
export default async function CallForFirePage() {
const headers = await nextHeaders();
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
const { user } = await payload.auth({ headers, canSetHeaders: false });
if (!user) {
redirect(`/login?returnTo=${encodeURIComponent("/minigames/call-for-fire")}`);
}
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: user.id as number } },
limit: 1,
depth: 0,
overrideAccess: true,
select: {
progression: {
minigames: true,
},
},
});
const callForFire = profileRes.docs[0]?.progression?.minigames?.callForFire ?? {};
const stats = {
gamesPlayed: callForFire.gamesPlayed ?? 0,
wins: callForFire.wins ?? 0,
losses: callForFire.losses ?? 0,
bestScore: callForFire.bestScore ?? 0,
callForFireXp: callForFire.xpEarned ?? 0,
xpEarned: 0,
bestPatrolMissions: callForFire.bestPatrolMissions ?? 0,
bestCheckpointMissions: callForFire.bestCheckpointMissions ?? 0,
bestCompoundMissions: callForFire.bestCompoundMissions ?? 0,
};
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">
<Target className="size-5 text-muted-foreground" />
<h1 className="text-lg font-semibold">Call for Fire</h1>
</div>
<p className="text-sm text-muted-foreground">
Adjust artillery onto the hidden target. Fewer fire missions score higher.
</p>
</div>
<CallForFireArena initialStats={stats} currentUserId={user.id as number} />
<div className="flex flex-col gap-2">
<h2 className="text-sm font-semibold text-muted-foreground">Anchored period standings</h2>
<PeriodStandingsCard
gameKey="callForFire"
icon="Target"
currentUserId={user.id as number}
/>
</div>
</div>
);
}

View file

@ -132,6 +132,7 @@ export const Profiles: CollectionConfig = {
radioTraffic?: { xpEarned?: number | null };
aimTrainer?: { xpEarned?: number | null };
opordRecall?: { xpEarned?: number | null };
callForFire?: { xpEarned?: number | null };
poker?: { xpEarned?: number | null };
blackjack?: { xpEarned?: number | null };
};
@ -151,6 +152,7 @@ export const Profiles: CollectionConfig = {
const radioTrafficXp = progressionData?.minigames?.radioTraffic?.xpEarned ?? 0;
const aimTrainerXp = progressionData?.minigames?.aimTrainer?.xpEarned ?? 0;
const opordRecallXp = progressionData?.minigames?.opordRecall?.xpEarned ?? 0;
const callForFireXp = progressionData?.minigames?.callForFire?.xpEarned ?? 0;
const pokerXp = progressionData?.minigames?.poker?.xpEarned ?? 0;
const blackjackXp = progressionData?.minigames?.blackjack?.xpEarned ?? 0;
const voiceoverXp = progressionData?.voiceover?.xpEarned ?? 0;
@ -197,6 +199,8 @@ export const Profiles: CollectionConfig = {
xpAcc += radioTrafficXp;
xpAcc += aimTrainerXp;
xpAcc += opordRecallXp;
// Call for Fire: XP from effective artillery adjustments
xpAcc += callForFireXp;
// Poker sit-and-go: XP from placement payouts
xpAcc += pokerXp;
// Blackjack sessions: XP from profit-based payouts
@ -658,6 +662,60 @@ export const Profiles: CollectionConfig = {
},
],
},
{
name: "callForFire",
label: "Call for Fire",
type: "group",
fields: [
{
name: "gamesPlayed",
type: "number",
defaultValue: 0,
},
{
name: "wins",
label: "Wins",
type: "number",
defaultValue: 0,
},
{
name: "losses",
label: "Losses",
type: "number",
defaultValue: 0,
},
{
name: "bestScore",
label: "Best Score",
type: "number",
defaultValue: 0,
},
{
name: "xpEarned",
label: "XP Earned",
type: "number",
defaultValue: 0,
},
{
name: "bestPatrolMissions",
label: "Fewest Missions on Best Patrol Support Run",
type: "number",
defaultValue: 0,
},
{
name: "bestCheckpointMissions",
label: "Fewest Missions on Best Checkpoint Defence Run",
type: "number",
defaultValue: 0,
},
{
name: "bestCompoundMissions",
label: "Fewest Missions on Best Compound Strike Run",
type: "number",
defaultValue: 0,
},
],
},
{
name: "poker",
label: "Poker",

View file

@ -27,6 +27,7 @@ import {
ScrollText,
Spade,
Club,
Target,
} from "lucide-react";
export interface NavigationCommand {
@ -271,6 +272,13 @@ export const navigationCommands: NavigationCommand[] = [
href: "/minigames/opord",
keywords: ["minigame", "briefing", "memory", "operations order", "training"],
},
{
id: "nav:call-for-fire",
label: "Call for Fire",
icon: Target,
href: "/minigames/call-for-fire",
keywords: ["minigame", "artillery", "fire mission", "observer", "bracket", "training"],
},
{
id: "nav:poker",
label: "Poker",

View file

@ -0,0 +1,50 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import type {
CallForFireDifficulty,
CallForFireStats,
} from "@/app/(frontend)/minigames/call-for-fire/actions";
import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import { useSidebar } from "@/components/ui/sidebar";
import { CallForFireLeaderboard } from "./CallForFireLeaderboard";
import { FireMissionBoard } from "./FireMissionBoard";
export function CallForFireArena({
initialStats,
currentUserId,
}: {
initialStats: CallForFireStats;
currentUserId: number | string;
}) {
const [refreshKey, setRefreshKey] = useState(0);
const [playing, setPlaying] = useState(false);
const [selectedDifficulty, setSelectedDifficulty] = useState<CallForFireDifficulty>("patrol");
const { isMobile, setOpenMobile } = useSidebar();
const activeTeams = useRealtimePresence("callForFire", playing, true);
const onPhaseChange = useCallback((phase: "ready" | "playing" | "over") => {
setPlaying(phase === "playing");
}, []);
useEffect(() => {
if (playing && isMobile) setOpenMobile(false);
}, [isMobile, playing, setOpenMobile]);
return (
<div className="flex flex-col items-center gap-6">
<FireMissionBoard
initialStats={initialStats}
onGameRecorded={() => setRefreshKey((key) => key + 1)}
onPhaseChange={onPhaseChange}
onDifficultyChange={setSelectedDifficulty}
/>
<CallForFireLeaderboard
refreshKey={refreshKey}
currentUserId={currentUserId}
activeTeams={activeTeams}
difficulty={selectedDifficulty}
onDifficultyChange={setSelectedDifficulty}
/>
</div>
);
}

View file

@ -0,0 +1,251 @@
"use client";
import { useEffect, useState } from "react";
import { Trophy } from "lucide-react";
import type { CallForFireDifficulty } from "@/app/(frontend)/minigames/call-for-fire/actions";
import type { PresenceParticipant } from "@/hooks/useRealtimePresence";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
interface ApiProfile {
id: number;
profileTitle?: string | null;
user?: {
id: number;
displayName?: string | null;
username?: string | null;
} | null;
progression?: {
minigames?: {
callForFire?: Record<string, number | undefined>;
};
};
}
interface LeaderboardRow {
id: number;
userId: number | null;
name: string;
gamesPlayed: number;
wins: number;
bestScore: number;
xpEarned: number;
bestMissions: number;
isCurrentUser: boolean;
isOutsideTopTen?: boolean;
}
interface CallForFireLeaderboardProps {
refreshKey?: number;
currentUserId?: number | string;
activeTeams?: PresenceParticipant[];
difficulty: CallForFireDifficulty;
onDifficultyChange: (difficulty: CallForFireDifficulty) => void;
}
const DIFFICULTY_LABELS: Record<CallForFireDifficulty, string> = {
patrol: "Patrol",
checkpoint: "Checkpoint",
compound: "Compound",
};
function rankClass(index: number) {
if (index === 0) return "font-bold text-amber-400";
if (index === 1) return "font-semibold text-slate-300";
if (index === 2) return "font-semibold text-amber-700";
return "text-muted-foreground";
}
export function CallForFireLeaderboard({
refreshKey = 0,
currentUserId,
activeTeams = [],
difficulty,
onDifficultyChange,
}: CallForFireLeaderboardProps) {
const [rows, setRows] = useState<LeaderboardRow[] | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let cancelled = false;
setFailed(false);
const missionsField = `progression.minigames.callForFire.best${DIFFICULTY_LABELS[difficulty]}Missions`;
const params = new URLSearchParams({
sort: missionsField,
limit: "100",
depth: "1",
});
params.set(`where[${missionsField}][greater_than]`, "0");
fetch(`/api/profiles?${params.toString()}`)
.then((res) => {
if (!res.ok) throw new Error("leaderboard fetch failed");
return res.json() as Promise<{ docs?: ApiProfile[] }>;
})
.then((data) => {
if (cancelled) return;
const mapped: LeaderboardRow[] = (data.docs ?? []).map((doc) => {
const game = doc.progression?.minigames?.callForFire ?? {};
const user = typeof doc.user === "object" && doc.user !== null ? doc.user : null;
const name =
user?.displayName || doc.profileTitle || user?.username || `Operator #${doc.id}`;
return {
id: doc.id,
userId: user?.id ?? null,
name,
gamesPlayed: game.gamesPlayed ?? 0,
wins: game.wins ?? 0,
bestScore: game.bestScore ?? 0,
xpEarned: game.xpEarned ?? 0,
bestMissions: game[`best${DIFFICULTY_LABELS[difficulty]}Missions`] ?? 0,
isCurrentUser: user ? String(user.id) === String(currentUserId) : false,
};
});
const scored = mapped
.filter((row) => row.bestMissions > 0)
.sort((a, b) => a.bestMissions - b.bestMissions || b.bestScore - a.bestScore);
const visible = scored.slice(0, 10);
const current = mapped.find((row) => row.isCurrentUser);
if (current && !visible.some((row) => row.id === current.id)) {
visible.push({ ...current, isOutsideTopTen: true });
}
setRows(visible);
})
.catch(() => {
if (!cancelled) setFailed(true);
});
return () => {
cancelled = true;
};
}, [difficulty, refreshKey, currentUserId]);
return (
<div className="w-full max-w-[520px] rounded-xl border border-border bg-card">
<div className="flex items-center gap-2 border-b border-border px-4 py-3">
<Trophy className="size-4 text-amber-400" />
<h2 className="text-sm font-semibold">Call for Fire Leaderboard</h2>
<div className="ml-auto flex items-center gap-2 text-xs text-muted-foreground">
<Select
value={difficulty}
onValueChange={(value) => onDifficultyChange(value as CallForFireDifficulty)}
>
<SelectTrigger aria-label="Leaderboard sector" className="h-8 w-[150px] text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="patrol">Patrol Support</SelectItem>
<SelectItem value="checkpoint">Checkpoint Defence</SelectItem>
<SelectItem value="compound">Compound Strike</SelectItem>
</SelectContent>
</Select>
<span>Top 10 · fewest missions</span>
</div>
</div>
<div
className="border-b border-border px-4 py-2 text-xs text-muted-foreground"
aria-live="polite"
>
<span className="font-medium text-emerald-400">
{activeTeams.length} observers on the net
</span>
{activeTeams.length > 0 && (
<span className="ml-1 text-foreground">
({activeTeams.map((team) => team.name).join(", ")})
</span>
)}
</div>
{failed ? (
<p className="px-4 py-4 text-sm text-muted-foreground">Could not load the leaderboard.</p>
) : rows === null ? (
<div className="space-y-2 px-4 py-4">
<div className="h-4 w-full animate-pulse rounded bg-border" />
<div className="h-4 w-3/4 animate-pulse rounded bg-border" />
<div className="h-4 w-1/2 animate-pulse rounded bg-border" />
</div>
) : rows.length === 0 ? (
<p className="px-4 py-4 text-sm text-muted-foreground">
No effective missions yet. Take the first sector!
</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs uppercase tracking-wider text-muted-foreground">
<th className="px-4 py-2 font-medium">#</th>
<th className="px-2 py-2 font-medium">Operator</th>
<th className="px-2 py-2 text-right font-medium">Missions</th>
<th className="px-2 py-2 text-right font-medium">Games</th>
<th className="px-2 py-2 text-right font-medium">Wins</th>
<th className="px-4 py-2 text-right font-medium">XP</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{rows.map((row, index) => (
<tr
key={row.id}
className={cn(
row.isCurrentUser && "bg-accent/40",
row.isOutsideTopTen && "text-muted-foreground opacity-70",
)}
title={
row.isOutsideTopTen
? "Operator status (not currently ranked in the top 10)"
: undefined
}
>
<td className="px-4 py-2">
<span className={rankClass(index)}>
{row.isOutsideTopTen ? "-" : index + 1}
</span>
</td>
<td className="px-2 py-2 font-medium">
<span className="flex items-center gap-2">
<span className="max-w-[180px] truncate">{row.name}</span>
{row.isCurrentUser && (
<span className="shrink-0 text-xs text-muted-foreground">(you)</span>
)}
{row.isOutsideTopTen && (
<span className="shrink-0 text-[10px] font-normal uppercase tracking-wide text-muted-foreground">
unranked
</span>
)}
{row.userId !== null &&
activeTeams.some((team) => team.id === row.userId) && (
<span
className="size-2 rounded-full bg-emerald-400"
title="Firing now"
aria-label="Firing now"
/>
)}
</span>
</td>
<td className="px-2 py-2 text-right font-semibold tabular-nums">
{row.bestMissions}
</td>
<td className="px-2 py-2 text-right tabular-nums text-muted-foreground">
{row.gamesPlayed}
</td>
<td className="px-2 py-2 text-right tabular-nums text-muted-foreground">
{row.wins}
</td>
<td className="px-4 py-2 text-right tabular-nums text-muted-foreground">
{row.xpEarned}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,688 @@
"use client";
import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
import { Crosshair, Radio, RotateCcw, Target, Timer } from "lucide-react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
submitCallForFireResult,
type CallForFireDifficulty,
type CallForFireStats,
} from "@/app/(frontend)/minigames/call-for-fire/actions";
import {
CALL_FOR_FIRE_DIFFICULTIES,
METERS_PER_CELL,
applyCorrection,
createScenario,
distanceMeters,
gridDesignation,
calculateScore,
isEffectiveHit,
observerReport,
type FireScenario,
type GridPoint,
} from "@/lib/minigames/call-for-fire";
import { PROFILE_UPDATE_EVENT } from "@/hooks/useGameTick";
import { useSessionExpired } from "@/hooks/useSessionExpired";
import { LoginLink } from "@/components/frontend/auth/LoginLink";
import { cn } from "@/lib/utils";
type Phase = "ready" | "playing" | "over";
type LastRun = {
readonly won: boolean;
readonly roundsUsed: number;
readonly seconds: number;
readonly finalDistanceM: number;
readonly score: number;
readonly xpEarned: number;
readonly best: number;
readonly reason?: "rounds" | "time";
readonly error?: string;
};
type Impact = {
readonly point: GridPoint;
readonly effective: boolean;
readonly spotting: boolean;
};
const DIFFICULTY_KEYS: readonly CallForFireDifficulty[] = ["patrol", "checkpoint", "compound"];
const CORRECTION_STEP = 50;
function formatClock(totalSeconds: number): string {
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}:${String(seconds).padStart(2, "0")}`;
}
export function FireMissionBoard({
initialStats: serverStats,
onGameRecorded,
onPhaseChange,
onDifficultyChange,
}: {
initialStats: CallForFireStats;
onGameRecorded: () => void;
onPhaseChange: (phase: Phase) => void;
onDifficultyChange: (difficulty: CallForFireDifficulty) => void;
}) {
const router = useRouter();
const { expired, expiredRef } = useSessionExpired();
const [difficulty, setDifficulty] = useState<CallForFireDifficulty>("patrol");
const [phase, setPhase] = useState<Phase>("ready");
const [scenario, setScenario] = useState<FireScenario | null>(null);
const [impacts, setImpacts] = useState<Impact[]>([]);
const [lastImpact, setLastImpact] = useState<GridPoint | null>(null);
const [radioLog, setRadioLog] = useState<string[]>([]);
const [roundsUsed, setRoundsUsed] = useState(0);
const [secondsLeft, setSecondsLeft] = useState(0);
const [rangeM, setRangeM] = useState(0);
const [deflectionM, setDeflectionM] = useState(0);
const [stats, setStats] = useState<CallForFireStats>(serverStats);
const [lastRun, setLastRun] = useState<LastRun | null>(null);
const [submitting, setSubmitting] = useState(false);
const submittingRef = useRef(false);
const statsRef = useRef<CallForFireStats>(serverStats);
const secondsLeftRef = useRef(0);
const config = CALL_FOR_FIRE_DIFFICULTIES[difficulty];
const roundsLeft = config.maxRounds - roundsUsed;
const elapsedSeconds = config.maxSeconds - secondsLeftRef.current;
const setPhaseSafe = useCallback(
(nextPhase: Phase) => {
setPhase(nextPhase);
onPhaseChange(nextPhase);
},
[onPhaseChange],
);
useEffect(() => {
onPhaseChange("ready");
}, [onPhaseChange]);
const reset = useCallback(
(nextDifficulty: CallForFireDifficulty = difficulty) => {
if (submittingRef.current) return;
if (expiredRef.current) return;
setDifficulty(nextDifficulty);
onDifficultyChange(nextDifficulty);
setScenario(null);
setImpacts([]);
setLastImpact(null);
setRadioLog([]);
setRoundsUsed(0);
setRangeM(0);
setDeflectionM(0);
setLastRun(null);
secondsLeftRef.current = CALL_FOR_FIRE_DIFFICULTIES[nextDifficulty].maxSeconds;
setSecondsLeft(CALL_FOR_FIRE_DIFFICULTIES[nextDifficulty].maxSeconds);
setPhaseSafe("ready");
},
[difficulty, expiredRef, onDifficultyChange, setPhaseSafe],
);
const recordResult = useCallback(
async (won: boolean, used: number, seconds: number, finalDistanceM: number) => {
if (submittingRef.current) return;
if (expiredRef.current) {
setLastRun({
won,
roundsUsed: used,
seconds,
finalDistanceM,
score: 0,
xpEarned: 0,
best: 0,
error: "Your session expired. Result not recorded.",
});
return;
}
submittingRef.current = true;
setSubmitting(true);
const result = await submitCallForFireResult({
difficulty,
roundsUsed: used,
seconds,
finalDistanceM,
won,
});
submittingRef.current = false;
setSubmitting(false);
const score = calculateScore(difficulty, used, seconds, finalDistanceM, won);
if (result.success && result.data) {
statsRef.current = result.data;
setStats(result.data);
onGameRecorded();
if (result.data.xpEarned > 0) {
window.dispatchEvent(
new CustomEvent(PROFILE_UPDATE_EVENT, {
detail: { reason: "xp", xpGained: result.data.xpEarned },
}),
);
window.setTimeout(() => router.refresh(), 1700);
}
setLastRun({
won,
roundsUsed: used,
seconds,
finalDistanceM,
score,
xpEarned: result.data.xpEarned,
best: result.data.bestScore,
});
} else {
setLastRun({
won,
roundsUsed: used,
seconds,
finalDistanceM,
score,
xpEarned: 0,
best: statsRef.current.bestScore,
error: result.error ?? "Could not record fire mission.",
});
}
},
[difficulty, expiredRef, onGameRecorded, router],
);
const finishGameRef = useRef<(won: boolean, reason?: "rounds" | "time") => void>(() => {});
finishGameRef.current = (won: boolean, reason?: "rounds" | "time") => {
if (submittingRef.current || phase === "over") return;
setPhaseSafe("over");
if (!scenario || !lastImpact) return;
const seconds = reason === "time" ? config.maxSeconds : elapsedSeconds;
const distance = distanceMeters(scenario.target, lastImpact);
void recordResult(won, roundsUsed, seconds, distance);
};
useEffect(() => {
if (phase !== "playing") return;
const interval = window.setInterval(() => {
setSecondsLeft((prev) => {
const next = prev - 1;
secondsLeftRef.current = next;
if (next <= 0) {
window.clearInterval(interval);
finishGameRef.current(false, "time");
return 0;
}
return next;
});
}, 1000);
return () => window.clearInterval(interval);
}, [phase]);
const begin = useCallback(() => {
if (expiredRef.current || submittingRef.current) return;
const nextScenario = createScenario(difficulty);
const report = observerReport(nextScenario.target, nextScenario.spotting);
setScenario(nextScenario);
setImpacts([
{ point: nextScenario.spotting, effective: false, spotting: true },
]);
setLastImpact(nextScenario.spotting);
setRadioLog([
`Splash, over. Spotting round ${gridDesignation(nextScenario.spotting)}: ${report.message}`,
]);
setRoundsUsed(1);
secondsLeftRef.current = config.maxSeconds;
setSecondsLeft(config.maxSeconds);
setRangeM(0);
setDeflectionM(0);
setLastRun(null);
setPhaseSafe("playing");
}, [config.maxSeconds, difficulty, expiredRef, setPhaseSafe]);
const fireMission = useCallback(() => {
if (phase !== "playing" || submittingRef.current || expiredRef.current) return;
if (!scenario || !lastImpact) return;
const impactPoint = applyCorrection(lastImpact, { rangeM, deflectionM }, config.size);
const distance = distanceMeters(scenario.target, impactPoint);
const effective = isEffectiveHit(scenario.target, impactPoint, config.lethalRadiusM);
const nextImpacts = [
...impacts,
{ point: impactPoint, effective, spotting: false },
];
const nextUsed = roundsUsed + 1;
setImpacts(nextImpacts);
setLastImpact(impactPoint);
setRoundsUsed(nextUsed);
setRangeM(0);
setDeflectionM(0);
if (effective) {
setRadioLog((log) =>
[
...log,
`Splash, over. Effective on grid ${gridDesignation(impactPoint)}. Target destroyed.`,
].slice(-6),
);
setPhaseSafe("over");
void recordResult(true, nextUsed, elapsedSeconds, distance);
return;
}
const report = observerReport(scenario.target, impactPoint);
setRadioLog((log) =>
[
...log,
`Impact grid ${gridDesignation(impactPoint)}: ${report.message}`,
].slice(-6),
);
if (nextUsed >= config.maxRounds) {
setPhaseSafe("over");
void recordResult(false, nextUsed, elapsedSeconds, distance);
}
}, [
config.lethalRadiusM,
config.maxRounds,
config.size,
elapsedSeconds,
expiredRef,
impacts,
lastImpact,
phase,
rangeM,
roundsUsed,
scenario,
setPhaseSafe,
]);
const timeCritical = phase === "playing" && secondsLeft <= 15;
const statusClass =
phase === "over"
? lastRun?.won
? "border-emerald-500/40 bg-emerald-500/10"
: "border-destructive/40 bg-destructive/10"
: "border-border bg-card";
return (
<div className="flex w-full max-w-5xl flex-col gap-4">
{expired && (
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-amber-500/40 bg-amber-500/10 p-6 text-center">
<span className="text-xl font-black uppercase tracking-widest text-amber-400">
Session Ending Soon
</span>
<span className="max-w-md text-sm text-white/80">
Your session is about to end. The app will refresh when it expires.
</span>
<LoginLink>
<Button type="button" size="sm">
Log in
</Button>
</LoginLink>
</div>
)}
<div className="flex select-none flex-col gap-4 rounded-xl border border-border bg-card p-4 shadow">
<div className="flex flex-wrap items-start justify-between gap-4">
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2 text-sm font-semibold">
<Target className="size-4 text-amber-500" />
Fire mission console
</div>
<p className="text-xs text-muted-foreground">
Bracket the hidden target from the spotting report, then walk fire on with range and
deflection corrections.
</p>
</div>
<div className="flex items-center gap-4 font-mono text-sm tabular-nums">
{phase !== "ready" && (
<span
className={cn("flex items-center gap-1.5", timeCritical && "text-destructive")}
aria-label={`${formatClock(Math.max(0, secondsLeft))} remaining`}
>
<Timer className="size-4" />
{formatClock(Math.max(0, secondsLeft))}
</span>
)}
{phase !== "ready" && (
<span
className="flex items-center gap-1.5"
aria-label={`${Math.max(0, roundsLeft)} rounds remaining`}
>
<Crosshair className="size-4 text-amber-400" />
{Math.max(0, roundsLeft)}
</span>
)}
</div>
</div>
<fieldset
disabled={phase === "playing"}
className={cn(
"m-0 flex min-w-0 flex-col gap-4 border-0 p-0 transition-opacity duration-300",
phase === "playing" && "pointer-events-none opacity-40",
)}
>
<div className="grid gap-2 md:grid-cols-3">
{DIFFICULTY_KEYS.map((key) => {
const option = CALL_FOR_FIRE_DIFFICULTIES[key];
return (
<Button
key={key}
type="button"
variant={difficulty === key ? "default" : "outline"}
className="h-auto justify-start px-3 py-2 text-left"
disabled={submitting || expired}
aria-pressed={difficulty === key}
onClick={() => reset(key)}
>
<span className="flex flex-col items-start gap-0.5">
<span>{option.label}</span>
<span className="text-[10px] font-normal opacity-75">
{option.size}×{option.size} grid · {option.maxRounds} rounds max ·{" "}
{option.parRounds} par · {formatClock(option.maxSeconds)} limit
</span>
</span>
</Button>
);
})}
</div>
</fieldset>
<div
className={cn(
"flex flex-wrap items-center justify-between gap-3 rounded-lg border px-3 py-2 text-sm",
statusClass,
)}
aria-live="polite"
>
<div className="flex flex-col gap-0.5">
{phase === "ready" && (
<span>Ready to observe. Begin the fire mission to receive your spotting round.</span>
)}
{phase === "playing" && (
<span>
Live fire mission: correct range (ADD/DROP) and deflection (RIGHT/LEFT) from the
last impact.
</span>
)}
{phase === "over" && lastRun?.won && (
<span>
Fire effect achieved. {config.label} target destroyed with {lastRun.roundsUsed}{" "}
round{lastRun.roundsUsed === 1 ? "" : "s"} in {lastRun.seconds}s.
</span>
)}
{phase === "over" && !lastRun?.won && lastRun?.reason === "rounds" && (
<span>Mission failed. Rounds expended before effect. Adjust and try again.</span>
)}
{phase === "over" && !lastRun?.won && lastRun?.reason === "time" && (
<span>Mission failed. Time expired before fire effect.</span>
)}
{phase === "over" && !lastRun && <span>Recording fire mission…</span>}
{lastRun?.won && (
<span className="text-xs text-emerald-500">
Score {lastRun.score} · accuracy {Math.round(lastRun.finalDistanceM)}m · +
{lastRun.xpEarned} XP earned.
</span>
)}
{lastRun?.error && <span className="text-xs text-destructive">{lastRun.error}</span>}
</div>
{phase === "ready" && (
<Button type="button" size="sm" disabled={submitting || expired} onClick={begin}>
<Crosshair /> Begin fire mission
</Button>
)}
{phase === "over" && (
<Button
type="button"
variant="outline"
size="sm"
disabled={submitting || expired}
onClick={() => reset()}
>
<RotateCcw /> New fire mission
</Button>
)}
</div>
<div className="grid gap-4 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,1fr)]">
<div
className="flex min-w-0 items-start justify-center overflow-auto rounded-lg border border-border bg-background p-2"
style={{ containerType: "inline-size" }}
>
<div
className="grid min-w-max gap-1"
style={
{
"--board-cols": config.size,
"--cell-size": `max(1.25rem, min(2rem, calc((100cqw - ${(config.size + 1) * 0.25}rem) / ${config.size})))`,
gridTemplateColumns: `auto repeat(var(--board-cols), var(--cell-size))`,
} as CSSProperties
}
role="grid"
aria-label={`${config.label} fire mission grid`}
>
<div />
{Array.from({ length: config.size }, (_, column) => (
<div
key={`col-${column}`}
className="flex size-[var(--cell-size)] items-center justify-center font-mono text-[10px] text-muted-foreground"
>
{String.fromCharCode(65 + column)}
</div>
))}
{Array.from({ length: config.size }, (_, row) => (
<ImpactRow
key={`row-${row}`}
row={row}
size={config.size}
impacts={impacts}
target={phase === "over" ? scenario?.target : undefined}
disabled={phase !== "playing" || expired}
/>
))}
</div>
</div>
<div className="flex min-w-0 flex-col gap-3">
<form
className="flex flex-col gap-3 rounded-lg border border-border/70 bg-background/50 p-3"
onSubmit={(event) => {
event.preventDefault();
fireMission();
}}
>
<div className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
<Crosshair className="size-3.5" />
Correction (metres, from last impact)
</div>
<CorrectionField
id="cff-range"
label="Range (+ ADD / - DROP)"
value={rangeM}
disabled={phase !== "playing"}
onChange={setRangeM}
/>
<CorrectionField
id="cff-deflection"
label="Deflection (+ RIGHT / - LEFT)"
value={deflectionM}
disabled={phase !== "playing"}
onChange={setDeflectionM}
/>
<Button type="submit" disabled={phase !== "playing" || submitting || expired}>
Fire mission
</Button>
<p className="text-[10px] text-muted-foreground">
1 cell = {METERS_PER_CELL}m. ADD pushes the burst north, RIGHT pushes it east.
</p>
</form>
<div className="min-w-0 rounded-lg border border-border/70 bg-background/50 px-3 py-2">
<div className="mb-1 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
<Radio className="size-3.5" />
Observer net
</div>
{radioLog.length === 0 ? (
<p className="text-xs text-muted-foreground">Net quiet. Awaiting your first call.</p>
) : (
<ul className="space-y-1 font-mono text-xs tabular-nums">
{radioLog.map((line, index) => (
<li
key={`${index}-${line}`}
className={cn(
line.includes("Effective") ? "text-emerald-400" : "text-muted-foreground",
)}
>
&gt; {line}
</li>
))}
</ul>
)}
</div>
</div>
</div>
<p className="text-center text-xs text-muted-foreground">
Read the spotting report, correct range and deflection, and walk the rounds onto the target
before time runs out
</p>
</div>
<div className="flex flex-wrap justify-center gap-6 text-sm text-muted-foreground">
<div className="flex items-center gap-1.5">
<span>Missions</span>
<span className="font-semibold text-foreground">{stats.gamesPlayed}</span>
</div>
<div className="flex items-center gap-1.5">
<span>Wins</span>
<span className="font-semibold text-foreground">{stats.wins}</span>
</div>
<div className="flex items-center gap-1.5">
<span>Best score</span>
<span className="font-semibold text-foreground">{stats.bestScore}</span>
</div>
<div className="flex items-center gap-1.5">
<span>XP from fires</span>
<span className="font-semibold text-foreground">{stats.callForFireXp}</span>
</div>
</div>
</div>
);
}
function ImpactRow({
row,
size,
impacts,
target,
disabled,
}: {
row: number;
size: number;
impacts: Impact[];
target?: GridPoint;
disabled: boolean;
}) {
const impactByColumn = new Map<number, Impact>();
for (const impact of impacts) {
if (impact.point.y === row) {
impactByColumn.set(impact.point.x, impact);
}
}
return (
<>
<div className="flex size-[var(--cell-size)] items-center justify-center font-mono text-[10px] text-muted-foreground">
{row + 1}
</div>
{Array.from({ length: size }, (_, column) => {
const impact = impactByColumn.get(column);
const isTarget = target !== undefined && target.x === column && target.y === row;
return (
<div
key={`${row}-${column}`}
role="gridcell"
aria-label={`grid ${gridDesignation({ x: column, y: row })}${
impact ? (impact.effective ? " effective impact" : impact.spotting ? " spotting round" : " impact") : ""
}`}
className={cn(
"flex size-[var(--cell-size)] items-center justify-center rounded-sm border text-xs font-bold transition-colors",
"border-border bg-card",
impact?.effective &&
"border-emerald-400 bg-emerald-600/80 text-emerald-50 shadow-[0_0_8px_rgb(16_185_129_/_0.6)]",
impact && !impact.effective && impact.spotting &&
"border-sky-400/80 bg-sky-500/20 text-sky-200",
impact && !impact.effective && !impact.spotting &&
"border-amber-500/70 bg-amber-500/20 text-amber-200",
isTarget && "border-destructive bg-destructive/25 text-red-300",
disabled && "opacity-90",
)}
>
{impact ? (
<Crosshair
className={cn("size-3.5", impact.spotting && "text-sky-300")}
strokeWidth={impact.spotting ? 2.5 : 2}
/>
) : null}
</div>
);
})}
</>
);
}
function CorrectionField({
id,
label,
value,
disabled,
onChange,
}: {
id: string;
label: string;
value: number;
disabled: boolean;
onChange: (next: number) => void;
}) {
const clamp = (next: number) => Math.min(2000, Math.max(-2000, next));
return (
<div className="flex flex-col gap-1">
<label htmlFor={id} className="text-xs text-muted-foreground">
{label}
</label>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="sm"
className="size-8 shrink-0 p-0"
disabled={disabled}
aria-label={`Decrease ${label}`}
onClick={() => onChange(clamp(value - CORRECTION_STEP))}
>
-{CORRECTION_STEP}
</Button>
<Input
id={id}
type="number"
step={CORRECTION_STEP}
value={value}
disabled={disabled}
className="h-8 text-center font-mono tabular-nums"
onChange={(event) => {
const parsed = Number(event.target.value);
onChange(Number.isFinite(parsed) ? clamp(Math.round(parsed)) : 0);
}}
/>
<Button
type="button"
variant="outline"
size="sm"
className="size-8 shrink-0 p-0"
disabled={disabled}
aria-label={`Increase ${label}`}
onClick={() => onChange(clamp(value + CORRECTION_STEP))}
>
+{CORRECTION_STEP}
</Button>
</div>
</div>
);
}

View file

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

View file

@ -8,6 +8,7 @@ Five XP-earning minigames under one parent: routes live at `/minigames/*` (moved
- **Qualification Course (aim trainer)**: `/minigames/qualification` (`src/app/(frontend)/minigames/qualification/`), game rules in `src/lib/minigames/aim-trainer.ts` (recruit/veteran/elite difficulties, civilian targets, scoring/accuracy/XP, injected rng). Components: `src/components/frontend/minigames/qualification/` (`AimTrainerArena`, `AimTrainerGame`, `AimTrainerCanvas`, `AimTrainerLeaderboard`). Action `submitAimTrainerResult` validates result bounds, updates profile stats, awards XP, emits `minigame:aim-trainer`.
- **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).
- Leaderboards match active players by user id (not display name) — see commit 72715c4 if leaderboard queries look wrong.
## Periods, achievements & the game registry

View file

@ -0,0 +1,335 @@
/**
* Call for Fire: artillery observer bracketing game.
*
* A hostile target sits at a hidden grid position. The observer (player)
* receives a spotting round that lands offset from the target, then issues
* iterative fire corrections ("add 200, right 100") within a limited number
* of rounds and a time limit. Each impact returns an observer report
* (bearing + range band) until a round lands within the lethal radius.
* Score rewards accuracy of the final round (distance from target) and
* efficiency (rounds used, time taken).
*
* Pure module: client-safe, no Payload imports. Server actions use the caps
* here to validate submitted results.
*/
export const CALL_FOR_FIRE_GRID_MIN = 0;
/** Absolute cap on rounds per run across all difficulties (validation). */
export const MAX_MISSIONS_PER_RUN = 24;
/** Grid cells per axis bounds across all difficulties (validation). */
export const MIN_GRID_SIZE = 8;
export const MAX_GRID_SIZE = 20;
/** Real-world metres represented by one grid cell (correction granularity). */
export const METERS_PER_CELL = 50;
export type CallForFireDifficulty = "patrol" | "checkpoint" | "compound";
export interface CallForFireDifficultyConfig {
label: string;
/** Grid is size x size cells. */
size: number;
/** Impact achieves effect when distance from target (metres) <= lethalRadiusM. */
lethalRadiusM: number;
/** Expected round count; score bonus for each round under par. */
parRounds: number;
/** Hard cap on rounds per run (spotting round included). */
maxRounds: number;
/** Base score awarded on an effective mission. */
baseScore: number;
/** Score per round under par. */
perRoundBonus: number;
/** Expected completion time in seconds; 1 score point per second under par. */
parSeconds: number;
/** Hard time limit in seconds; exceeding it fails the run. */
maxSeconds: number;
/** Hidden target is placed at least this many cells from any edge. */
targetInset: number;
/** Spotting round lands this many cells from the target (min). */
spotMinCells: number;
/** Spotting round lands this many cells from the target (max). */
spotMaxCells: number;
}
export const CALL_FOR_FIRE_DIFFICULTIES: Record<
CallForFireDifficulty,
CallForFireDifficultyConfig
> = {
patrol: {
label: "Patrol Support",
size: 10,
lethalRadiusM: 75,
parRounds: 4,
maxRounds: 8,
baseScore: 100,
perRoundBonus: 25,
parSeconds: 90,
maxSeconds: 180,
targetInset: 3,
spotMinCells: 3,
spotMaxCells: 6,
},
checkpoint: {
label: "Checkpoint Defence",
size: 12,
lethalRadiusM: 50,
parRounds: 6,
maxRounds: 10,
baseScore: 300,
perRoundBonus: 40,
parSeconds: 120,
maxSeconds: 240,
targetInset: 4,
spotMinCells: 4,
spotMaxCells: 8,
},
compound: {
label: "Compound Strike",
size: 14,
lethalRadiusM: 50,
parRounds: 8,
maxRounds: 12,
baseScore: 600,
perRoundBonus: 60,
parSeconds: 150,
maxSeconds: 300,
targetInset: 5,
spotMinCells: 5,
spotMaxCells: 10,
},
};
const DIFFICULTY_KEYS: CallForFireDifficulty[] = ["patrol", "checkpoint", "compound"];
export function isCallForFireDifficulty(value: string): value is CallForFireDifficulty {
return DIFFICULTY_KEYS.includes(value as CallForFireDifficulty);
}
/** Per-difficulty profile field for the fewest rounds used to achieve effect. */
export const BEST_MISSIONS_FIELDS: Record<CallForFireDifficulty, string> = {
patrol: "bestPatrolMissions",
checkpoint: "bestCheckpointMissions",
compound: "bestCompoundMissions",
};
export interface GridPoint {
x: number;
y: number;
}
export function euclideanDistance(a: GridPoint, b: GridPoint): number {
return Math.hypot(a.x - b.x, a.y - b.y);
}
/** Distance from an impact to the target in metres. */
export function distanceMeters(target: GridPoint, impact: GridPoint): number {
return euclideanDistance(target, impact) * METERS_PER_CELL;
}
/** True when an impact at `impact` achieves effect on a target at `target`. */
export function isEffectiveHit(
target: GridPoint,
impact: GridPoint,
lethalRadiusM: number,
): boolean {
return distanceMeters(target, impact) <= lethalRadiusM;
}
const COMPASS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] as const;
export type CompassBearing = (typeof COMPASS)[number];
/**
* Bearing from an impact toward the target. Grid y grows downward, so north
* is negative dy. Due north is "N"; ties split clockwise from due north.
*/
export function bearingOf(target: GridPoint, impact: GridPoint): CompassBearing {
const dx = target.x - impact.x;
const dy = target.y - impact.y;
if (dx === 0 && dy === 0) {
return "N";
}
// atan2 expects y up: negate dy. Angle 0 = north, clockwise positive.
const angle = (Math.atan2(dx, -dy) * 180) / Math.PI;
const normalized = (angle + 360) % 360;
const index = Math.round(normalized / 45) % 8;
return COMPASS[index];
}
export type RangeBand = "dangerClose" | "close" | "medium" | "far";
export const RANGE_BANDS: { band: RangeBand; label: string; maxDistance: number }[] = [
{ band: "dangerClose", label: "danger close", maxDistance: 2 },
{ band: "close", label: "close", maxDistance: 4 },
{ band: "medium", label: "mid", maxDistance: 7 },
{ band: "far", label: "far", maxDistance: Number.POSITIVE_INFINITY },
];
/** Human range band from an impact to the target (euclidean cells). */
export function rangeBandOf(target: GridPoint, impact: GridPoint): RangeBand {
const distance = euclideanDistance(target, impact);
for (const entry of RANGE_BANDS) {
if (distance <= entry.maxDistance) {
return entry.band;
}
}
return "far";
}
export function rangeBandLabel(band: RangeBand): string {
return RANGE_BANDS.find((entry) => entry.band === band)?.label ?? "far";
}
export interface ObserverReport {
bearing: CompassBearing;
band: RangeBand;
message: string;
}
/** Radio-style observer report for a missed impact. */
export function observerReport(target: GridPoint, impact: GridPoint): ObserverReport {
const bearing = bearingOf(target, impact);
const band = rangeBandOf(target, impact);
return {
bearing,
band,
message: `Shot, over. Target bearing ${bearing}, range ${rangeBandLabel(band)}.`,
};
}
/** A fire correction in metres: range (+ADD / -DROP) and deflection (+RIGHT / -LEFT). */
export interface Correction {
rangeM: number;
deflectionM: number;
}
/** Clamp a grid point into the size x size board. */
export function clampPoint(point: GridPoint, size: number): GridPoint {
return {
x: Math.min(size - 1, Math.max(0, point.x)),
y: Math.min(size - 1, Math.max(0, point.y)),
};
}
/**
* Apply a correction to the last impact. ADD moves the impact further from
* the observer (north, -y); RIGHT shifts it east (+x). Metres round to the
* nearest cell and the result clamps to the board.
*/
export function applyCorrection(
lastImpact: GridPoint,
correction: Correction,
size: number,
): GridPoint {
const dx = Math.round(correction.deflectionM / METERS_PER_CELL);
const dy = -Math.round(correction.rangeM / METERS_PER_CELL);
return clampPoint({ x: lastImpact.x + dx, y: lastImpact.y + dy }, size);
}
/**
* Score for a run: base, plus a bonus per round under par, plus a bonus per
* second under par, plus a bonus for final-round accuracy (metres inside the
* lethal radius). Losses score 0.
*/
export function calculateScore(
difficulty: CallForFireDifficulty,
roundsUsed: number,
seconds: number,
finalDistanceM: number,
won: boolean,
): number {
if (!won) {
return 0;
}
const config = CALL_FOR_FIRE_DIFFICULTIES[difficulty];
const roundsBonus = Math.max(0, config.parRounds - roundsUsed) * config.perRoundBonus;
const timeBonus = Math.max(0, config.parSeconds - seconds);
const accuracyBonus = Math.max(0, Math.round(config.lethalRadiusM - finalDistanceM));
return config.baseScore + roundsBonus + timeBonus + accuracyBonus;
}
/** XP for a run: 1 XP per 50 score, minimum 1 on a win. Losses earn nothing. */
export function calculateXp(score: number, won: boolean): number {
if (!won) {
return 0;
}
return Math.max(1, Math.floor(score / 50));
}
/**
* Tube accuracy for a run: how tightly the final round landed relative to the
* difficulty's lethal radius. 1 is a direct hit (or tighter), 0 is at the
* radius edge. Values outside [0, 1] clamp, so a loss (which lands outside the
* radius) reports 0 rather than a negative; the submit action records `null`
* for losses so period precision ignores them entirely.
*/
export function calculateAccuracy(
difficulty: CallForFireDifficulty,
finalDistanceM: number,
): number {
const { lethalRadiusM } = CALL_FOR_FIRE_DIFFICULTIES[difficulty];
if (!Number.isFinite(finalDistanceM) || lethalRadiusM <= 0) {
return 0;
}
return Math.max(0, Math.min(1, 1 - finalDistanceM / lethalRadiusM));
}
/** Uniform random point in the interior region reserved for the hidden target. */
export function randomTargetPosition(
difficulty: CallForFireDifficulty,
rng: () => number = Math.random,
): GridPoint {
const { size, targetInset } = CALL_FOR_FIRE_DIFFICULTIES[difficulty];
const min = targetInset;
const max = size - 1 - targetInset;
return {
x: min + Math.floor(rng() * (max - min + 1)),
y: min + Math.floor(rng() * (max - min + 1)),
};
}
/** Random compass direction; magnitude uniform in [min, max] cells. */
export function randomSpottingOffset(
difficulty: CallForFireDifficulty,
rng: () => number = Math.random,
): GridPoint {
const { spotMinCells, spotMaxCells } = CALL_FOR_FIRE_DIFFICULTIES[difficulty];
const magnitude = spotMinCells + rng() * (spotMaxCells - spotMinCells);
const angle = rng() * Math.PI * 2;
return {
x: Math.round(Math.cos(angle) * magnitude),
y: Math.round(Math.sin(angle) * magnitude),
};
}
export interface FireScenario {
/** Hidden target position. */
target: GridPoint;
/** Where the initial spotting round lands. */
spotting: GridPoint;
}
/**
* Generate a randomized scenario: hidden target plus a spotting round landing
* a random distance and direction from it, clamped to the board.
*/
export function createScenario(
difficulty: CallForFireDifficulty,
rng: () => number = Math.random,
): FireScenario {
const { size } = CALL_FOR_FIRE_DIFFICULTIES[difficulty];
const target = randomTargetPosition(difficulty, rng);
const offset = randomSpottingOffset(difficulty, rng);
const spotting = clampPoint({ x: target.x + offset.x, y: target.y + offset.y }, size);
return { target, spotting };
}
/** Grid designation like "E5" for display (column letter + 1-based row). */
export function gridDesignation(point: GridPoint): string {
const column = String.fromCharCode(65 + (point.x % 26));
return `${column}${point.y + 1}`;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,45 @@
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_users_preferences_notifications_muted_types" ADD VALUE 'minigame:achievement';
ALTER TYPE "public"."enum_users_preferences_discord_muted_types" ADD VALUE 'minigame:achievement';
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_games_played" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_wins" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_losses" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_best_score" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_xp_earned" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_best_patrol_missions" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_best_checkpoint_missions" numeric DEFAULT 0;
ALTER TABLE "profiles" ADD COLUMN "progression_minigames_call_for_fire_best_compound_missions" numeric DEFAULT 0;`)
// Seed the Call for Fire registry row so a production deploy gets it from
// the migration chain (the dev seed script covers local resets). Idempotent;
// poker/blackjack shift down one place so the Core nav orders cleanly.
await db.execute(sql`
INSERT INTO "minigames" ("key", "label", "description", "route", "icon", "category", "status", "order", "counts_for_periods", "score_label") VALUES
('callForFire', 'Call for Fire', 'Bracket artillery onto a hidden target: fewer fire missions score higher.', '/minigames/call-for-fire', 'Target', 'core', 'active', 6, true, 'Score')
ON CONFLICT ("key") DO NOTHING;
UPDATE "minigames" SET "order" = 7 WHERE "key" = 'poker';
UPDATE "minigames" SET "order" = 8 WHERE "key" = 'blackjack';`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "users_preferences_notifications_muted_types" ALTER COLUMN "value" SET DATA TYPE text;
DROP TYPE "public"."enum_users_preferences_notifications_muted_types";
CREATE TYPE "public"."enum_users_preferences_notifications_muted_types" AS ENUM('market:offer', 'market:counter', 'market:accept', 'market:reject', 'market:withdrawn', 'market:closed', 'market:sold', 'market:expired', 'award:granted', 'account:discord-request', 'finance:deposit', 'finance:withdraw', 'finance:transfer', 'shipment:completed', 'ticket:created', 'ticket:assigned', 'ticket:reply', 'ticket:status', 'poker:force-ended', 'poker:everyone-left', 'blackjack:force-ended', 'blackjack:everyone-left', 'mission:role-promoted', 'contribution:xp-granted', 'contribution:xp-revoked');
ALTER TABLE "users_preferences_notifications_muted_types" ALTER COLUMN "value" SET DATA TYPE "public"."enum_users_preferences_notifications_muted_types" USING "value"::"public"."enum_users_preferences_notifications_muted_types";
ALTER TABLE "users_preferences_discord_muted_types" ALTER COLUMN "value" SET DATA TYPE text;
DROP TYPE "public"."enum_users_preferences_discord_muted_types";
CREATE TYPE "public"."enum_users_preferences_discord_muted_types" AS ENUM('market:offer', 'market:counter', 'market:accept', 'market:reject', 'market:withdrawn', 'market:closed', 'market:sold', 'market:expired', 'award:granted', 'account:discord-request', 'finance:deposit', 'finance:withdraw', 'finance:transfer', 'shipment:completed', 'ticket:created', 'ticket:assigned', 'ticket:reply', 'ticket:status', 'poker:force-ended', 'poker:everyone-left', 'blackjack:force-ended', 'blackjack:everyone-left', 'mission:role-promoted', 'contribution:xp-granted', 'contribution:xp-revoked');
ALTER TABLE "users_preferences_discord_muted_types" ALTER COLUMN "value" SET DATA TYPE "public"."enum_users_preferences_discord_muted_types" USING "value"::"public"."enum_users_preferences_discord_muted_types";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_games_played";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_wins";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_losses";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_best_score";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_xp_earned";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_best_patrol_missions";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_best_checkpoint_missions";
ALTER TABLE "profiles" DROP COLUMN "progression_minigames_call_for_fire_best_compound_missions";`)
}

View file

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

View file

@ -0,0 +1,250 @@
import { describe, expect, it } from "vitest";
import {
BEST_MISSIONS_FIELDS,
CALL_FOR_FIRE_DIFFICULTIES,
MAX_MISSIONS_PER_RUN,
METERS_PER_CELL,
applyCorrection,
bearingOf,
calculateScore,
calculateXp,
createScenario,
distanceMeters,
euclideanDistance,
gridDesignation,
isCallForFireDifficulty,
isEffectiveHit,
observerReport,
randomTargetPosition,
rangeBandLabel,
rangeBandOf,
calculateAccuracy,
} from "@/lib/minigames/call-for-fire";
function seededRng(seed: number): () => number {
let state = seed;
return () => {
state = (state * 1103515245 + 12345) % 2147483648;
return state / 2147483648;
};
}
describe("call-for-fire difficulty configs", () => {
it("has three difficulties with sane bounds", () => {
expect(Object.keys(CALL_FOR_FIRE_DIFFICULTIES).sort()).toEqual([
"checkpoint",
"compound",
"patrol",
]);
for (const key of Object.keys(CALL_FOR_FIRE_DIFFICULTIES) as Array<
keyof typeof CALL_FOR_FIRE_DIFFICULTIES
>) {
const config = CALL_FOR_FIRE_DIFFICULTIES[key];
expect(config.maxRounds).toBeLessThanOrEqual(MAX_MISSIONS_PER_RUN);
expect(config.parRounds).toBeLessThan(config.maxRounds);
expect(config.lethalRadiusM).toBeGreaterThan(0);
expect(config.lethalRadiusM).toBeLessThan((config.size / 2) * METERS_PER_CELL);
expect(config.targetInset).toBeGreaterThan(config.lethalRadiusM / METERS_PER_CELL);
expect(config.parSeconds).toBeLessThan(config.maxSeconds);
expect(config.spotMinCells).toBeGreaterThan(0);
expect(config.spotMaxCells).toBeGreaterThan(config.spotMinCells);
}
});
it("recognizes valid difficulty keys only", () => {
expect(isCallForFireDifficulty("patrol")).toBe(true);
expect(isCallForFireDifficulty("checkpoint")).toBe(true);
expect(isCallForFireDifficulty("compound")).toBe(true);
expect(isCallForFireDifficulty("training")).toBe(false);
expect(isCallForFireDifficulty("")).toBe(false);
});
it("maps difficulties to profile stat fields", () => {
expect(BEST_MISSIONS_FIELDS.patrol).toBe("bestPatrolMissions");
expect(BEST_MISSIONS_FIELDS.checkpoint).toBe("bestCheckpointMissions");
expect(BEST_MISSIONS_FIELDS.compound).toBe("bestCompoundMissions");
});
});
describe("call-for-fire geometry", () => {
it("computes euclidean distance", () => {
expect(euclideanDistance({ x: 0, y: 0 }, { x: 3, y: 4 })).toBe(5);
expect(euclideanDistance({ x: 2, y: 2 }, { x: 2, y: 2 })).toBe(0);
});
it("converts cells to metres", () => {
expect(distanceMeters({ x: 0, y: 0 }, { x: 3, y: 4 })).toBe(250);
expect(METERS_PER_CELL).toBe(50);
});
it("counts impacts within the lethal radius as effective", () => {
const target = { x: 5, y: 5 };
// One cell = 50m; the diagonal of one cell is ~70.7m, inside the 75m patrol radius.
expect(isEffectiveHit(target, { x: 5, y: 5 }, 75)).toBe(true);
expect(isEffectiveHit(target, { x: 5, y: 4 }, 75)).toBe(true);
expect(isEffectiveHit(target, { x: 6, y: 6 }, 75)).toBe(true);
// Two cells straight out is 100m, well outside the radius.
expect(isEffectiveHit(target, { x: 7, y: 5 }, 75)).toBe(false);
expect(isEffectiveHit(target, { x: 7, y: 6 }, 75)).toBe(false);
});
it("reports compass bearings with north up", () => {
const target = { x: 5, y: 5 };
expect(bearingOf(target, { x: 5, y: 6 })).toBe("N");
expect(bearingOf(target, { x: 5, y: 4 })).toBe("S");
expect(bearingOf(target, { x: 4, y: 5 })).toBe("E");
expect(bearingOf(target, { x: 6, y: 5 })).toBe("W");
expect(bearingOf(target, { x: 4, y: 4 })).toBe("SE");
expect(bearingOf(target, { x: 6, y: 6 })).toBe("NW");
});
it("returns north for a direct overlay impact", () => {
expect(bearingOf({ x: 3, y: 3 }, { x: 3, y: 3 })).toBe("N");
});
it("buckets ranges into bands", () => {
const target = { x: 0, y: 0 };
expect(rangeBandOf(target, { x: 2, y: 0 })).toBe("dangerClose");
expect(rangeBandOf(target, { x: 3, y: 0 })).toBe("close");
expect(rangeBandOf(target, { x: 4, y: 4 })).toBe("medium");
expect(rangeBandOf(target, { x: 9, y: 0 })).toBe("far");
expect(rangeBandLabel("dangerClose")).toBe("danger close");
});
it("builds a radio-style report for misses", () => {
const report = observerReport({ x: 5, y: 5 }, { x: 5, y: 8 });
expect(report.bearing).toBe("N");
expect(report.band).toBe("close");
expect(report.message).toBe("Shot, over. Target bearing N, range close.");
});
});
describe("call-for-fire corrections", () => {
it("moves impacts north on ADD and east on RIGHT", () => {
const size = 10;
// ADD 200 (4 cells north) and RIGHT 100 (2 cells east).
expect(applyCorrection({ x: 5, y: 7 }, { rangeM: 200, deflectionM: 100 }, size)).toEqual({
x: 7,
y: 3,
});
// DROP 100 (2 cells south) and LEFT 150 (3 cells west) move the opposite way.
expect(applyCorrection({ x: 5, y: 5 }, { rangeM: -100, deflectionM: -150 }, size)).toEqual({
x: 2,
y: 7,
});
});
it("rounds metres to the nearest cell", () => {
expect(applyCorrection({ x: 5, y: 5 }, { rangeM: 74, deflectionM: 26 }, 10)).toEqual({
x: 6,
y: 4,
});
});
it("clamps corrected impacts to the board", () => {
expect(applyCorrection({ x: 0, y: 0 }, { rangeM: 5000, deflectionM: -5000 }, 10)).toEqual({
x: 0,
y: 0,
});
expect(applyCorrection({ x: 9, y: 9 }, { rangeM: -5000, deflectionM: 5000 }, 10)).toEqual({
x: 9,
y: 9,
});
});
});
describe("call-for-fire scenarios", () => {
it("places the spotting round within the difficulty offset band", () => {
for (const key of ["patrol", "checkpoint", "compound"] as const) {
const { size, spotMinCells, spotMaxCells, targetInset } = CALL_FOR_FIRE_DIFFICULTIES[key];
for (let i = 0; i < 200; i++) {
const { target, spotting } = createScenario(key);
const offsetCells = Math.max(
Math.abs(target.x - spotting.x),
Math.abs(target.y - spotting.y),
);
// Chebyshev distance stays in band (rounding may add one cell).
expect(offsetCells).toBeLessThanOrEqual(spotMaxCells + 1);
// Targets stay interior; spotting rounds stay on the board.
expect(target.x).toBeGreaterThanOrEqual(targetInset);
expect(spotting.x).toBeGreaterThanOrEqual(0);
expect(spotting.x).toBeLessThan(size);
expect(spotting.y).toBeGreaterThanOrEqual(0);
expect(spotting.y).toBeLessThan(size);
}
}
});
it("is deterministic for a seeded rng", () => {
const a = createScenario("patrol", seededRng(42));
const b = createScenario("patrol", seededRng(42));
expect(a).toEqual(b);
});
it("generates different scenarios across seeds", () => {
const seen = new Set<string>();
for (let seed = 1; seed <= 20; seed++) {
seen.add(JSON.stringify(createScenario("checkpoint", seededRng(seed))));
}
expect(seen.size).toBeGreaterThan(5);
});
it("keeps target placement inside the interior inset region", () => {
for (const key of ["patrol", "checkpoint", "compound"] as const) {
for (let i = 0; i < 200; i++) {
const point = randomTargetPosition(key);
const { size, targetInset } = CALL_FOR_FIRE_DIFFICULTIES[key];
expect(point.x).toBeGreaterThanOrEqual(targetInset);
expect(point.x).toBeLessThanOrEqual(size - 1 - targetInset);
expect(point.y).toBeGreaterThanOrEqual(targetInset);
expect(point.y).toBeLessThanOrEqual(size - 1 - targetInset);
}
}
});
it("formats grid designations", () => {
expect(gridDesignation({ x: 0, y: 0 })).toBe("A1");
expect(gridDesignation({ x: 4, y: 6 })).toBe("E7");
});
});
describe("call-for-fire scoring", () => {
it("awards base plus round, time, and accuracy bonuses on a win", () => {
// Patrol: base 100, 4 rounds under par 4? none; 60s under par 90; 75m accuracy.
expect(calculateScore("patrol", 4, 30, 0, true)).toBe(100 + 60 + 75);
// Checkpoint: base 300 + 2 rounds under par * 40 + 0 time + 50 accuracy.
expect(calculateScore("checkpoint", 4, 120, 0, true)).toBe(300 + 2 * 40 + 50);
// Compound: base 600 + 3 rounds under par * 60 + 20s + 25 accuracy.
expect(calculateScore("compound", 5, 130, 25, true)).toBe(600 + 3 * 60 + 20 + 25);
});
it("never awards negative bonuses for slow or wasteful runs", () => {
expect(calculateScore("patrol", 8, 180, 75, true)).toBe(100);
});
it("scores losses as zero", () => {
expect(calculateScore("patrol", 2, 30, 0, false)).toBe(0);
});
it("derives xp from score with a floor of one on a win", () => {
expect(calculateXp(149, true)).toBe(2);
expect(calculateXp(100, true)).toBe(2);
expect(calculateXp(50, true)).toBe(1);
expect(calculateXp(10, true)).toBe(1);
expect(calculateXp(600, false)).toBe(0);
});
it("reports tube accuracy from the final round's distance to target", () => {
// Direct hit: 1.0. Patrol lethal radius is 75m.
expect(calculateAccuracy("patrol", 0)).toBe(1);
// Half the radius out: 0.5.
expect(calculateAccuracy("patrol", 37.5)).toBeCloseTo(0.5);
// At or beyond the radius: 0 (never negative for a loss).
expect(calculateAccuracy("patrol", 75)).toBe(0);
expect(calculateAccuracy("patrol", 500)).toBe(0);
// Checkpoint radius is 50m, so a 25m miss is 0.5 there too.
expect(calculateAccuracy("checkpoint", 25)).toBeCloseTo(0.5);
});
});

View file

@ -79,7 +79,7 @@ describe("Minigame registry", () => {
.catch(() => undefined);
});
it("falls back to the built-in seven when the registry is empty", async () => {
it("falls back to the built-in eight when the registry is empty", async () => {
const games = await loadMinigameRegistry(payload);
expect(games).toHaveLength(BUILTIN_MINIGAMES.length);
expect(games.map((game) => game.key)).toEqual(BUILTIN_MINIGAMES.map((game) => game.key));