1
0
Fork 0
polaris-task-force/src/lib/minigames/call-for-fire-versus/engine.ts
Z8MB1E 49782365c2 chore(call-for-fire-versus): finish place/structure wording in help and errors
Completes the terminology pass: the "How to place" help block and the
engine's user-facing error strings ("Missing structure", "Structures cannot
overlap", "Placement is closed", "The opponent has not placed their
structures") now match the place/structure/target vocabulary used elsewhere
in the duel. Also splits a comment that had been merged onto the scoreOf
declaration. Strings only; no behavior change.
2026-10-12 00:01:34 -04:00

370 lines
12 KiB
TypeScript

/**
* 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);
}