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.
335 lines
11 KiB
TypeScript
335 lines
11 KiB
TypeScript
/**
|
|
* 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}`;
|
|
}
|