1
0
Fork 0

Compare commits

...

6 commits

Author SHA1 Message Date
869d2944b3 v0.12.7 - widescreen page layouts, minigame touch controls 2026-10-19 10:57:23 -04:00
977aa26664 docs: add v0.12.7 changelog entry 2026-10-19 10:57:18 -04:00
c149f07347 fix(ui): unify remaining page caps to 96rem and repair story xl cap
Raise the centered operations, supply-boxes, campaigns, factions and
missions wrappers from max-w-7xl to the same max-w-[96rem] used by the
logistics detail pages so all capped pages share one width.

The story page used xl:max-w-screen-2xl, a utility Tailwind v4 removed,
so that override silently did nothing; swap it for xl:max-w-[96rem],
which restores the intended wider gutter layout on xl screens.
2026-10-19 10:52:04 -04:00
9f05351798 fix(ui): center and widen left-aligned detail pages
Structure, vehicle, resource, shipment, banking, profile and awards
pages capped content at max-w-7xl pinned to the left edge, so all
slack pooled on the right on wide monitors (worse with the sidebar
hidden). Raise the cap to 96rem and center it, matching the existing
mx-auto convention on operations and intelligence pages.
2026-10-19 10:50:35 -04:00
ce682becec feat(minigames): touch controls and responsive board for Bomperator
- Extract pressDir/releaseDir/stopAll edge callbacks; keyboard, D-pad and
  swipes all feed the same held-stack path (prediction, keepalives and the
  pending ledger stay input-source agnostic)
- BomperatorTouchControls: 4-way pad + stop center + plant button on coarse
  pointers, per-button pointer capture for hold-and-plant multi-touch
- Board gestures: dominant-axis swipe sets direction, quick tap stops
- Canvas scales via CSS (w-full h-auto, fixed internal buffer), so prediction
  is viewport-independent; touch-action/overscroll guards on the board
- Harness: backgrounded-tab scenario (4s rAF freeze under prod trace replay)
  proves resume never teleports (teleports=0, maxJump 0.43)
- E2E smoke at 390x844 hasTouch: page loads without horizontal overflow
2026-10-19 10:11:30 -04:00
a72f1bbe03 feat(call-for-fire-versus): resize fleet, add second FOB, charred destroyed cells with burn effect
Command Post becomes a 3x2 rect that flips wide/tall, the Ammo Depot L grows to four cells, the FOB becomes two cells, and a second FOB (Forward Operating Base II) joins the fleet for 16 cells across five structures. Fully destroyed structures now render charred black instead of red, and their cells burn with flame and ember particles for 45 seconds after destruction, driven by a new impact timestamp on each shot.
2026-10-19 09:34:40 -04:00
34 changed files with 675 additions and 106 deletions

View file

@ -1,5 +1,21 @@
# Changelog
# v0.12.7
Detail pages finally fill a widescreen monitor, and Ordnance Disposal comes to phones and tablets.
### Improvements
- **Layout.** Structure, vehicle, resource, shipment, banking, profile, awards, operations and intelligence pages now stretch wider on large monitors and center themselves when the sidebar is hidden, instead of leaving a dead strip on the right.
- **Ordnance Disposal.** Touch controls (D-pad and swipes) with a responsive board make the game playable on phones and tablets.
- **Call for Fire (Versus).** The fleet has been resized, a second forward operating base joins the battlefield, and destroyed cells now scorch with lingering burn effects.
### Fixes
- **Chronicle.** The wide reading layout on extra-large monitors is restored; an outdated Tailwind class had silently disabled it.
---
# v0.12.6
Ordnance Disposal no longer yanks technicians backward during fast play.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.12.6",
"version": "0.12.7",
"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

@ -130,7 +130,7 @@ export default async function AwardsPage() {
}
return (
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<div className="p-5 flex flex-col gap-6 mx-auto w-full max-w-[96rem]">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="flex flex-col gap-1.5" data-tour="page-header">
<div className="flex items-center gap-2">

View file

@ -207,7 +207,7 @@ export default async function CampaignDetailPage({ params }: CampaignDetailPageP
</div>
</header>
<div className="p-5 flex flex-col gap-6 max-w-7xl mx-auto w-full">
<div className="p-5 flex flex-col gap-6 max-w-[96rem] mx-auto w-full">
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
{/* ── Main Content (2/3) ──────────────────────────── */}
<div className="xl:col-span-2 flex flex-col gap-6">

View file

@ -223,7 +223,7 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
</div>
</header>
<div className="p-5 flex flex-col gap-6 max-w-7xl mx-auto w-full">
<div className="p-5 flex flex-col gap-6 max-w-[96rem] mx-auto w-full">
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
{/* ── Main Content (2/3) ──────────────────────────── */}
<div className="xl:col-span-2 flex flex-col gap-6">

View file

@ -355,7 +355,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
<div className="absolute inset-0 bg-gradient-to-r from-black/30 via-transparent to-black/40" />
<div className="relative z-10 mt-auto flex flex-col px-5 pb-6 pt-14 md:absolute md:inset-0 md:justify-end md:px-10 md:py-10 lg:px-12">
<div className="mx-auto flex w-full max-w-7xl flex-col">
<div className="mx-auto flex w-full max-w-[96rem] flex-col">
<div className="z-20 mb-4 flex flex-wrap gap-2 md:absolute md:top-4 md:right-4 md:mb-0">
<span
className={`rounded-md border border-white/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-wider backdrop-blur-sm ${statusColors[mission.ownershipAndStatus.status] ?? "bg-muted text-muted-foreground"}`}
@ -455,7 +455,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
</div>
</header>
<div className="p-5 flex flex-col gap-6 max-w-7xl mx-auto w-full">
<div className="p-5 flex flex-col gap-6 max-w-[96rem] mx-auto w-full">
{planningMapEnabled && canDelegate && (
<PlanningAccessControl
missionId={mission.id}

View file

@ -74,7 +74,7 @@ export default async function AccountPage({ params }: AccountPageProps) {
const currencyConfig = await getCurrencyConfig(payload);
return (
<div className="p-5 max-w-7xl">
<div className="p-5 mx-auto w-full max-w-[96rem]">
<AccountDetail
account={typedAccount}
ledger={ledger}

View file

@ -69,7 +69,7 @@ export default async function GameVehicleDetailPage({ params }: GameVehicleDetai
const resourceCount = storedResources.length;
return (
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<div className="p-5 flex flex-col gap-6 mx-auto w-full max-w-[96rem]">
<Link
href="/logistics/garage"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"

View file

@ -106,7 +106,7 @@ export default async function ResourceDetailPage({ params }: ResourceDetailPageP
];
return (
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<div className="p-5 flex flex-col gap-6 mx-auto w-full max-w-[96rem]">
<Link
href="/logistics/resources"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"

View file

@ -95,7 +95,7 @@ export default async function ShipmentDetailPage({ params }: ShipmentDetailPageP
shipment.fuelCost > 0 ? ((shipment.fuelConsumed ?? 0) / shipment.fuelCost) * 100 : 0;
return (
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<div className="p-5 flex flex-col gap-6 mx-auto w-full max-w-[96rem]">
<Link
href="/logistics/shipments"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"

View file

@ -319,7 +319,7 @@ export default async function StructureDetailPage({ params }: StructureDetailPag
});
return (
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<div className="p-5 flex flex-col gap-6 mx-auto w-full max-w-[96rem]">
<header
className={`relative flex flex-col gap-3 overflow-hidden rounded-lg${
imageUrl ? " min-h-[280px] justify-between border border-border p-5" : ""

View file

@ -136,7 +136,7 @@ export default async function SupplyBoxDetailPage({ params }: { params: Promise<
if (capability === false) {
return (
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6">
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<PageShell title="Supply Box" meta="LOGISTICS // CRATE SYNC">
<NoticeState
variant="error"
@ -150,7 +150,7 @@ export default async function SupplyBoxDetailPage({ params }: { params: Promise<
if (box === null) {
return (
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6">
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<PageShell title="Supply Box" meta="LOGISTICS // CRATE SYNC">
<NoticeState
variant="error"
@ -186,7 +186,7 @@ export default async function SupplyBoxDetailPage({ params }: { params: Promise<
];
return (
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6">
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<PageShell title={box.boxId} meta="SUPPLY BOX // DETAIL">
<Link
href="/logistics/supply-boxes"

View file

@ -148,7 +148,7 @@ export default async function SupplyBoxesPage() {
const data = await getSupplyBoxList(payload, surfaceUser);
return (
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6">
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<PageShell title="Supply Boxes" meta="LOGISTICS // CRATE SYNC">
<p className="max-w-2xl text-sm text-white/70">
Crate inventory synced from the game server through the Arma bridge. Rows show the newest

View file

@ -85,7 +85,7 @@ export default async function VehicleDetailPage({ params }: VehicleDetailPagePro
) ?? [];
return (
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<div className="p-5 flex flex-col gap-6 mx-auto w-full max-w-[96rem]">
<Link
href="/logistics/vehicles"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"

View file

@ -49,7 +49,7 @@ export default async function OperationAarPage({
: [];
return (
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6">
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<OperationsRealtimeRefresher />
<PageShell title={`Operation ${operationId}`} meta="AFTER-ACTION REPORT // PROVENANCE LINKED">
{aar === null ? (

View file

@ -50,7 +50,7 @@ export default async function OperationsLedgerPage({
);
return (
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6">
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<OperationsRealtimeRefresher />
<PageShell
title="Operations ledger"

View file

@ -30,7 +30,7 @@ export default async function OperationsPage() {
const overview = await getOperationOverview(payload, surfaceUser);
return (
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6">
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<OperationsRealtimeRefresher />
<PageShell title="Operations" meta="OPERATION FEED // AFTER-ACTION RECORDS" dataTour="page-header">
<p className="max-w-2xl text-sm text-white/70">

View file

@ -88,7 +88,7 @@ export default async function ReservationDetailPage({
if (reservation === null) {
return (
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6">
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<PageShell title="Reservation" meta="ALLOCATION RESERVATIONS // COMMAND VIEW">
<NoticeState
variant="error"
@ -121,7 +121,7 @@ export default async function ReservationDetailPage({
];
return (
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6">
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<PageShell title={reservation.reservationKey} meta="RESERVATION // DETAIL">
<Link
href="/operations/reservations"

View file

@ -110,7 +110,7 @@ export default async function ReservationsPage({
const options = canCreate && user ? await listReservationOptions(payload, user) : null;
return (
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6">
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<PageShell title="Reservations" meta="ALLOCATION RESERVATIONS // COMMAND VIEW">
<p className="max-w-2xl text-sm text-white/70">
Every allocation of people, vehicles, cargo, and treasury budget against an operation,

View file

@ -466,7 +466,7 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
: `${remainingMonths} mo`;
return (
<div className="p-5 flex flex-col gap-6 max-w-7xl">
<div className="p-5 flex flex-col gap-6 mx-auto w-full max-w-[96rem]">
<Link
href="/"
className="py-1 text-sm text-muted-foreground hover:text-primary transition-colors flex items-center gap-1 w-fit"

View file

@ -109,7 +109,7 @@ export default async function StoryPage() {
}));
return (
<div className="mx-auto max-w-3xl px-4 py-10 xl:max-w-screen-2xl">
<div className="mx-auto max-w-3xl px-4 py-10 xl:max-w-[96rem]">
<div className="xl:grid xl:grid-cols-[minmax(0,1fr)_minmax(0,48rem)_minmax(0,1fr)] xl:gap-8">
<div className="min-w-0 xl:col-start-2">
<header className="mb-12 text-center">

View file

@ -2101,6 +2101,115 @@
}
}
/* Burning wreckage on destroyed Call-for-Fire-versus cells (~45s per cell). */
.versus-burn {
position: absolute;
inset: 0;
z-index: 1;
overflow: hidden;
border-radius: inherit;
pointer-events: none;
}
.versus-burn::before,
.versus-burn::after {
content: "";
position: absolute;
left: 50%;
bottom: -8%;
width: 72%;
height: 88%;
transform-origin: 50% 100%;
background: radial-gradient(
ellipse at 50% 100%,
rgba(251, 146, 60, 0.9) 0%,
rgba(239, 68, 68, 0.5) 45%,
rgba(127, 29, 29, 0) 75%
);
animation: versus-flame 900ms ease-in-out infinite alternate;
}
.versus-burn::after {
width: 42%;
height: 62%;
background: radial-gradient(
ellipse at 50% 100%,
rgba(254, 240, 138, 0.95) 0%,
rgba(251, 146, 60, 0.6) 55%,
rgba(251, 146, 60, 0) 85%
);
animation-duration: 620ms;
animation-delay: -280ms;
}
.versus-ember {
position: absolute;
bottom: 14%;
left: 50%;
width: 3px;
height: 3px;
border-radius: 9999px;
background: rgba(253, 186, 116, 0.95);
animation: versus-ember-rise 1.5s linear infinite;
}
.versus-ember:nth-child(2) {
left: 30%;
animation-delay: 0.5s;
}
.versus-ember:nth-child(3) {
left: 68%;
animation-delay: 1s;
background: rgba(252, 165, 165, 0.9);
}
@keyframes versus-flame {
0% {
transform: translateX(-50%) scale(0.85, 0.7);
opacity: 0.7;
}
50% {
transform: translateX(-50%) scale(1.05, 1);
opacity: 1;
}
100% {
transform: translateX(-50%) scale(0.9, 0.8);
opacity: 0.75;
}
}
@keyframes versus-ember-rise {
0% {
transform: translateY(0) scale(1);
opacity: 0;
}
12% {
opacity: 1;
}
100% {
transform: translateY(-14px) scale(0.3);
opacity: 0;
}
}
@media (prefers-reduced-motion: reduce) {
.versus-burn::before,
.versus-burn::after,
.versus-ember {
animation: none;
}
.versus-burn::before {
opacity: 0.55;
}
.versus-burn::after {
display: none;
}
.versus-ember {
display: none;
}
}
.poker-action-console:not(.poker-action-console-complete) {
grid-template-columns: minmax(0, 1.5fr) minmax(10rem, 0.8fr);
}

View file

@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
import { Eye, Flag, Play, Radio, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@ -12,6 +12,7 @@ import {
} from "@/lib/minigames/bomperator/prediction";
import { sendBomperatorInput } from "@/app/(frontend)/minigames/bomperator/actions";
import { BomperatorHud, seatColor } from "./BomperatorHud";
import { BomperatorTouchControls } from "./BomperatorTouchControls";
import { useBomperatorSounds } from "./sounds";
import { BomperatorSoundToggle } from "./BomperatorSoundToggle";
@ -455,6 +456,33 @@ export function BomperatorGame({
[match.matchId],
);
/**
* Shared edge-send plumbing for EVERY input source (keyboard, D-pad, swipe).
* The held-stack owns priority (newest first); each edge sends the current
* top so the server always holds our latest intent. Touch handlers in
* BomperatorTouchControls call exactly these, keeping prediction, keepalives
* and the pending ledger source-agnostic.
*/
const pressDir = useCallback(
(dir: Dir) => {
heldKeysRef.current = [dir, ...heldKeysRef.current.filter((d) => d !== dir)];
sendDir(heldKeysRef.current[0] ?? null);
},
[sendDir],
);
const releaseDir = useCallback(
(dir: Dir) => {
heldKeysRef.current = heldKeysRef.current.filter((d) => d !== dir);
sendDir(heldKeysRef.current[0] ?? null);
},
[sendDir],
);
const stopAll = useCallback(() => {
if (heldKeysRef.current.length === 0) return;
heldKeysRef.current = [];
sendDir(null);
}, [sendDir]);
useEffect(() => {
if (!canControl) return;
@ -471,14 +499,12 @@ export function BomperatorGame({
const dir = KEY_DIR[e.code];
if (!dir) return;
e.preventDefault();
heldKeysRef.current = [dir, ...heldKeysRef.current.filter((d) => d !== dir)];
sendDir(heldKeysRef.current[0] ?? null);
pressDir(dir);
};
const onKeyUp = (e: KeyboardEvent) => {
const dir = KEY_DIR[e.code];
if (!dir) return;
heldKeysRef.current = heldKeysRef.current.filter((d) => d !== dir);
sendDir(heldKeysRef.current[0] ?? null);
releaseDir(dir);
};
window.addEventListener("keydown", onKeyDown, { capture: true });
window.addEventListener("keyup", onKeyUp, { capture: true });
@ -496,7 +522,36 @@ export function BomperatorGame({
window.clearInterval(keepalive);
heldKeysRef.current = [];
};
}, [canControl, match.matchId, sendDrop, sendDir]);
}, [canControl, match.matchId, pressDir, releaseDir, sendDir, sendDrop]);
/* ---- board swipes (touch): swipe sets direction, tap stops ---- */
const swipeRef = useRef<{ x: number; y: number; t: number; fired: boolean } | null>(null);
const onBoardPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
if (e.pointerType === "mouse" || !canControl) return;
swipeRef.current = { x: e.clientX, y: e.clientY, t: performance.now(), fired: false };
};
const onBoardPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
const s = swipeRef.current;
if (!s || s.fired) return;
const dx = e.clientX - s.x;
const dy = e.clientY - s.y;
if (Math.hypot(dx, dy) < 24) return;
s.fired = true;
// Dominant axis, cardinal only: movement is grid-locked, so one swipe
// commits one leg. The held stack keeps priority, so a swipe simply sits
// on top of whatever the D-pad holds and releases back to it.
pressDir(
Math.abs(dx) >= Math.abs(dy) ? (dx > 0 ? "right" : "left") : dy > 0 ? "down" : "up",
);
};
const onBoardPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {
const s = swipeRef.current;
swipeRef.current = null;
if (!s || s.fired || e.pointerType === "mouse") return;
// A quick tap that never crossed the swipe threshold means "stop".
if (performance.now() - s.t < 300) stopAll();
};
/* ---- render loop: predict our own seat, ease the rest toward snapshots ---- */
@ -507,8 +562,9 @@ export function BomperatorGame({
const dpr = window.devicePixelRatio || 1;
canvas.width = CANVAS_W * dpr;
canvas.height = CANVAS_H * dpr;
canvas.style.width = `${CANVAS_W}px`;
canvas.style.height = `${CANVAS_H}px`;
// CSS owns the display size (responsive wrapper + h-auto keeps the
// intrinsic aspect ratio); the internal buffer stays CANVAS_* * dpr so
// rendering and prediction never depend on the viewport.
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.scale(dpr, dpr);
@ -901,10 +957,16 @@ export function BomperatorGame({
<BomperatorHud match={match} currentUserId={currentUserId} />
<div className="relative mx-auto w-full max-w-[520px]">
<div
className="relative mx-auto w-full max-w-[520px] touch-none select-none overscroll-contain"
onPointerDown={onBoardPointerDown}
onPointerMove={onBoardPointerMove}
onPointerUp={onBoardPointerUp}
onPointerCancel={onBoardPointerUp}
>
<canvas
ref={canvasRef}
className="block w-full rounded-xl border border-border shadow-lg"
className="block h-auto w-full rounded-xl border border-border shadow-lg"
aria-label="Ordnance Disposal arena"
/>
{match.phase === "countdown" && (
@ -932,8 +994,20 @@ export function BomperatorGame({
)}
</div>
{canControl && (
<BomperatorTouchControls
onPress={pressDir}
onRelease={releaseDir}
onStop={stopAll}
onDrop={() => void sendDrop()}
/>
)}
<p className="text-center text-[11px] text-muted-foreground">
Move: WASD / arrows · Plant charge: Space
<span className="[@media(pointer:coarse)]:hidden">Move: WASD / arrows · Plant charge: Space</span>
<span className="hidden [@media(pointer:coarse)]:inline">
Swipe or hold the pad to move · tap board or stop key to halt · bomb button plants a charge
</span>
</p>
</div>
);

View file

@ -0,0 +1,106 @@
"use client";
import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
import { Button } from "@/components/ui/button";
import type { Dir } from "@/lib/minigames/bomperator/types";
import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Bomb, Square } from "lucide-react";
interface BomperatorTouchControlsProps {
onPress: (dir: Dir) => void;
onRelease: (dir: Dir) => void;
onStop: () => void;
onDrop: () => void;
}
/**
* Touch controls for Ordnance Disposal: a 4-way D-pad with a stop key under
* the left thumb, a large plant button under the right. Rendered only on
* coarse pointers (phones/tablets); keyboard users never see it.
*
* The buttons feed the SAME press/release edge path as the keyboard handlers
* (pressDir/releaseDir in BomperatorGame), so prediction, keepalives and the
* pending ledger stay input-source agnostic. Hold semantics mirror keys:
* pressing a direction moves, releasing stops at the next cell center. Each
* button captures its own pointer so holding a direction while tapping plant
* works; cancel/lost-capture release paths keep the held stack honest when an
* OS gesture steals the touch mid-hold.
*/
export function BomperatorTouchControls({
onPress,
onRelease,
onStop,
onDrop,
}: BomperatorTouchControlsProps) {
const hold = (dir: Dir) => (e: ReactPointerEvent<HTMLButtonElement>) => {
e.preventDefault();
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
// Pointer already gone; the press still counts.
}
onPress(dir);
};
const lift = (dir: Dir) => () => {
onRelease(dir);
};
const pad = (dir: Dir, label: string, icon: ReactNode) => (
<Button
key={dir}
variant="secondary"
className="size-14 rounded-lg p-0"
aria-label={label}
onPointerDown={hold(dir)}
onPointerUp={lift(dir)}
onPointerCancel={lift(dir)}
onLostPointerCapture={lift(dir)}
>
{icon}
</Button>
);
return (
<div
className="mx-auto hidden w-full max-w-[520px] touch-none select-none items-center justify-between px-4 pb-1 pt-3 [@media(pointer:coarse)]:flex"
aria-label="Touch controls"
>
<div className="grid grid-cols-3 grid-rows-3 gap-1">
<span />
{pad("up", "Move up", <ArrowUp className="size-6" />)}
<span />
{pad("left", "Move left", <ArrowLeft className="size-6" />)}
<Button
variant="outline"
className="size-14 rounded-lg p-0"
aria-label="Stop"
onPointerDown={(e) => {
e.preventDefault();
onStop();
}}
>
<Square className="size-4" />
</Button>
{pad("right", "Move right", <ArrowRight className="size-6" />)}
<span />
{pad("down", "Move down", <ArrowDown className="size-6" />)}
<span />
</div>
<Button
variant="default"
className="size-20 rounded-full p-0"
aria-label="Plant charge"
onPointerDown={(e) => {
e.preventDefault();
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
// Pointer already gone; the press still counts.
}
onDrop();
}}
>
<Bomb className="size-8" />
</Button>
</div>
);
}

View file

@ -14,6 +14,7 @@ import {
import { gridDesignation, METERS_PER_CELL, type GridPoint } from "@/lib/minigames/call-for-fire";
import {
FOB_FLEET,
VERSUS_BURN_MS,
VERSUS_WAITING_USER_ID,
type FobPlacement,
type FobRotation,
@ -50,8 +51,16 @@ const FOB_STYLES: Record<string, { cell: string; swatch: string; ring: string }>
swatch: "bg-violet-400",
ring: "border-violet-500/60",
},
"fob-2": {
cell: "border-emerald-500/70 bg-emerald-500/30 text-emerald-50",
swatch: "bg-emerald-400",
ring: "border-emerald-500/60",
},
};
/** Charred look for a fully destroyed structure's cells. */
const DESTROYED_CELL = "border-zinc-500/40 bg-zinc-950 text-zinc-600";
function fobStyle(id: string) {
return (
FOB_STYLES[id] ?? {
@ -66,13 +75,14 @@ function fobStyle(id: string) {
function turnsForShape(shape: FobShape): number {
if (shape === "square") return 1;
if (shape === "l") return 4;
return 2;
return 2; // line and rect flip between two orientations
}
/** Toggle-button label for the selected emplacement's current orientation. */
function rotationLabel(shape: FobShape, orientation: FobRotation): string {
if (shape === "square") return "Fixed";
if (shape === "l") return "Rotate 90°";
if (shape === "rect") return orientation % 2 === 0 ? "Wide" : "Tall";
return orientation % 2 === 0 ? "Horizontal" : "Vertical";
}
@ -388,7 +398,7 @@ function PlacementPhase({
size="sm"
className="h-auto"
disabled={selectedIsSquare}
title={selectedIsSquare ? "The Command Post is a fixed 2x2 block." : undefined}
title={selectedIsSquare ? "This structure has a fixed orientation." : undefined}
onClick={toggleOrientation}
>
<RotateCcw /> {rotationLabel(selectedDefinition.shape, effectiveOrientation)}
@ -432,8 +442,8 @@ function PlacementPhase({
<li>Click a placed structure to pick it up, then click a new cell to move it.</li>
<li>
Double-click a placed structure, or press the rotate toggle, to rotate it in place.
The Command Post is a fixed 2x2 block and does not rotate; the Ammo Depot is an L and
turns through four orientations.
The Command Post is a 3x2 block that flips between wide and tall; the Ammo Depot is
a four-cell L and turns through four orientations.
</li>
<li>The toggle also sets the orientation used for your next placement.</li>
<li>Structures cannot overlap, and your opponent never sees your layout.</li>
@ -513,6 +523,59 @@ function buildBoards(you: VersusMatchView["you"]) {
return { myCells, incoming, myShots };
}
/**
* Cells still burning on each board. A structure burns for VERSUS_BURN_MS from
* the instant its destroying round landed; after that its cells stay charred.
*/
function burnSets(
you: VersusMatchView["you"],
now: number,
): { mine: Set<string>; enemy: Set<string> } {
const mine = new Set<string>();
const enemy = new Set<string>();
const freshKill = (shot: VersusShotView) => {
if (shot.outcome !== "destroyed" || !shot.assetId) return false;
const at = Date.parse(shot.at);
return Number.isFinite(at) && now - at < VERSUS_BURN_MS;
};
// Own board: the defender knows their full layout, so every cell of a
// reduced structure burns.
for (const shot of you.incoming) {
if (!freshKill(shot)) continue;
const fob = you.fleet.find((candidate) => candidate.id === shot.assetId);
for (const cell of fob?.cells ?? []) mine.add(key(cell));
}
// Enemy sector: the shooter only knows the cells they struck, which is
// exactly every cell of a structure they just destroyed.
for (const shot of you.shots) {
if (!freshKill(shot)) continue;
for (const other of you.shots) {
if (other.assetId === shot.assetId) enemy.add(key(other.grid));
}
}
return { mine, enemy };
}
/** Asset ids whose structure has been fully destroyed (from my fire). */
function destroyedAssetIds(shots: VersusMatchView["you"]["shots"]): Set<string> {
const ids = new Set<string>();
for (const shot of shots) {
if (shot.outcome === "destroyed" && shot.assetId) ids.add(shot.assetId);
}
return ids;
}
/** Flickering flame and ember particles over a freshly destroyed cell. */
function BurnFlames() {
return (
<span className="versus-burn" aria-hidden="true">
<span className="versus-ember" />
<span className="versus-ember" />
<span className="versus-ember" />
</span>
);
}
function BattlePhase({
match,
currentUserId,
@ -534,6 +597,8 @@ function BattlePhase({
const yourTurn = match.turnUserId !== null && String(match.turnUserId) === String(currentUserId);
const boards = buildBoards(you);
const burn = useMemo(() => burnSets(you, now), [you, now]);
const enemyDown = useMemo(() => destroyedAssetIds(you.shots), [you.shots]);
const firstShot = you.lastImpact === null;
// Only animate explosions for shots that arrive while watching (not those
// already on the board when the page loaded).
@ -614,7 +679,7 @@ function BattlePhase({
<div className="grid gap-4 lg:grid-cols-2">
<BoardPanel
title="Your fire bases"
subtitle="Incoming rounds are marked. Structures turn red when reduced."
subtitle="Incoming rounds are marked. Reduced structures burn out and go dark."
>
{Array.from({ length: BOARD }, (_, y) => (
<ReadOnlyRow key={y} y={y}>
@ -628,9 +693,10 @@ function BattlePhase({
label={`grid ${cellLabel(x, y)}`}
className={cn(
fob && !destroyed && fobStyle(fob.id).cell,
fob && destroyed && "border-red-500/70 bg-red-600/50 text-red-50",
fob && destroyed && DESTROYED_CELL,
)}
>
{burn.mine.has(`${x},${y}`) && <BurnFlames />}
{fob ? "▣" : ""}
{hit && (
<span
@ -674,17 +740,20 @@ function BattlePhase({
{Array.from({ length: BOARD }, (_, x) => {
const shot = boards.myShots.get(`${x},${y}`);
const pending = pendingGrid && pendingGrid.x === x && pendingGrid.y === y;
// Every cell of an enemy structure you fully destroyed goes dark.
const structureDown = Boolean(
shot?.shot.assetId && enemyDown.has(shot.shot.assetId),
);
return (
<ReadOnlyCell
key={`${x}-${y}`}
label={`grid ${cellLabel(x, y)}`}
className={cn(
shot && shot.shot.outcome === "hit" && shot.shot.assetId
? fobStyle(shot.shot.assetId).cell
: undefined,
shot &&
shot.shot.outcome === "destroyed" &&
"border-red-500/70 bg-red-600/40 text-red-50",
shot && structureDown
? DESTROYED_CELL
: shot && shot.shot.outcome === "hit" && shot.shot.assetId
? fobStyle(shot.shot.assetId).cell
: undefined,
shot &&
shot.shot.outcome === "hit" &&
!shot.shot.assetId &&
@ -694,6 +763,7 @@ function BattlePhase({
interactive={Boolean(yourTurn && firstShot)}
onClick={() => setPendingGrid({ x, y })}
>
{burn.enemy.has(`${x},${y}`) && <BurnFlames />}
{pending ? "◉" : shot ? (shot.shot.outcome === "miss" ? "•" : "✕") : ""}
{shot &&
shot.shot.outcome !== "miss" &&

View file

@ -12,6 +12,7 @@ Five XP-earning minigames under one parent: routes live at `/minigames/*` (moved
- **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`).
- **Ordnance Disposal (multiplayer, real-time)**: `/minigames/bomperator` (internal key `bomperator`, label "Ordnance Disposal"), category `multiplayer` (out of periods), a 2-8 player free-for-all Bomberman-style charge-clearing drill. Same pure-engine + in-memory-registry split as CFF versus, but upgraded from turn-based to a **fixed ~20 Hz tick loop** (was ~10 Hz until v0.12.3; every tick-denominated constant doubles with the rate so real-world durations stay identical): `src/lib/minigames/bomperator/{constants,types,engine,views}.ts` are pure/client-safe (seeded RNG via `state.rngState`/`gridSeed`; `generateGrid`, `createMatchState`, `startRound`, `applyInput`, `tick`), and `registry.ts` runs one `setInterval(TICK_MS)` per live match (started on `startMatch`, cleared on complete/dissolve; `globalThis.__bomperatorMatches`; SINGLE-INSTANCE ONLY: a restart/redeploy kills live matches). Grid is 15x13 (border + even/even pillars + seeded crates with one hidden power-up each; four classic pickups bomb/range/speed/kick). Movement is grid-locked with sub-cell interpolation; charges fuse ~2.5s, cross-flames stop at walls, destroy crates, chain-detonate, and kick-push; round ends at <=1 alive; sudden death spawns random-cell explosions after the 150s timer, with a draw guard. FFA has no hidden info so `buildBomperatorView` serves every viewer the same board (`yourSeat: null` = spectator). Clients POST inputs (`sendBomperatorInput`, rate-limited 40/s) and poll `fetchBomperatorMatch` (~500ms fallback behind the SSE stream); a rolling event buffer (monotonic ids) drives client SFX without diffing. Disconnects hold the seat for `RECONNECT_WINDOW_MS` then eliminate; below two active seats the match dissolves. Rewards on completion via `stats.ts` (`minigame:bomperator`, profile group `bomperator`: matchesPlayed/matchWins/roundsWon/kills/xpEarned; XP win/loss base + per-kill bounty, chips auto-derived). Registry row ships `status: "upcoming"` (page renders `MinigameComingSoon` until an admin flips it active).
- **Client prediction & correction**: `BomperatorGame.tsx` predicts its own seat between snapshots and reconciles with a lead-aware envelope policy (helpers in `bomperator/prediction.ts`): gaps inside `max(PRED_DEADZONE, speed*(rttAvg/2 + TICK_MS/2 + PRED_ENVELOPE_BUDGET_MS)/1000)` ride untouched, anything beyond is trimmed on EVERY snapshot, and gaps past 2.5 cells ease toward the estimate at up to 2.5x run speed instead of teleporting (round resets still snap via the ack-backwards branch). Root cause of the old teleport-back: Node event-loop stalls make the server's 20Hz tick loop DROP setInterval callbacks (no catch-up), so the sim permanently lags wall clock; the old all-inputs-acked pull let that gap stack and discharge at once. `tests/int/bomperator-prediction.int.spec.ts` is an offline deterministic harness (real engine + modeled network + frame-by-frame reconcile mirror) including production-latency replay (`tests/fixtures/bomperator-prod-rtt.json`, from HAR) and a server-stall A/B proof; change client prediction in BOTH component and mirror, and run the trace scenarios before shipping. v0.12.4 lesson (reverted in v0.12.5): do not add mechanisms that trust precise latency estimates (decision nudges, projected ghost placement); real TTFB swings 31-463ms and they glitch under it.
- **Mobile / touch input**: `BomperatorTouchControls.tsx` renders a D-pad (+ stop) and plant button on coarse pointers only (`(pointer: coarse)`); the board itself accepts swipes (dominant-axis cardinal, sets direction) and taps (stop). ALL input sources feed the same `pressDir`/`releaseDir`/`stopAll` edge callbacks in `BomperatorGame.tsx` that keyboard uses, so prediction/keepalive/pending logic stays source-agnostic; held-stack priority makes D-pad + swipe coexist. Canvas is CSS-scaled (`w-full h-auto`, max 520px wrapper) with fixed internal resolution. Backgrounded-tab safety is harness-proven ("backgrounded tab" scenario: 4s rAF freeze under prod trace replay, teleports=0). E2E smoke: `tests/e2e/bomperator-mobile.e2e.spec.ts` (phone viewport, no horizontal overflow); run with `E2E_BROWSER_PATH=<playwright chromium>` when Vivaldi crashes.
- 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

@ -26,31 +26,40 @@ 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 type FobShape = "line" | "square" | "rect" | "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. */
/**
* "line" is straight, "square" is an NxN block, "rect" is a width x height
* block (rotates between wide and tall), "l" is a corner with one long arm
* (`size - 2` cells) and one short arm (1 cell) around a fixed elbow.
*/
readonly shape: FobShape;
/** Width in cells; only meaningful for the "rect" shape. */
readonly width?: number;
/** Height in cells; only meaningful for the "rect" shape. */
readonly height?: number;
}
/**
* The emplacement fleet each player hides. Total occupied cells are 10 of 100,
* The emplacement fleet each player hides. Total occupied cells are 16 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: "command-post", label: "Command Post", size: 6, shape: "rect", width: 3, height: 2 },
{ id: "ammo-depot", label: "Ammo Depot", size: 4, shape: "l" },
{ id: "radar-site", label: "Radar Site", size: 2, shape: "line" },
{ id: "fob", label: "Forward Operating Base", size: 1, shape: "line" },
{ id: "fob", label: "Forward Operating Base", size: 2, shape: "line" },
{ id: "fob-2", label: "Forward Operating Base II", size: 2, shape: "line" },
];
/**
* Quarter-turns clockwise. Lines use 0 (horizontal) and 1 (vertical); the
* square ignores it; the L uses all four.
* rect uses 0 (wide) and 1 (tall); the square ignores it; the L uses all four.
*/
export type FobRotation = 0 | 1 | 2 | 3;
@ -64,6 +73,13 @@ export interface FobPlacement {
export const VERSUS_SCORE_PER_FOB = 100;
export const VERSUS_SCORE_PER_CELL = 1;
/**
* How long a destroyed structure's cells keep burning on the client before
* they settle to charred black. Purely cosmetic; the engine only stamps when
* each structure died.
*/
export const VERSUS_BURN_MS = 45_000;
/** XP payout on match completion. */
export const VERSUS_XP_WIN = 40;
export const VERSUS_XP_LOSS = 10;

View file

@ -81,6 +81,7 @@ function relativeCells(
shape: FobShape,
orientation: FobRotation,
size: number,
dims?: { width: number; height: number },
): GridPoint[] | null {
if (shape === "square") {
const side = Math.round(Math.sqrt(size));
@ -91,15 +92,29 @@ function relativeCells(
}
return cells;
}
if (shape === "rect") {
const width = dims?.width ?? 0;
const height = dims?.height ?? 0;
if (width <= 0 || height <= 0 || width * height !== size) return null;
// Orientation 0 is wide (width x height), orientation 1 tall (swapped);
// the anchor stays the top-left cell of the block either way.
const [w, h] = orientation % 2 === 0 ? [width, height] : [height, width];
const cells: GridPoint[] = [];
for (let dy = 0; dy < h; dy += 1) {
for (let dx = 0; dx < w; 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),
];
// fixed on the board and the two arms swing around it. The long arm runs
// `size - 2` cells, the short arm one. Orientation 0 looks like an L with
// the elbow at its bottom-left, the long arm up and the short arm right.
const longArm = Math.max(1, size - 2);
const cells: GridPoint[] = [{ x: 0, y: 0 }];
for (let i = 1; i <= longArm; i += 1) cells.push(rotateVector({ x: 0, y: -i }, orientation));
cells.push(rotateVector({ x: 1, y: 0 }, orientation));
return cells;
}
const horizontal = orientation % 2 === 0;
const cells: GridPoint[] = [];
@ -113,7 +128,8 @@ function relativeCells(
* 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.
* square's or rect's top-left, or the L's elbow. `dims` (width x height) is
* required by the rect shape and ignored by the others.
*/
export function cellsForPlacement(
origin: GridPoint,
@ -121,8 +137,9 @@ export function cellsForPlacement(
size: number,
boardSize: number,
shape: FobShape = "line",
dims?: { width: number; height: number },
): GridPoint[] | null {
const relative = relativeCells(shape, orientation, size);
const relative = relativeCells(shape, orientation, size, dims);
if (!relative) return null;
const cells: GridPoint[] = [];
for (const cell of relative) {
@ -141,7 +158,18 @@ export function cellsForFob(
orientation: FobRotation,
boardSize: number,
): GridPoint[] | null {
return cellsForPlacement(origin, orientation, definition.size, boardSize, definition.shape);
const dims =
definition.width && definition.height
? { width: definition.width, height: definition.height }
: undefined;
return cellsForPlacement(
origin,
orientation,
definition.size,
boardSize,
definition.shape,
dims,
);
}
function cellKey(point: GridPoint): string {
@ -319,7 +347,7 @@ export function fireShot(
}
}
const shot: VersusShot = { grid: impact, outcome, assetId };
const shot: VersusShot = { grid: impact, outcome, assetId, at: now.toISOString() };
const updatedPlayer: VersusPlayerState = {
...player,
lastImpact: impact,

View file

@ -30,6 +30,8 @@ export interface VersusShot {
readonly outcome: ShotOutcome;
/** Emplacement struck, or null on a miss. */
readonly assetId: string | null;
/** ISO instant the round impacted (drives the client burn effect). */
readonly at: string;
}
export interface VersusPlayerState {
@ -79,6 +81,8 @@ export interface VersusShotView {
readonly outcome: ShotOutcome;
/** Emplacement type struck (known to the shooter), or null on a miss. */
readonly assetId: string | null;
/** ISO instant the round impacted (drives the client burn effect). */
readonly at: string;
}
export interface VersusYouView {

View file

@ -24,7 +24,12 @@ export function projectFob(fob: VersusFob): VersusFobView {
}
function projectShots(shots: readonly VersusShot[]): VersusShotView[] {
return shots.map((shot) => ({ grid: shot.grid, outcome: shot.outcome, assetId: shot.assetId }));
return shots.map((shot) => ({
grid: shot.grid,
outcome: shot.outcome,
assetId: shot.assetId,
at: shot.at,
}));
}
/** Build the safe, per-viewer view of a match. */

View file

@ -0,0 +1,37 @@
import { expect, test } from "@playwright/test";
/**
* Mobile layout smoke for Ordnance Disposal (touch-controls feature).
*
* Guards the responsive shell at phone size: login works on a coarse-pointer
* viewport, the game page renders, and nothing overflows horizontally. Real
* touch interaction (D-pad, swipes, multi-touch planting) is verified by
* manual playtest with a phone and desktop in one live match; automating the
* canvas itself would only re-test the engine, which the integration suite
* already covers deterministically.
*/
test.describe("Bomperator mobile layout", () => {
test.use({
viewport: { width: 390, height: 844 },
hasTouch: true,
isMobile: true,
});
test("game page loads at phone width without horizontal overflow", async ({ page }) => {
await page.goto("/login");
await page.getByLabel("Username").fill("dev");
await page.getByLabel("Password").fill("Test123");
await page.getByRole("button", { name: "Log in" }).click();
await page.waitForURL((url) => !url.pathname.startsWith("/login"), { timeout: 30_000 });
await page.goto("/minigames/bomperator");
await expect(
page.getByRole("heading", { name: /ordnance disposal/i }).first(),
).toBeVisible({ timeout: 60_000 });
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
);
expect(overflow).toBeLessThanOrEqual(1);
});
});

View file

@ -776,6 +776,27 @@ describe("bomperator prediction harness", () => {
expect(tel.snaps).toHaveLength(0);
});
it("backgrounded tab: a 4s freeze every 20s resumes without teleporting", () => {
// Mobile reality: app switches stop rAF for seconds while the server keeps
// running. On resume the dt cap under-advances pred by nearly the whole
// freeze, so the gap can only close through the correction path. The
// envelope policy must reel in at the capped rate - never teleport. This
// is the guarantee the touch-controls work depends on.
const cfg: ScenarioConfig = {
...BASE,
legMs: 350,
rttTrace: loadProdTrace(),
stallEveryMs: 20000,
stallMs: 4000,
};
const tel = runScenario(cfg);
report("background-resume", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.teleports).toBe(0);
expect(tel.maxJump).toBeLessThanOrEqual(1.5);
expect(tel.completedMs).toBeGreaterThan(85_000);
});
it("prod trace: measured HAR latency replay never hard-snaps", () => {
// The v0.12.4 regression shipped because every scenario here assumed a
// calm 90ms RTT. This replays the actual production input round-trips

View file

@ -13,12 +13,14 @@ import {
} from "@/lib/minigames/call-for-fire-versus/registry";
import { computeVersusStatsDelta, readVersusStats, xpForVersus } from "@/lib/minigames/call-for-fire-versus/stats";
/** Mirrors the engine spec layout: 3x2 CP, 4-cell L depot, three 2-cell lines. */
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 },
{ assetId: "ammo-depot", origin: { x, y: y + 4 }, orientation: 0 },
{ assetId: "radar-site", origin: { x, y: y + 5 }, orientation: 0 },
{ assetId: "fob", origin: { x, y: y + 6 }, orientation: 0 },
{ assetId: "fob-2", origin: { x, y: y + 7 }, orientation: 0 },
];
}
@ -73,7 +75,7 @@ describe("call for fire versus registry: battle", () => {
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));
placeFleetFor(matchId, 9501, fleetAt(6, 0));
const view = placeFleetFor(matchId, 9502, fleetAt(0, 0));
expect(view.phase).toBe("battle");
expect(view.turnUserId).toBe(9501);
@ -83,7 +85,7 @@ describe("call for fire versus registry: battle", () => {
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, 9601, fleetAt(6, 0));
placeFleetFor(matchId, 9602, fleetAt(0, 0));
const afterShot = fireShotFor(matchId, 9601, { kind: "grid", grid: { x: 0, y: 0 } });
@ -99,7 +101,7 @@ describe("call for fire versus registry: battle", () => {
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, 9701, fleetAt(6, 0));
placeFleetFor(matchId, 9702, fleetAt(0, 0));
leaveMatch(matchId, 9701);

View file

@ -16,22 +16,24 @@ import {
/**
* 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).
* a 3x2 Command Post (rows y..y+1), a 4-cell L Ammo Depot with its elbow at
* (x, y+4) (long arm up through row y+2, short arm at (x+1, y+4)), then three
* 2-cell horizontal lines: Radar Site (row y+5), FOB (row y+6), and FOB II
* (row y+7).
*/
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 },
{ assetId: "ammo-depot", origin: { x, y: y + 4 }, orientation: 0 },
{ assetId: "radar-site", origin: { x, y: y + 5 }, orientation: 0 },
{ assetId: "fob", origin: { x, y: y + 6 }, orientation: 0 },
{ assetId: "fob-2", origin: { x, y: y + 7 }, 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, 0, fleetAt(6, 0)));
state = expectState(placeFleet(state, 1, fleetAt(0, 0)));
return state;
}
@ -63,6 +65,55 @@ describe("call for fire versus: fleet placement", () => {
expect(cellsForPlacement({ x: 9, y: 0 }, 0, 4, 10, "square")).toBeNull();
});
it("lays out a 3x2 rect that flips between wide and tall", () => {
const wide = [
{ x: 0, y: 0 },
{ x: 1, y: 0 },
{ x: 2, y: 0 },
{ x: 0, y: 1 },
{ x: 1, y: 1 },
{ x: 2, y: 1 },
];
expect(cellsForPlacement({ x: 0, y: 0 }, 0, 6, 10, "rect", { width: 3, height: 2 })).toEqual(
wide,
);
const tall = [
{ x: 0, y: 0 },
{ x: 1, y: 0 },
{ x: 0, y: 1 },
{ x: 1, y: 1 },
{ x: 0, y: 2 },
{ x: 1, y: 2 },
];
expect(cellsForPlacement({ x: 0, y: 0 }, 1, 6, 10, "rect", { width: 3, height: 2 })).toEqual(
tall,
);
expect(cellsForPlacement({ x: 8, y: 0 }, 0, 6, 10, "rect", { width: 3, height: 2 })).toBeNull();
// A rect without usable dimensions is rejected.
expect(cellsForPlacement({ x: 0, y: 0 }, 0, 6, 10, "rect")).toBeNull();
});
it("grows the L with its size while keeping the elbow anchor", () => {
const anchor = { x: 2, y: 4 };
// Orientation 0: long arm (size - 2 cells) up, short arm right.
expect(cellsForPlacement(anchor, 0, 4, 10, "l")).toEqual([
{ x: 2, y: 4 },
{ x: 2, y: 3 },
{ x: 2, y: 2 },
{ x: 3, y: 4 },
]);
// Half-turn swings the long arm down and the short arm left; the elbow holds.
expect(cellsForPlacement(anchor, 2, 4, 10, "l")).toEqual([
{ x: 2, y: 4 },
{ x: 2, y: 5 },
{ x: 2, y: 6 },
{ x: 1, y: 4 },
]);
for (const turn of [0, 1, 2, 3] as const) {
expect(cellsForPlacement(anchor, turn, 4, 10, "l")).toContainEqual(anchor);
}
});
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([
@ -96,11 +147,14 @@ describe("call for fire versus: fleet placement", () => {
it("rejects missing, overlapping, and unknown emplacements", () => {
expect(buildFleet([fleetAt(0, 0)[0]], 10)).toEqual({ error: "Missing structure: Ammo Depot." });
// The L's elbow at (2,2) runs its long arm up through (2,1), inside the
// Command Post's 3x2 block.
const overlapping: FobPlacement[] = [
{ assetId: "command-post", origin: { x: 0, y: 0 }, orientation: 0 },
{ assetId: "ammo-depot", origin: { x: 1, y: 1 }, orientation: 0 },
{ assetId: "ammo-depot", origin: { x: 2, y: 2 }, orientation: 0 },
{ assetId: "radar-site", origin: { x: 0, y: 4 }, orientation: 0 },
{ assetId: "fob", origin: { x: 0, y: 5 }, orientation: 0 },
{ assetId: "fob-2", origin: { x: 0, y: 6 }, orientation: 0 },
];
expect(buildFleet(overlapping, 10)).toEqual({ error: "Structures cannot overlap." });
@ -115,7 +169,7 @@ describe("call for fire versus: fleet placement", () => {
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)));
state = expectState(placeFleet(state, 1, fleetAt(0, 1)));
expect(state.phase).toBe("battle");
expect(state.turn).toBe(0);
expect(state.startedAt).not.toBeNull();
@ -159,39 +213,65 @@ describe("call for fire versus: firing", () => {
});
it("ends the match when every emplacement is reduced", () => {
// Player 0 walks fire across player 1's whole fleet; player 1 always misses.
// Player 0 walks fire across all sixteen cells of player 1's fleetAt(0,0)
// (Command Post, Ammo Depot L, Radar Site, FOB, FOB II); player 1 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 } },
const targets = [
{ x: 0, y: 0 },
{ x: 1, y: 0 },
{ x: 2, y: 0 },
{ x: 2, y: 1 },
{ x: 1, y: 1 },
{ x: 0, y: 1 },
{ x: 0, y: 2 },
{ x: 0, y: 3 },
{ x: 0, y: 4 },
{ x: 1, y: 4 },
{ x: 1, y: 5 },
{ x: 0, y: 5 },
{ x: 0, y: 6 },
{ x: 1, y: 6 },
{ x: 1, y: 7 },
{ x: 0, y: 7 },
];
for (const move of moves) {
state = expectState(fireShot(state, move.i, move.input));
state = expectState(fireShot(state, 0, { kind: "grid", grid: targets[0] }));
for (let i = 1; i < targets.length; i += 1) {
// Player 1 keeps re-hitting the same empty corner between player 0's shots.
state = expectState(
fireShot(
state,
1,
i === 1
? { kind: "grid", grid: { x: 9, y: 9 } }
: { kind: "correction", rangeM: 0, deflectionM: 0 },
),
);
const previous = targets[i - 1];
const next = targets[i];
state = expectState(
fireShot(state, 0, {
kind: "correction",
// One cell per 50m step; range is north-positive, deflection east-positive.
rangeM: (previous.y - next.y) * 50,
deflectionM: (next.x - previous.x) * 50,
}),
);
}
expect(state.phase).toBe("complete");
expect(state.winner).toBe(0);
expect(state.reason).toBe("eliminated");
expect(state.players[0].fobsDestroyed).toBe(4);
expect(state.players[0].fobsDestroyed).toBe(5);
expect(isFleetDestroyed(state.players[1].fleet ?? [])).toBe(true);
});
it("stamps every shot with its impact instant", () => {
const state = startedState();
const at = new Date("2026-10-19T12:00:00Z");
const first = fireShot(state, 0, { kind: "grid", grid: { x: 0, y: 0 } }, at);
if (!("shot" in first)) throw new Error("expected the shot to resolve");
expect(first.shot.at).toBe(at.toISOString());
});
it("passes the turn on a timeout", () => {
const state = startedState();
const skipped = skipTurn(state);
@ -211,7 +291,7 @@ describe("call for fire versus: views", () => {
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);
expect(view.you.fleet).toHaveLength(5);
});
it("reports the outcome to the shooter only after a shot", async () => {