v0.5.0 — multiplayer Phases 2 and 3: a server that runs a game and survives being restarted

Phases 0-1 shipped in v0.4.0 (seat/identity split, per-player turn state, the Session boundary).
This lands Phase 2 (server core, one game, no lobby) and Phase 3 (persistence and resumption) per
docs/architecture/multiplayer.md §12. Phases 4-6 (lobby/reconnection, the 22 opponent-directed
cards, StartOS packaging) are still ahead.

Phase 2: src/server/session.ts hosts a game in pure logic (no sockets) on top of game.ts's existing
Game/submit/currentActor/actionMenu; it verifies seat === currentActor(game) itself before calling
submit, since submit() trusts its caller and a server can't. src/server/http.ts and index.ts add
POST /api/game, GET /api/stream (SSE, per-seat), POST /api/intent, and static serving of dist/.
src/sim/frame-delta.ts is a purpose-built per-seat board delta for one live push at a time. Found
and fixed along the way: actionMenu(game, seat) only used seat for the hand field, so a server
computing every connected seat's Menu would have handed the acting player's legal moves to a
waiting seat. Verified with a live end-to-end smoke test (2-player game, two SSE streams, a
rejected intent from the wrong seat, an idempotent resend) plus test/server/session.test.ts and
test/redaction.test.ts. Not verified: an actual browser (none available in this environment).

Phase 3: src/server/persistence.ts writes game.json and turn-timings.json, atomic-rewrite-then-
rename. game.ts gained fromMultiplayerSave, fixing a narration-attribution bug found while testing
it (fromSave's replay loop drops the actor argument, invisible in solitaire, unreadable the moment
there's more than one seat — fromSave itself still has this gap, deliberately untouched). Verified
live: server killed and restarted mid-game, both seats reconnected exactly where they left off.

Two rules bugs found while building this: the New Train phase never implemented its car-placement
round (every car of every train was placed by the Superintendent alone, in every mode, all along —
now reads the round position off tray.consist.length); and victory conditions are now one shared,
configurable GameConfig set across solitaire/competitive/coop instead of a fixed length lookup and
a dead firstToTarget condition.

Also folds in the three fixes already released on the patch line as v0.4.9b/c/d: a switching
train's crew badge failing to draw once it left the Office square, an unload that always took the
westmost car regardless of which was picked, and a legal decision that could render with zero
buttons.

docs/testing/0.5.0-test-plan.md and three reported-bug save files (docs/station-master-seed*.json)
included for reproducibility. tools/jitsi-harness/ deliberately left untracked — unrelated
side-project work, not part of this release. 635 tests, 0 failures.
This commit is contained in:
Jesse
2026-08-20 23:50:38 -04:00
parent f9c4d9fa92
commit c3c5cbfeec
52 changed files with 5282 additions and 420 deletions
+168 -20
View File
@@ -9,17 +9,20 @@ import assert from 'node:assert/strict';
import { advance, pump } from '../src/engine/advance.ts';
import { applyIntent, areaOf, check } from '../src/engine/apply.ts';
import { EXPEDITE_FAULT_PENALTY, HAND_LIMIT, STAGES_PER_DAY, lengthProfile, TOTAL_ROLLING_STOCK } from '../src/engine/content.ts';
import { EXPEDITE_FAULT_PENALTY, HAND_LIMIT, STAGES_PER_DAY, TOTAL_ROLLING_STOCK } from '../src/engine/content.ts';
import { legalActions } from '../src/engine/legal.ts';
import { createGame } from '../src/engine/setup.ts';
import { developerBot } from '../src/sim/bot.ts';
import type { CrewTray, GameConfig, GameState } from '../src/engine/state.ts';
import { railFacingOf } from '../src/engine/state.ts';
import { coordKey, railFacingOf } from '../src/engine/state.ts';
const baseConfig = (over: Partial<GameConfig> = {}): GameConfig => ({
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'short',
days: 3,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
@@ -327,6 +330,75 @@ describe('collisions are automatic (Gap 2)', () => {
assert.ok(!s.trays.has(id), 'the train is removed');
});
it('does not collide when a coach is legally parked at the Office (v0.5.0 §A.4 exception)', () => {
// A coach may now be set out at the Office (§A.4's carve-out). It must not become a hazard to
// the next train in — that would punish exactly the thing the rule was written to allow.
const s = game();
const area = s.officeAreas.get(0)!;
area.adOccupancy = []; // an A/D track is free — only the fouling check is under test
const officeCard = area.grid.get(coordKey(area.officeCoord))!;
officeCard.standing = [{ type: 'coach', loaded: false }];
const id = 'inbound';
s.trays.set(id, {
id,
trainNumber: 2,
trainIsExtra: false,
engineAt: 0,
consist: [{ type: 'coach', loaded: true }],
direction: 'east',
position: { at: 'mainline', index: 1 },
movesUsed: 0,
});
const ml = s.division.nodes[1];
if (ml?.kind === 'mainline') {
ml.card = 'plains';
ml.transits.push({ tray: id, stagesRemaining: 1, stagesTotal: 1, direction: 'east' });
}
s.clock.phase = 'mainline';
s.movedThisPhase = new Set();
advance(s);
assert.equal(s.collisionsToday, 0, 'a legally parked coach is not a hazard to the next arrival');
assert.ok(s.trays.has(id), 'the train is not written off');
});
it('still collides when a non-coach car is left fouling the Office track', () => {
// Reachable only by poking state directly — `canDropCarsAt` already refuses every non-coach
// drop at the Office, so this backstops the collision check itself, not a state a legal game
// can reach.
const s = game();
const area = s.officeAreas.get(0)!;
area.adOccupancy = [];
const officeCard = area.grid.get(coordKey(area.officeCoord))!;
officeCard.standing = [{ type: 'boxcar', loaded: false }];
const id = 'inbound';
s.trays.set(id, {
id,
trainNumber: 2,
trainIsExtra: false,
engineAt: 0,
consist: [{ type: 'coach', loaded: true }],
direction: 'east',
position: { at: 'mainline', index: 1 },
movesUsed: 0,
});
const ml = s.division.nodes[1];
if (ml?.kind === 'mainline') {
ml.card = 'plains';
ml.transits.push({ tray: id, stagesRemaining: 1, stagesTotal: 1, direction: 'east' });
}
s.clock.phase = 'mainline';
s.movedThisPhase = new Set();
advance(s);
assert.equal(s.collisionsToday, 1);
assert.ok(!s.trays.has(id), 'the train is removed');
});
it('returns cabooses to the Division Yard and other stock to Classification (Gap 2c)', () => {
const s = game();
s.officeAreas.get(0)!.adOccupancy = ['blocker'];
@@ -464,11 +536,11 @@ describe('the Superintendent clearance interrupt (§8.1)', () => {
// ---------------------------------------------------------------------------
describe('victory conditions (§3, Gap 10e)', () => {
it('loses a timed Solitaire game that misses the target', () => {
// The target doubles as a MINIMUM in Solitaire: below it you lose regardless of score.
const s = game(1);
s.clock.day = lengthProfile('short').days + 1;
describe('victory conditions (§3, Gap 10e) — unified 2026-08-20', () => {
it('loses a timed Solitaire game that misses minCombinedRevenue', () => {
// minCombinedRevenue doubles as a MINIMUM in Solitaire: below it you lose regardless of score.
const s = game(1, { minCombinedRevenue: 10 });
s.clock.day = s.config.days + 1;
s.clock.stage = STAGES_PER_DAY;
s.clock.phase = 'shiftChange';
s.players[0]!.revenue = 0;
@@ -478,25 +550,101 @@ describe('victory conditions (§3, Gap 10e)', () => {
assert.equal(s.outcome!.reason, 'revenueFloor');
});
it('wins a timed Solitaire game that clears the target', () => {
const s = game(1);
s.clock.day = lengthProfile('short').days + 1;
it('wins a timed Solitaire game that clears minCombinedRevenue', () => {
const s = game(1, { minCombinedRevenue: 10 });
s.clock.day = s.config.days + 1;
s.clock.stage = STAGES_PER_DAY;
s.clock.phase = 'shiftChange';
s.players[0]!.revenue = lengthProfile('short').target;
s.players[0]!.revenue = 10;
advance(s);
assert.equal(s.status, 'finished');
assert.equal(s.outcome!.result, 'win');
});
it('ends a first-to-target game the moment the target is reached', () => {
const s = game(1, { victory: 'firstToTarget' });
s.players[0]!.revenue = lengthProfile('short').target;
it('minCombinedRevenue = 0 disables the floor — any score wins once days run out', () => {
const s = game(1, { minCombinedRevenue: 0 });
s.clock.day = s.config.days + 1;
s.clock.stage = STAGES_PER_DAY;
s.clock.phase = 'shiftChange';
s.players[0]!.revenue = 0;
advance(s);
assert.equal(s.status, 'finished');
assert.equal(s.outcome!.result, 'win');
});
it('everyone loses in Competitive when the TABLE misses minCombinedRevenue, whoever scored best', () => {
const s = createGame({
id: 'g', seed: 2, config: baseConfig({ mode: 'competitive', minCombinedRevenue: 20 }),
playerNames: ['A', 'B'],
});
s.clock.day = s.config.days + 1;
s.clock.stage = STAGES_PER_DAY;
s.clock.phase = 'shiftChange';
s.players[0]!.revenue = 5; // best individual score...
s.players[1]!.revenue = 3; // ...but combined (8) still misses the floor (20).
advance(s);
assert.equal(s.status, 'finished');
assert.equal(s.outcome!.result, 'loss');
assert.equal(s.outcome!.reason, 'revenueFloor');
});
it('Co-op wins as one table score (summed Revenue), winner stays null', () => {
const s = createGame({
id: 'g', seed: 3, config: baseConfig({ mode: 'coop', minCombinedRevenue: 10 }),
playerNames: ['A', 'B'],
});
s.clock.day = s.config.days + 1;
s.clock.stage = STAGES_PER_DAY;
s.clock.phase = 'shiftChange';
s.players[0]!.revenue = 4;
s.players[1]!.revenue = 6; // combined 10 clears the floor, neither alone would.
advance(s);
assert.equal(s.status, 'finished');
assert.equal(s.outcome!.result, 'win');
assert.equal(s.outcome!.winner, null, 'Co-op names an individual winner instead of a shared one');
});
it('ends immediately, mid-Stage, when collisions reach maxCollisionsPerDay', () => {
// Competitive/coop only, and immediate — not gated on the day boundary the way the revenue
// floor is. Stage 1, well short of STAGES_PER_DAY, proves it fires mid-day.
const s = game(1, { mode: 'competitive', maxCollisionsPerDay: 2 });
s.collisionsToday = 2;
s.clock.stage = 1;
s.clock.phase = 'shiftChange';
advance(s);
assert.equal(s.status, 'finished');
assert.equal(s.outcome!.reason, 'targetReached');
assert.equal(s.outcome!.result, 'loss');
assert.equal(s.outcome!.reason, 'collisionFloor');
});
it('ends immediately when the running total reaches maxCollisionsTotal, even under the per-day cap', () => {
const s = game(1, { mode: 'coop', maxCollisionsPerDay: 0, maxCollisionsTotal: 3 });
s.collisionsTotal = 3;
s.clock.stage = 1;
s.clock.phase = 'shiftChange';
advance(s);
assert.equal(s.status, 'finished');
assert.equal(s.outcome!.reason, 'collisionFloor');
});
it('maxCollisionsPerDay = 0 and maxCollisionsTotal = 0 disable the collision floor entirely', () => {
const s = game(1, { mode: 'competitive', maxCollisionsPerDay: 0, maxCollisionsTotal: 0 });
s.collisionsToday = 99;
s.collisionsTotal = 99;
s.clock.stage = 1;
s.clock.phase = 'shiftChange';
advance(s);
assert.notEqual(s.status, 'finished');
});
it('solitaire never checks the collision floor, whatever the counts', () => {
const s = game(1, { mode: 'solitaire', maxCollisionsPerDay: 1, maxCollisionsTotal: 1 });
s.collisionsToday = 99;
s.collisionsTotal = 99;
s.clock.stage = 1;
s.clock.phase = 'shiftChange';
advance(s);
assert.notEqual(s.status, 'finished');
});
});
@@ -708,7 +856,7 @@ describe('the history says WHY a train moved, and says it truthfully', () => {
* which deadlocks the moment Local Operations wants an option chosen before it can be ended.
*/
const phasesWith = (trainNumber: number): { localOps: number; loadUnload: number; leftIn: string } => {
const s = game(7, { length: 'standard' });
const s = game(7, { days: 5 });
for (const n of s.division.nodes) if (n.kind === 'mainline') n.card = 'plains';
/**
* A DIVISION WITH NOTHING ELSE ON IT. §8.1 can still hold any train, Expedited or not, on a
@@ -799,7 +947,7 @@ describe('the history says WHY a train moved, and says it truthfully', () => {
// What Expedite actually restricts now: not WHEN the train leaves, but WHERE it may be left
// standing in the meantime. Parked on Secondary Track — cleared there to make way for other
// switching, say — it must not still be there when the next Mainline Phase begins.
const s = game(7, { length: 'standard' });
const s = game(7, { days: 5 });
const area = areaOf(s, 0);
const id = 'expedited';
const secondary = { row: area.officeCoord.row, col: area.officeCoord.col + 1 };
@@ -827,7 +975,7 @@ describe('the history says WHY a train moved, and says it truthfully', () => {
it('does not fault an Expedited train legitimately held at the station itself', () => {
// A train sitting on the Office square is not "left" anywhere — including one §8.1 is holding
// for a same-direction meet, which is an ordinary hold, not a Station Master failure.
const s = game(7, { length: 'standard' });
const s = game(7, { days: 5 });
const area = areaOf(s, 0);
const id = 'expedited';
s.trays.set(id, {
+5 -2
View File
@@ -17,8 +17,11 @@ import { cardDescription, snapshot } from '../src/sim/view.ts';
const config: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'standard',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
+5 -2
View File
@@ -18,8 +18,11 @@ import { carsOn, coordKey, turnOf } from '../src/engine/state.ts';
const config: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'standard',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
+5 -2
View File
@@ -18,8 +18,11 @@ import { coordKey, subdivisions, turnOf } from '../src/engine/state.ts';
const config: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'standard',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
};
const game = (seed = 5): GameState => createGame({ id: 'g', seed, config, playerNames: ['p'] });
+87
View File
@@ -0,0 +1,87 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { areaOf } from '../src/engine/apply.ts';
import { createGame } from '../src/engine/setup.ts';
import { coordKey } from '../src/engine/state.ts';
import type { GameConfig, GameState } from '../src/engine/state.ts';
import { applyDelta, deltaFrame } from '../src/sim/frame-delta.ts';
import { snapshot } from '../src/sim/view.ts';
const config: GameConfig = {
mode: 'solitaire',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
employeeRotation: false,
emergencyToolbox: false,
},
};
const game = (seed = 1): GameState => createGame({ id: 'g', seed, config, playerNames: ['a'] });
describe('deltaFrame — the live one-step-back board diff', () => {
it('nulls cells/facilities/division when the board has not changed, keeps everything else', () => {
const s = game();
const first = snapshot(s, [], null);
s.players[0]!.revenue = 42; // a non-board change
const second = snapshot(s, [], null);
const delta = deltaFrame(first, second);
assert.equal(delta.cells, null, 'unchanged cells were not nulled');
assert.equal(delta.facilities, null, 'unchanged facilities were not nulled');
assert.equal(delta.division, null, 'unchanged division was not nulled');
assert.equal(delta.revenue, 42, 'a real change was dropped along with the unchanged board');
});
it('sends the real board when it changed', () => {
const s = game();
const first = snapshot(s, [], null);
const area = areaOf(s, 0);
area.grid.set(coordKey({ row: area.runningRow - 1, col: 0 }), {
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
const second = snapshot(s, [], null);
const delta = deltaFrame(first, second);
assert.notEqual(delta.cells, null, 'a real board change was nulled');
assert.deepEqual(delta.cells, second.cells);
});
it('never nulls anything on a first connect (no previous Frame)', () => {
const s = game();
const frame = snapshot(s, [], null);
const delta = deltaFrame(null, frame);
assert.deepEqual(delta.cells, frame.cells);
assert.deepEqual(delta.facilities, frame.facilities);
assert.deepEqual(delta.division, frame.division);
});
it('applyDelta round-trips: merge(delta(A, B)) against A reconstructs B exactly', () => {
const s = game();
const a = snapshot(s, [], null);
s.players[0]!.revenue = 7;
const area = areaOf(s, 0);
area.grid.set(coordKey({ row: area.runningRow - 1, col: 1 }), {
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
const b = snapshot(s, [], null);
const merged = applyDelta(a, deltaFrame(a, b));
assert.deepEqual(merged, b);
});
it('throws rather than silently reconstructing garbage when previous is missing but the delta says "unchanged"', () => {
const s = game();
const frame = snapshot(s, [], null);
const delta = deltaFrame(frame, frame); // everything nulled, since nothing changed
assert.throws(() => applyDelta(null, delta));
});
});
+5 -2
View File
@@ -29,8 +29,11 @@ const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const config: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'standard',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
+7 -4
View File
@@ -32,8 +32,11 @@ import { snapshot } from '../src/sim/view.ts';
const config: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'standard',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
};
const game = (seed = 5): GameState => createGame({ id: 'g', seed, config, playerNames: ['p'] });
@@ -733,7 +736,7 @@ describe('regions on a Mainline card (§2.1, §8.2)', () => {
id: 'reg',
seed: 4,
config: {
mode: 'solitaire', victory: 'highestAfterDays', length: 'standard',
mode: 'solitaire', days: 5, minCombinedRevenue: 0, maxCollisionsPerDay: 0, maxCollisionsTotal: 0, pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
},
playerNames: ['Solitaire'],
@@ -796,7 +799,7 @@ describe('Q13 — a train that catches the one ahead runs into it', () => {
const s = createGame({
id: 'rear', seed: 3,
config: {
mode: 'solitaire', victory: 'highestAfterDays', length: 'standard',
mode: 'solitaire', days: 5, minCombinedRevenue: 0, maxCollisionsPerDay: 0, maxCollisionsTotal: 0, pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
},
playerNames: ['bot'],
+116 -4
View File
@@ -11,21 +11,31 @@ import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { advance, pump } from '../src/engine/advance.ts';
import { areaAtSeat, areaOf } from '../src/engine/apply.ts';
import { applyIntent, areaAtSeat, areaOf } from '../src/engine/apply.ts';
import { STAGES_PER_SHIFT, crewTrayCount } from '../src/engine/content.ts';
import { createGame } from '../src/engine/setup.ts';
import type { GameConfig, GameState, PlayerIndex } from '../src/engine/state.ts';
import { coordKey, playerAtSeat, seatOf, subdivisions } from '../src/engine/state.ts';
import { coordKey, playerAtSeat, playerLeftOf, seatOf, subdivisions } from '../src/engine/state.ts';
import { developerBot, playGame } from '../src/sim/bot.ts';
import { snapshot } from '../src/sim/view.ts';
import { impediments } from '../src/sim/narrate.ts';
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { actionMenu } from '../src/web/game.ts';
import type { Game } from '../src/web/game.ts';
/** The thin wrapper `actionMenu` expects, built directly around an already-created multi-player state
* — `newGame` (game.ts) hardcodes one player, so it cannot construct this for a multi-seat game. */
const wrap = (s: GameState): Game =>
({ state: s, seed: s.seed, history: [], log: [], mustPlayCard: false, cues: [], scheduled: null, justDrawn: null, announced: null });
const competitive: GameConfig = {
mode: 'competitive',
victory: 'highestAfterDays',
length: 'standard',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
};
@@ -474,6 +484,9 @@ describe('the view shows one seat at a time', () => {
* which is a list of squares that do not exist on the board they are looking at.
*/
const s = game(3);
// A real floor to pace against — the shared `competitive` fixture leaves it off (0) since most
// tests in this file don't care, but pacing against "off" is trivially "always on pace" (view.ts).
s.config.minCombinedRevenue = 10;
s.players[0]!.revenue = 1;
s.players[1]!.revenue = 9;
s.players[2]!.revenue = 17;
@@ -600,3 +613,102 @@ describe('scoring lands on the right seat', () => {
assert.notEqual(areaAtSeat(s, 1), areaAtSeat(s, 2), 'two seats share one Office Area object');
});
});
describe('the New Train phase car-placement round rotates (§7, Gap 9)', () => {
/**
* REGRESSION. `newTrainPhase` used to hand the whole car-filling loop to a fixed actor —
* `actorOffset` is reset to 0 entering the phase and was never incremented, so `actorAt(s, 0)`
* always resolved to the Superintendent, who placed every car of every train alone. The written
* rule (`rules-v0.2.md` §7, Gap 9) is explicit: "starting with the Superintendent and working
* left, each player may place ONE car... the round repeats... until the consist is full," with a
* worked example showing seats alternating. The fix reads the round position off
* `tray.consist.length` instead, which is already exactly that counter and resets per train.
*/
it('cycles Superintendent-then-left, one car per player, wrapping as the round repeats', () => {
// Train 1, "Crack Limited" — 3 coaches, no freight or caboose (content.ts) — small enough to
// exercise both a player count that wraps (2p: seats 0,1,0) and one that doesn't (3p: 0,1,2).
for (const players of [2, 3]) {
const s = game(players);
s.clock.phase = 'newTrain';
s.trays.set('t1', {
id: 't1',
trainNumber: 1,
trainIsExtra: false,
engineAt: 0,
consist: [],
direction: 'west',
position: { at: 'divisionPoint', side: 'east' },
movesUsed: 0,
});
s.yards.divisionYard.push(
{ type: 'coach', loaded: false },
{ type: 'coach', loaded: false },
{ type: 'coach', loaded: false },
);
const expected = [0, 1, 2].map((offset) => playerLeftOf(s, s.clock.superintendent, offset));
const seenActors: PlayerIndex[] = [];
for (let guard = 0; guard < 10; guard++) {
const r = advance(s);
if (!r.needsInput) break;
const actor = s.clock.currentActor!;
seenActors.push(actor);
const result = applyIntent(s, actor, {
type: 'newTrain.placeCar',
trayId: 't1',
carType: 'coach',
loaded: false,
});
assert.ok(result.ok, `${players}p: placeCar rejected — ${result.ok ? '' : result.code}`);
}
const wanted = [0, 1, 2].map((i) => expected[i % players]!);
assert.deepEqual(
seenActors,
wanted,
`${players}p: actor sequence was [${seenActors}], wanted [${wanted}] (Superintendent-then-left)`,
);
}
});
});
describe('actionMenu is seat-safe (Phase 2 prep)', () => {
/**
* REGRESSION. `actionMenu(game, seat)` used `seat` only for the `hand` field — `options`/`direct`/
* `placeable`/`makeUp` all came from `currentActor(game)` regardless of which seat was asked. A
* server computing every connected seat's Menu would have handed the acting player's legal moves to
* a waiting seat, paired with the WRONG seat's hand. Found tracing Phase 2's per-seat Menu step.
*/
it('gives the acting seat its real options, and every other seat none at all', () => {
const s = game(3);
const g = wrap(s);
const actorSeat = s.clock.currentActor!;
const waiting = [0, 1, 2].filter((seat) => seat !== actorSeat);
const actorMenu = actionMenu(g, actorSeat as PlayerIndex);
assert.ok(actorMenu.options.length > 0, "the acting seat's Menu had no options at all");
for (const seat of waiting) {
const menu = actionMenu(g, seat as PlayerIndex);
assert.deepEqual(menu.options, [], `seat ${seat} (not acting) was given real options`);
assert.deepEqual(menu.direct, [], `seat ${seat} (not acting) was given direct actions`);
assert.deepEqual(menu.placeable, [], `seat ${seat} (not acting) was given placeable actions`);
assert.equal(menu.makeUp, null, `seat ${seat} (not acting) was given a make-up panel`);
}
});
it('still shows a waiting seat its own hand, just nothing to do with it', () => {
const s = game(3);
const g = wrap(s);
const actorSeat = s.clock.currentActor!;
const waitingSeat = [0, 1, 2].find((seat) => seat !== actorSeat)! as PlayerIndex;
const menu = actionMenu(g, waitingSeat);
const expectedHand = s.decks.hands.get(waitingSeat) ?? [];
assert.equal(menu.hand.length, expectedHand.length, "the waiting seat's own hand did not come through");
for (const card of menu.hand) {
assert.equal(card.playNow, null, 'a waiting seat was offered a way to play a card');
assert.equal(card.spots, 0, 'a waiting seat was offered somewhere to place a card');
}
});
});
+118
View File
@@ -0,0 +1,118 @@
/**
* §7's redaction test — "the single most important test in the plan."
*
* Everything else about `Frame` degrades gracefully; a redaction bug hands one player's hand to
* another and cannot be walked back once it has been seen. `test/multiplayer.test.ts`'s "the view
* shows one seat at a time" section already proves `snapshot(s, ..., viewer)` gives each seat its
* own hand, board and Revenue — spot-checks that today's code does the right thing. This is the
* different, exhaustive check: serialize a seat's whole `Frame` and assert none of some OTHER seat's
* actual secret data appears anywhere in it, so a future careless edit is caught rather than assumed
* safe. No server needed — `snapshot()` and a multi-player `GameState` are all this exercises.
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { pump } from '../src/engine/advance.ts';
import { createGame } from '../src/engine/setup.ts';
import type { GameConfig, GameState, PlayerIndex } from '../src/engine/state.ts';
import { developerBot, playGame } from '../src/sim/bot.ts';
import { snapshot } from '../src/sim/view.ts';
const config: GameConfig = {
mode: 'competitive',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
employeeRotation: false,
emergencyToolbox: false,
},
};
/** Plays a real multi-player game partway — enough for every seat to hold a real, distinct hand. */
function midGame(players: number, seed: number): GameState {
const s = createGame({
id: `redact-${players}`,
seed,
config,
playerNames: Array.from({ length: players }, (_, i) => `p${i}`),
});
const r = playGame(s, developerBot, pump, 400);
// A partial or finished game both exercise real hands — either is fine for this check.
void r;
return s;
}
describe('redaction — a seat\'s Frame never carries another seat\'s secrets', () => {
it('never contains another seat\'s actual hand-card ids', () => {
for (const players of [3, 4]) {
const s = midGame(players, 1000 + players);
for (let viewer = 0 as PlayerIndex; viewer < players; viewer++) {
const serialized = JSON.stringify(snapshot(s, [], null, null, null, false, viewer));
for (let other = 0 as PlayerIndex; other < players; other++) {
if (other === viewer) continue;
for (const cardId of s.decks.hands.get(other) ?? []) {
assert.ok(
!serialized.includes(`"${cardId}"`),
`${players}p seed ${1000 + players}: seat ${viewer}'s Frame contains seat ${other}'s ` +
`hand card id "${cardId}"`,
);
}
}
}
}
});
it('never contains the Home Office deck\'s order or contents, only its count', () => {
for (const players of [3, 4]) {
const s = midGame(players, 2000 + players);
// The deck's own card ids are the thing that must never leak — distinct from any hand's ids,
// since a card once dealt is removed from `homeOffice` (state.ts).
const deckIds = new Set(s.decks.homeOffice);
for (let viewer = 0 as PlayerIndex; viewer < players; viewer++) {
const frame = snapshot(s, [], null, null, null, false, viewer);
assert.equal(frame.deck, s.decks.homeOffice.length, 'deck field is not a plain count');
const serialized = JSON.stringify(frame);
for (const cardId of deckIds) {
assert.ok(
!serialized.includes(`"${cardId}"`),
`${players}p seed ${2000 + players}: seat ${viewer}'s Frame contains a Home Office deck id "${cardId}"`,
);
}
}
}
});
it('never carries the seed or rngState — Frame has no field for either', () => {
// A structural guarantee, not a runtime one: confirmed here so a future field addition to Frame
// that reintroduces one of these is at least forced past a reader of this test, if not the type
// system directly (see Frame in src/sim/view.ts, which carries neither today).
const s = midGame(3, 3003);
const frame = snapshot(s, [], null, null, null, false, 0);
assert.ok(!('seed' in frame), 'Frame gained a seed field');
assert.ok(!('rngState' in frame), 'Frame gained an rngState field');
const serialized = JSON.stringify(frame);
assert.ok(!serialized.includes(String(s.seed)), 'the seed value leaked into the Frame some other way');
});
it('only the viewer\'s own hand and handCount are non-public — everything else matches across seats', () => {
// The redaction surface is four fields (§7), not sixty event types. Cross-check that seats agree
// on everything else a Frame carries about shared state.
const s = midGame(3, 4004);
const frames = [0, 1, 2].map((p) => snapshot(s, [], null, null, null, false, p as PlayerIndex));
for (const f of frames) {
assert.deepEqual(f.timetable, frames[0]!.timetable, 'the public timetable differs by seat');
assert.deepEqual(f.deck, frames[0]!.deck, 'the deck count differs by seat');
assert.deepEqual(
f.players.map((p) => ({ index: p.index, revenue: p.revenue, hand: p.hand })),
frames[0]!.players.map((p) => ({ index: p.index, revenue: p.revenue, hand: p.hand })),
'public standing (names, Revenue, hand COUNTS) differs by seat',
);
}
});
});
+8 -2
View File
@@ -9,6 +9,7 @@ import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { pump } from '../src/engine/advance.ts';
import { DEFAULT_MAX_COLLISIONS_PER_DAY, DEFAULT_MAX_COLLISIONS_TOTAL, collectiveRevenueFloor } from '../src/engine/content.ts';
import type { GameEvent } from '../src/engine/events.ts';
import { createGame } from '../src/engine/setup.ts';
import type { GameConfig } from '../src/engine/state.ts';
@@ -17,10 +18,15 @@ import { impediments, isVisible, narrate, phaseLabel } from '../src/sim/narrate.
import { compress, rehydrateCells, record, renderHtml } from '../src/sim/replay.ts';
import { summarize } from '../src/sim/stats.ts';
// Mirrors `record()`'s own default exactly (`replay.ts`) — "does not drift from the engine" below
// plays the same seed through both paths and compares outcomes, so they must share one floor.
const config: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'standard',
days: 5,
minCombinedRevenue: collectiveRevenueFloor(1, 5),
maxCollisionsPerDay: DEFAULT_MAX_COLLISIONS_PER_DAY,
maxCollisionsTotal: DEFAULT_MAX_COLLISIONS_TOTAL,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
+101
View File
@@ -0,0 +1,101 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { GameConfig } from '../../src/engine/state.ts';
import type { SavedGame } from '../../src/server/session.ts';
import { appendTiming, loadGame, writeGame } from '../../src/server/persistence.ts';
const config: GameConfig = {
mode: 'competitive',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
employeeRotation: false,
emergencyToolbox: false,
},
};
const saved: SavedGame = {
seed: 42,
config,
playerNames: ['Alice', 'Bob'],
history: [{ type: 'localOps.choose', option: 'draw' }],
status: 'active',
createdAt: 1000,
};
async function withTempDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
const dir = await mkdtemp(join(tmpdir(), 'station-master-persist-'));
try {
return await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
describe('game persistence (Phase 3)', () => {
it('writes and reads back exactly what was written', () =>
withTempDir(async (dir) => {
await writeGame(dir, saved, '1.2.3');
const result = await loadGame(dir, '1.2.3');
assert.equal(result.found, true);
if (!result.found) return;
assert.equal(result.ok, true);
if (!result.ok) return;
assert.deepEqual(result.saved, saved);
}));
it('refuses a version mismatch explicitly, naming both versions', () =>
withTempDir(async (dir) => {
await writeGame(dir, saved, '1.2.3');
const result = await loadGame(dir, '9.9.9');
assert.equal(result.found, true);
if (!result.found) return;
assert.equal(result.ok, false);
if (result.ok) return;
assert.equal(result.storedVersion, '1.2.3');
assert.equal(result.currentVersion, '9.9.9');
}));
it('reports not-found rather than throwing when nothing has been saved yet', () =>
withTempDir(async (dir) => {
const result = await loadGame(dir, '1.2.3');
assert.deepEqual(result, { found: false });
}));
it('a later writeGame fully replaces the earlier one, not merges with it', () =>
withTempDir(async (dir) => {
await writeGame(dir, saved, '1.2.3');
const grown: SavedGame = { ...saved, history: [...saved.history, { type: 'draw.end' }] };
await writeGame(dir, grown, '1.2.3');
const result = await loadGame(dir, '1.2.3');
assert.equal(result.found, true);
if (!result.found) return;
assert.equal(result.ok, true);
if (!result.ok) return;
assert.equal(result.saved.history.length, 2);
}));
it('never leaves a stray .tmp file behind after a write', () =>
withTempDir(async (dir) => {
await writeGame(dir, saved, '1.2.3');
await assert.rejects(() => readFile(join(dir, 'game.json.tmp')));
}));
it('appendTiming accumulates across calls rather than overwriting', () =>
withTempDir(async (dir) => {
await appendTiming(dir, { player: 0, phase: 'localOps', day: 1, stage: 1, startedAt: 1, endedAt: 2 });
await appendTiming(dir, { player: 1, phase: 'localOps', day: 1, stage: 1, startedAt: 2, endedAt: 3 });
const text = await readFile(join(dir, 'turn-timings.json'), 'utf8');
const timings = JSON.parse(text) as unknown[];
assert.equal(timings.length, 2);
}));
});
+200
View File
@@ -0,0 +1,200 @@
/**
* The game session host (`src/server/session.ts`) — pure logic, no sockets, exercised directly.
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import type { GameConfig, PlayerIndex } from '../../src/engine/state.ts';
import type { Push } from '../../src/server/session.ts';
import { createSession, resumeSession } from '../../src/server/session.ts';
const config: GameConfig = {
mode: 'competitive',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
employeeRotation: false,
emergencyToolbox: false,
},
};
describe('the game session host', () => {
it('gives a fresh connect a full Frame — nothing nulled', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const push = session.connect(0 as PlayerIndex);
assert.notEqual(push.frame.cells, null, 'a first connect nulled the board');
assert.notEqual(push.frame.division, null, 'a first connect nulled the division');
});
it('only the current actor gets a real Menu; every other seat gets null', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const a = session.connect(0 as PlayerIndex);
const b = session.connect(1 as PlayerIndex);
const actorPushes = [a, b].filter((p) => p.menu !== null);
assert.equal(actorPushes.length, 1, 'more than one seat (or zero) was given a real Menu');
});
it('rejects an intent from a seat that is not the current actor, with NOT_YOUR_TURN', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
// Whichever seat is NOT the current actor should be refused, regardless of the intent's content.
const bPush = session.connect(1 as PlayerIndex);
const notActor = (bPush.menu === null ? 1 : 0) as PlayerIndex;
const result = session.intent(notActor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(result.accepted, false);
if (!result.accepted) assert.equal(result.code, 'NOT_YOUR_TURN');
});
it('accepts a legal intent from the current actor and pushes every seat', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const aPush = session.connect(0 as PlayerIndex);
const actor = (aPush.menu !== null ? 0 : 1) as PlayerIndex;
const result = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(result.accepted, true);
if (result.accepted) assert.equal(result.pushes.size, 2, 'not every connected seat was pushed to');
});
it('rejects an illegal intent with its real RejectionCode, and does not remember the seq', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const aPush = session.connect(0 as PlayerIndex);
const actor = (aPush.menu !== null ? 0 : 1) as PlayerIndex;
// Discarding before ever drawing is illegal on an opening hand at the limit — a safe "this is
// definitely rejected" fixture that does not depend on exactly which cards were dealt.
const bad = session.intent(actor, 1, { type: 'card.discard', cardId: 'not-a-real-card', toSlot: 0 });
assert.equal(bad.accepted, false);
if (!bad.accepted) assert.ok(bad.code.length > 0, 'a rejection carried no code at all');
// The same seq, now with a legal intent, must still go through — a rejection is not "applied".
const retry = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(retry.accepted, true, 'a seq burned by an earlier rejection could not be reused');
});
it('treats a repeated seq as an already-applied no-op, not a second application', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const aPush = session.connect(0 as PlayerIndex);
const actor = (aPush.menu !== null ? 0 : 1) as PlayerIndex;
const first = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(first.accepted, true);
const second = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(second.accepted, true, 'a resend of an already-applied seq was rejected instead of ignored');
if (second.accepted) assert.equal(second.pushes.size, 0, 'a resend produced pushes as if newly applied');
});
it('deltas the board on a second push when it has not changed since the first', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const aPush = session.connect(0 as PlayerIndex);
session.connect(1 as PlayerIndex); // both seats need a baseline Frame before a delta means anything
const actor = (aPush.menu !== null ? 0 : 1) as PlayerIndex;
const result = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(result.accepted, true);
if (!result.accepted) return;
// Choosing "draw" doesn't move a single card on the board — the division/cells should be nulled
// on this push for a seat that already had them from `connect`.
const push = result.pushes.get(actor)!;
assert.equal(push.frame.division, null, 'the board was resent even though nothing on it changed');
});
it('only sends narration NEW since the last push to that specific seat', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const aPush = session.connect(0 as PlayerIndex);
const actor = (aPush.menu !== null ? 0 : 1) as PlayerIndex;
// A first connect is this seat's first contact, so it gets everything narrated so far (the
// "Game Begins" intro and whatever `drain()` said entering the first Stage) — not an empty log.
assert.ok(aPush.lines.length > 0, 'a first connect got no narration at all, not even the game-begins intro');
const first = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(first.accepted, true);
if (!first.accepted) return;
const firstLines = first.pushes.get(actor)!.lines;
assert.ok(firstLines.length > 0, 'the acting seat got no narration for its own action');
const second = session.intent(actor, 2, { type: 'draw.end' });
assert.equal(second.accepted, true);
if (!second.accepted) return;
const secondLines = second.pushes.get(actor)!.lines;
assert.ok(secondLines.length > 0, 'a second real action produced no narration at all');
for (const line of firstLines) {
assert.ok(!secondLines.includes(line), 'the second push repeated narration already sent in the first');
}
});
});
describe('turn timings (lobby-and-sessions.md §5)', () => {
it('records a wall-clock span once the acting player, phase, Day or Stage changes', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
let pushes = new Map<PlayerIndex, Push>([
[0 as PlayerIndex, session.connect(0 as PlayerIndex)],
[1 as PlayerIndex, session.connect(1 as PlayerIndex)],
]);
const seq = new Map<PlayerIndex, number>([[0 as PlayerIndex, 1], [1 as PlayerIndex, 1]]);
const timings = [];
for (let step = 0; step < 60 && timings.length === 0; step++) {
const acting = [0, 1].find((seat) => pushes.get(seat as PlayerIndex)!.menu !== null) as PlayerIndex | undefined;
const menu = acting === undefined ? null : pushes.get(acting)!.menu;
if (acting === undefined || !menu || menu.options.length === 0) break;
const n = seq.get(acting)!;
seq.set(acting, n + 1);
const result = session.intent(acting, n, menu.options[0]!);
assert.equal(result.accepted, true, `step ${step}: ${JSON.stringify(menu.options[0])} rejected`);
if (!result.accepted) break;
if (result.timing) timings.push(result.timing);
pushes = result.pushes;
}
assert.ok(timings.length > 0, 'no turn timing ever closed across 60 real steps of actual play');
const [timing] = timings;
assert.ok(timing!.endedAt >= timing!.startedAt, 'a span ended before it started');
assert.ok([0, 1].includes(timing!.player), 'a timing named a player outside the table');
});
});
describe('persistence hooks — exportSave / resumeSession (Phase 3)', () => {
it('exportSave carries enough to reconstruct the exact same game', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const push = session.connect(0 as PlayerIndex);
const actor = (push.menu !== null ? 0 : 1) as PlayerIndex;
const applied = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.equal(applied.accepted, true);
const saved = session.exportSave();
assert.equal(saved.seed, 42);
assert.deepEqual(saved.playerNames, ['Alice', 'Bob']);
assert.equal(saved.history.length, 1);
assert.equal(saved.status, 'active');
assert.ok(saved.createdAt > 0, 'createdAt was not set');
const resumed = resumeSession(saved);
const before = session.connect(actor);
const after = resumed.connect(actor);
assert.deepEqual(after.frame, before.frame, 'resumeSession did not reconstruct the same board/state');
});
it('a resumed session keeps enforcing whose turn it is', () => {
const session = createSession(7, config, ['Alice', 'Bob']);
const push = session.connect(0 as PlayerIndex);
const actor = (push.menu !== null ? 0 : 1) as PlayerIndex;
session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
const resumed = resumeSession(session.exportSave());
const notActor = (actor === 0 ? 1 : 0) as PlayerIndex;
const rejected = resumed.intent(notActor, 1, { type: 'draw.end' });
assert.equal(rejected.accepted, false);
if (!rejected.accepted) assert.equal(rejected.code, 'NOT_YOUR_TURN');
});
it('marks status finished only once the game actually is', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
assert.equal(session.exportSave().status, 'active');
});
});
+13 -6
View File
@@ -34,8 +34,11 @@ import { subdivisions } from '../src/engine/state.ts';
const solitaireConfig: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'standard',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
@@ -299,12 +302,16 @@ describe('card catalogue (component 1)', () => {
}
});
it('uses the Gap 10e revised victory targets', () => {
it('keeps the three day-count presets sim/CLI tooling still relies on', () => {
// Gap 10e's fixed targets retired 2026-08-20 — `minCombinedRevenue` is a free `GameConfig`
// variable now, not a `length`-keyed lookup. `LENGTH_PROFILES` survives only as a convenience
// preset for tools that still want a short/standard/campaign argument (`harness.ts`, `compare.ts`,
// `replay.ts`).
assert.deepEqual(
LENGTH_PROFILES.map((p) => [p.target, p.days]),
[[10, 3], [20, 5], [45, 10]],
LENGTH_PROFILES.map((p) => [p.length, p.days]),
[['short', 3], ['standard', 5], ['campaign', 10]],
);
assert.equal(lengthProfile('standard').target, 20);
assert.equal(lengthProfile('standard').days, 5);
});
it('scales fixed supplies with player count', () => {
+22 -19
View File
@@ -22,8 +22,11 @@ import { anomalies, strategyBuckets } from '../src/sim/stats.ts';
const config: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'short',
days: 3,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
@@ -155,7 +158,7 @@ describe('the revenue chain works end to end (regression)', () => {
// more cars in total (22 vs 19 over forty games). Widened so it fails for the reason it names.
let spotted = 0;
for (const seed of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) {
const s = createGame({ id: 'g', seed, config: { ...config, length: 'standard' }, playerNames: ['bot'] });
const s = createGame({ id: 'g', seed, config: { ...config, days: 5 }, playerNames: ['bot'] });
playGame(s, developerBot, pump);
for (const card of s.officeAreas.get(0)!.grid.values()) {
if (card.facility?.kind === 'freight') spotted += card.facility.industryTrack.cars.length;
@@ -172,7 +175,7 @@ describe('the revenue chain works end to end (regression)', () => {
// the old 52-card placeholder it was 10 in 52.
let placed = 0;
for (const seed of [11, 23, 47, 91, 137, 211]) {
const s = createGame({ id: 'g', seed, config: { ...config, length: 'campaign' }, playerNames: ['bot'] });
const s = createGame({ id: 'g', seed, config: { ...config, days: 10 }, playerNames: ['bot'] });
playGame(s, developerBot, pump);
for (const card of s.officeAreas.get(0)!.grid.values()) {
if (card.geometry.kind !== 'facility') continue;
@@ -206,7 +209,7 @@ describe('the revenue chain works end to end (regression)', () => {
// "downward only" is gone, and with it the rule that rejected every square above row 0.
const rows = new Set<number>();
for (const seed of [3, 9, 27, 81]) {
const s = createGame({ id: 'g', seed, config: { ...config, length: 'campaign' }, playerNames: ['bot'] });
const s = createGame({ id: 'g', seed, config: { ...config, days: 10 }, playerNames: ['bot'] });
playGame(s, developerBot, pump);
for (const key of s.officeAreas.get(0)!.grid.keys()) rows.add(Number(key.split(',')[0]));
}
@@ -272,7 +275,7 @@ describe('the deck is closed — no card is created or destroyed', () => {
// Every card is in exactly one place: the Home Office deck, a Department pile, the Salvage Yard,
// a hand, or on the board — grid cells, enhancements laid on them, and Mainline modifiers.
for (const seed of [3, 17, 91]) {
const s = createGame({ id: `cc-${seed}`, seed, config: { ...config, length: 'standard' }, playerNames: ['bot'] });
const s = createGame({ id: `cc-${seed}`, seed, config: { ...config, days: 5 }, playerNames: ['bot'] });
const total = s.cards.size;
playGame(s, developerBot, pump);
@@ -294,7 +297,7 @@ describe('the deck is closed — no card is created or destroyed', () => {
// The sharper form of the same guard. A discard moves a card from a hand to a Department pile
// and a draw moves one back, so the count across deck + Departments + Salvage Yard + hands can
// only fall by cards actually placed on the board — never by one being overwritten.
const s = createGame({ id: 'cc', seed: 5, config: { ...config, length: 'standard' }, playerNames: ['bot'] });
const s = createGame({ id: 'cc', seed: 5, config: { ...config, days: 5 }, playerNames: ['bot'] });
const before = s.cards.size;
playGame(s, developerBot, pump);
const loose =
@@ -541,7 +544,7 @@ describe('the bot builds sidings that are actually sidings (regression)', () =>
const s = createGame({
id: `sd-${i}`,
seed: 1000 + i * 7919,
config: { ...config, length: 'standard' },
config: { ...config, days: 5 },
playerNames: ['bot'],
});
playGame(s, developerBot, pump);
@@ -639,7 +642,7 @@ describe('the bot builds sidings that are actually sidings (regression)', () =>
const s = createGame({
id: `cs-${i}`,
seed: 1000 + i * 7919,
config: { ...config, length: 'standard' },
config: { ...config, days: 5 },
playerNames: ['bot'],
});
const r = playGame(s, developerBot, pump);
@@ -723,7 +726,7 @@ describe('the bot does not throw away its own freight (regression)', () => {
const s = createGame({
id: `uj-${i}`,
seed: 1000 + i * 7919,
config: { ...config, length: 'standard' },
config: { ...config, days: 5 },
playerNames: ['bot'],
});
const r = playGame(s, developerBot, pump);
@@ -752,7 +755,7 @@ describe('the bot does not throw away its own freight (regression)', () => {
// The other half of the regression above. Gutting the fallback entirely would satisfy "never
// unjams a green box" while leaving a real jam to block the industry forever — a load stranded
// on WORK keeps the track locked, which now stops trains passing as well as stopping (§9.3).
const s = createGame({ id: 'jam', seed: 5, config: { ...config, length: 'standard' }, playerNames: ['bot'] });
const s = createGame({ id: 'jam', seed: 5, config: { ...config, days: 5 }, playerNames: ['bot'] });
const area = s.officeAreas.get(0)!;
area.grid.set('-1,0', {
geometry: { kind: 'facility', facility: 'mineTipple' },
@@ -797,7 +800,7 @@ describe('Enhancements can reach the board at all (regression)', () => {
const s = createGame({
id: `st-${i}`,
seed: 1000 + i * 7919,
config: { ...config, length: 'standard' },
config: { ...config, days: 5 },
playerNames: ['bot'],
});
playGame(s, developerBot, pump);
@@ -834,7 +837,7 @@ describe('Enhancements can reach the board at all (regression)', () => {
const s = createGame({
id: `il-${i}`,
seed: 1000 + i * 7919,
config: { ...config, length: 'standard' },
config: { ...config, days: 5 },
playerNames: ['bot'],
});
playGame(s, developerBot, pump);
@@ -872,7 +875,7 @@ describe('rolling stock returns to service (regression)', () => {
const s = createGame({
id: 'refill',
seed: 4,
config: { ...config, length: 'standard' },
config: { ...config, days: 5 },
playerNames: ['bot'],
});
@@ -911,7 +914,7 @@ describe('measurement discipline', () => {
// the observer hook cannot drift from the log, so probes have one trustworthy way in and no
// reason to hand-roll the drive loop again.
const seen: string[] = [];
const s = createGame({ id: 'obs', seed: 4242, config: { ...config, length: 'standard' }, playerNames: ['b'] });
const s = createGame({ id: 'obs', seed: 4242, config: { ...config, days: 5 }, playerNames: ['b'] });
const out = playGame(s, developerBot, pump, 50_000, (e) => seen.push(e.type));
assert.ok(out.events.length > 0, 'a finished game must produce events');
@@ -923,7 +926,7 @@ describe('measurement discipline', () => {
// Asserted across several seeds because a single game may never draw a Depot card.
let upgrades = 0;
for (let seed = 0; seed < 25; seed++) {
const s = createGame({ id: `u${seed}`, seed, config: { ...config, length: 'standard' }, playerNames: ['b'] });
const s = createGame({ id: `u${seed}`, seed, config: { ...config, days: 5 }, playerNames: ['b'] });
const out = playGame(s, developerBot, pump);
upgrades += out.events.filter((e) => e.type === 'officeUpgraded').length;
}
@@ -943,7 +946,7 @@ describe('the bot does not lay track that cannot work (regression)', () => {
const s = createGame({
id: `lay-${seed}`,
seed,
config: { ...config, length: 'standard' },
config: { ...config, days: 5 },
playerNames: ['Solitaire'],
});
const laid: Lay[] = [];
@@ -996,7 +999,7 @@ describe('the bot does not lay track that cannot work (regression)', () => {
for (const seed of SEEDS) {
const s = createGame({
id: `dp-${seed}`, seed,
config: { ...config, length: 'standard' },
config: { ...config, days: 5 },
playerNames: ['Solitaire'],
});
const spy = {
@@ -1085,7 +1088,7 @@ describe('the freight figures count both halves (regression)', () => {
const seed = 1000 + i * 7919;
const s = createGame({
id: `fu-${seed}`, seed,
config: { ...config, length: 'standard' },
config: { ...config, days: 5 },
playerNames: ['bot'],
});
const r = playGame(s, developerBot, pump);
+11 -1
View File
@@ -128,7 +128,7 @@ function gameWith(area: OfficeArea): GameState {
const s = createGame({
id: 'g', seed: 5,
config: {
mode: 'solitaire', victory: 'highestAfterDays', length: 'standard',
mode: 'solitaire', days: 5, minCombinedRevenue: 0, maxCollisionsPerDay: 0, maxCollisionsTotal: 0, pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
},
playerNames: ['p'],
@@ -563,6 +563,16 @@ describe('placement and drop-off', () => {
assert.ok(canDropCarsAt(area, at(0, 1)), 'ordinary Operational Rail');
});
it('allows a coach, and only a coach, to be dropped at the Office (v0.5.0 §A.4 exception)', () => {
const area = areaFrom(
{ [coordKey(at(0, 0))]: officeCard(), [coordKey(at(0, 1))]: straight() },
at(0, 0),
);
assert.ok(!canDropCarsAt(area, at(0, 0), 1, false), 'not asking for the coach exception');
assert.ok(canDropCarsAt(area, at(0, 0), 1, true), 'one coach');
assert.ok(canDropCarsAt(area, at(0, 0), 2, true), 'more than one coach');
});
it('forbids dropping cars on a locked industry track', () => {
const area = areaFrom(
{
+43 -5
View File
@@ -19,8 +19,11 @@ import { trainRules } from '../src/sim/view.ts';
const config: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'standard',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
};
const game = (seed = 5): GameState => createGame({ id: 'g', seed, config, playerNames: ['p'] });
@@ -46,9 +49,9 @@ function switching(
): string {
const area = areaOf(s, 0);
const office = area.officeCoord;
// The crew stands one square west of the Office and works westward. It may NOT stand on the Office
// itself: §A.4 forbids leaving Rolling Stock on the Office track, so every drop there is refused
// whatever the train's own card says.
// The crew stands one square west of the Office and works westward, away from the Office square's
// own special-cased drop rule (§A.4 forbids everything but a coach there, v0.5.0) — tests that want
// that exception exercise it directly instead.
const here = { row: office.row, col: office.col - 1 };
area.grid.set(coordKey(here), straight());
area.grid.set(coordKey({ row: office.row, col: office.col - 2 }), straight(westCars));
@@ -202,6 +205,41 @@ describe('§7 — the Local keeps its coach (trains 7/8)', () => {
switching(s, 9, false, [boxcar(), coach()]);
assert.equal(check(s, 0, { type: 'switch.dropCars', trayId: 't', count: 1 }), null);
});
it('may set the coach out at the Office — the one place §A.4 now allows it (v0.5.0)', () => {
const s = game();
const area = areaOf(s, 0);
const office = area.officeCoord;
s.trays.set('t', {
id: 't',
trainNumber: 7,
trainIsExtra: false,
engineAt: 0,
consist: [boxcar(), coach()],
direction: 'west',
facing: 'w',
position: { at: 'grid', seat: 0, coord: office },
movesUsed: 0,
});
s.clock.phase = 'localOps';
s.clock.currentActor = 0;
turnOf(s, 0).option = 'switch';
turnOf(s, 0).movesRemaining = 6;
assert.equal(
check(s, 0, { type: 'switch.dropCars', trayId: 't', count: 1 }),
null,
'the coach may be cut loose at the Office',
);
assert.ok(applyIntent(s, 0, { type: 'switch.dropCars', trayId: 't', count: 1 }).ok);
const officeCard = area.grid.get(coordKey(office))!;
assert.deepEqual(
officeCard.standing.map((c) => c.type),
['coach'],
'the coach is parked on the Office card',
);
assert.equal(s.trays.get('t')!.consist.length, 1, 'the coach left the tray');
});
});
describe('§7 — trains Porters may not work', () => {
+333 -46
View File
@@ -42,7 +42,21 @@ import {
} from '../src/web/game.ts';
const root = join(import.meta.dirname, '..');
/**
* `dist/` is built once by the `pretest` npm script (`scripts/build-web.ts`), before `node --test`
* ever starts — every test below that reads `dist` assumes it is already complete, not that some
* other test in this file built it. `npm run test` directly (skipping `npm test`'s `pretest` hook)
* will not have run it.
*/
const dist = join(root, 'dist');
/**
* A directory the actual "run the build command" test below builds into, kept separate from the
* shared `dist/` above. Two suites racing to write and read the SAME `dist/` — the build command
* doing a full `rmSync` + rebuild while other tests in this file read it mid-run — used to fail 9
* times in one measured run and 0 the next. `dist/` is now single-writer (`pretest`, once, before
* anything reads it); this directory is the ONLY thing the build-command test itself may touch.
*/
const distTest = join(root, 'dist-test');
/** Play a whole game by always taking the first offered action. */
function playThrough(seed: number, maxTurns = 20_000) {
@@ -764,15 +778,30 @@ describe('the board draws the printed card (docs/tracks.png)', () => {
.map((m) => ({ x1: Number(m[1]), y1: Number(m[2]), x2: Number(m[3]), y2: Number(m[4]) }));
};
/** Undirected segment angles in degrees, deduplicated. 0 is horizontal. */
const angles = (links: string[]): number[] => [
...new Set(
draw(links).map((r) => {
const a = (Math.atan2(r.y2 - r.y1, r.x2 - r.x1) * 180) / Math.PI;
return Math.round((((a % 180) + 180) % 180) * 10) / 10;
/**
* A 45° leg is a curved `<path>` now (v0.5.0), not straight `<line>`s — see `curvedRail` in
* `board-svg.ts`. Each returned array is the sampled polyline for one of the leg's two rails, in
* order from the through edge to the diagonal edge.
*/
const drawCurve = (links: string[]): { x: number; y: number }[][] => {
const cell = {
row: 0, col: 0, kind: 'trk', label: 'x', running: true, enhancements: [], enhancementsWhat: [],
trains: [], adTracks: null, cars: [], standingWest: 0, facility: null, links, what: '',
};
const svg = officeSvg([cell] as never, 0);
return [...svg.matchAll(/<path class="bs-rail" fill="none" d="M([^"]+)"\/>/g)].map((m) =>
m[1]!.split(' L').map((pair) => {
const [x, y] = pair.trim().split(' ').map(Number);
return { x: x!, y: y! };
}),
),
].sort((a, b) => a - b);
);
};
/** Undirected angle in degrees between two points, 0–180. */
const angleOf = (a: { x: number; y: number }, b: { x: number; y: number }): number => {
const deg = (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
return ((deg % 180) + 180) % 180;
};
it('runs the through track dead centre, edge to edge', () => {
// The measurement from the printed sheet: on every one of its nine rows the east-west rail sits
@@ -788,36 +817,46 @@ describe('the board draws the printed card (docs/tracks.png)', () => {
}
});
it('leaves at exactly 45°, through the middle of the north or south edge', () => {
it('leaves the through edge level and the diagonal edge at 45°, curved rather than kinked', () => {
// The TRUE tangent is exactly 0° at the through edge and exactly 45°/135° at the diagonal edge —
// that is what the curve's control points are chosen to hit (see `curvedRail`'s call site). What
// is rendered is a sampled polyline, so the first and last drawn segment only APPROXIMATE that
// limit; a few degrees off at the sample count in use, well inside the tolerance below.
for (const links of [['ne'], ['nw'], ['se'], ['sw'], ['ew', 'ws'], ['ew', 'en']]) {
const found = angles(links);
assert.ok(found.includes(0), `${links} has no level run along the centre line`);
assert.ok(
found.includes(45) || found.includes(135),
`${links} draws its leg at ${found.join('/')}° — the card prints 45°`,
);
assert.equal(found.length, 2, `${links} draws ${found.join('/')}° — a leg is a run and one 45° angle`);
const [rail] = drawCurve(links);
assert.ok(rail && rail.length > 2, `${links} drew no curved leg`);
const start = angleOf(rail[0]!, rail[1]!);
const end = angleOf(rail[rail.length - 2]!, rail[rail.length - 1]!);
assert.ok(start <= 6 || start >= 174, `${links} leaves the through edge at ${start}°, not level`);
const offDiagonal = Math.min(Math.abs(end - 45), Math.abs(end - 135));
assert.ok(offDiagonal <= 6, `${links} meets the diagonal edge at ${end}°, not 45°/135°`);
}
});
it('draws the two diagonals as two different diagonals', () => {
// The matching rule made visible. `ne` and `sw` lie on one line and `nw` and `se` on the other,
// so a stacked pair on the same diagonal reads as one unbroken rail and a mismatched pair reads
// as the V it is. Drawn alike, the picture would claim a join the engine refuses.
assert.deepEqual(angles(['ne']), angles(['sw']), 'ne and sw must lie on the same diagonal');
assert.deepEqual(angles(['nw']), angles(['se']), 'nw and se must lie on the same diagonal');
assert.notDeepEqual(angles(['ne']), angles(['nw']), 'the two diagonals must be distinguishable');
// so a stacked pair on the same diagonal reads as one continuous curve and a mismatched pair
// reads as the V it is. Drawn alike, the picture would claim a join the engine refuses.
const family = (links: string[]): 'rising' | 'falling' => {
const [rail] = drawCurve(links);
const end = angleOf(rail![rail!.length - 2]!, rail![rail!.length - 1]!);
return Math.abs(end - 45) < Math.abs(end - 135) ? 'rising' : 'falling';
};
assert.equal(family(['ne']), family(['sw']), 'ne and sw must lie on the same diagonal');
assert.equal(family(['nw']), family(['se']), 'nw and se must lie on the same diagonal');
assert.notEqual(family(['ne']), family(['nw']), 'the two diagonals must be distinguishable');
});
it('meets the card edge at its midpoint, so abutting cards line up', () => {
// A leg that met the edge anywhere else would join to nothing, however right its angle.
// A leg that met the edge anywhere else would join to nothing, however right its angle. Exact,
// not approximate: the curve's LAST sampled point is always the true edge point (`edge` in
// `curvedRail`'s call site, not a discretised approximation of it), so averaging the two rails'
// endpoints cancels their perpendicular offset exactly, the same way it did when the leg was two
// straight segments.
const W = 166;
const H = 96;
// Only the sloping segments, and only the end of each that lands on the south edge.
const atEdge = draw(['sw'])
.filter((r) => r.y1 !== r.y2)
.map((r) => (Math.abs(r.y1 - H) < Math.abs(r.y2 - H) ? r.x1 : r.x2));
assert.equal(atEdge.length, 2, 'the leg is two rails');
const rails = drawCurve(['sw']);
assert.equal(rails.length, 2, 'the leg is two rails');
const atEdge = rails.map((r) => r[r.length - 1]!.x);
const mid = (atEdge[0]! + atEdge[1]!) / 2;
assert.ok(Math.abs(mid - W / 2) < 0.5, `the leg crosses the south edge at x=${mid}, not the middle (${W / 2})`);
});
@@ -1171,10 +1210,12 @@ describe('the page explains itself', () => {
});
it('states the objective and whether you are keeping up', () => {
// SOLO_CONFIG's minCombinedRevenue is collectiveRevenueFloor(1, 5) = 15 (game.ts) — the old
// fixed target of 20 retired 2026-08-20 with the victory-condition redesign.
const f = view(newGame(430));
assert.equal(f.objective.target, 20);
assert.equal(f.objective.target, 15);
assert.equal(f.objective.days, 5);
assert.match(f.objective.note, /of 20/);
assert.match(f.objective.note, /of 15/);
assert.match(f.objective.note, /Days? left/);
});
@@ -1325,11 +1366,17 @@ describe('replays are saves', () => {
describe('the static build', () => {
it('builds, and needs nothing but a static host', () => {
execFileSync('node', ['scripts/build-web.ts'], { cwd: root, stdio: 'pipe' });
// Its OWN directory (`dist-test/`), not the shared `dist/` every other test in this file reads
// — see the comment on `distTest` above.
execFileSync('node', ['scripts/build-web.ts'], {
cwd: root,
stdio: 'pipe',
env: { ...process.env, BUILD_DIST_DIR: 'dist-test' },
});
assert.ok(existsSync(join(dist, 'index.html')), 'no index.html');
assert.ok(existsSync(join(dist, 'web/main.js')), 'no entry script');
assert.ok(existsSync(join(dist, 'engine/apply.js')), 'the engine did not emit');
assert.ok(existsSync(join(distTest, 'index.html')), 'no index.html');
assert.ok(existsSync(join(distTest, 'web/main.js')), 'no entry script');
assert.ok(existsSync(join(distTest, 'engine/apply.js')), 'the engine did not emit');
});
it('emits no import that a browser cannot resolve', () => {
@@ -1579,6 +1626,173 @@ describe('the static build', () => {
);
});
it('remembers auto-focus, sound and zoom across a reload, separately from the save', async () => {
// A lighter DOM stub than the highlight test above — this never touches board highlighting or
// action buttons, only the settings-bearing elements and `localStorage` itself.
const els = new Map<string, Record<string, unknown>>();
const injected: Record<string, unknown>[] = [];
const make = (): Record<string, unknown> => {
let html = '';
const listeners = new Map<string, ((e?: unknown) => void)[]>();
const ownClasses = new Set<string>();
const node: Record<string, unknown> = {
textContent: '', style: {}, dataset: {}, onclick: null, disabled: false,
title: '', returnValue: '', open: false,
addEventListener: (type: string, fn: (e?: unknown) => void) =>
void listeners.set(type, [...(listeners.get(type) ?? []), fn]),
showModal() {
(node as { open: boolean }).open = true;
},
close(value?: string) {
(node as { open: boolean; returnValue: string }).open = false;
if (value !== undefined) (node as { returnValue: string }).returnValue = value;
for (const fn of listeners.get('close') ?? []) fn();
},
classList: {
add: (c: string) => void ownClasses.add(c),
remove: (c: string) => void ownClasses.delete(c),
contains: (c: string) => ownClasses.has(c),
toggle: (c: string) => (ownClasses.has(c) ? ownClasses.delete(c) : ownClasses.add(c)),
},
// No real `<svg>` child: `applyZoom` looks for one, finds none on this stub, and no-ops —
// the same way it does on a board card the stub never renders. Sizing the actual SVG needs a
// real DOM (jsdom or a browser), which this test suite does not carry; what IS checked here —
// the persisted setting, the button labels, the click wiring — is everything observable
// without one. `querySelectorAll` empty rather than absent: several unrelated render steps
// (crew markers, hand buttons, department piles) iterate whatever their element returns.
querySelector: () => null,
querySelectorAll: () => [],
};
Object.defineProperty(node, 'innerHTML', {
get: () => html,
set: (v: string) => void (html = v),
});
return node;
};
const served = new Set(
[...readFileSync(join(dist, 'play.html'), 'utf8').matchAll(/id="([a-zA-Z][\w-]*)"/g)].map(
(m) => m[1]!,
),
);
const g = globalThis as Record<string, unknown>;
g['document'] = {
getElementById: (id: string) => {
if (!served.has(id)) return null;
if (!els.has(id)) els.set(id, make());
return els.get(id);
},
createElement: () => make(),
addEventListener: () => {},
body: { appendChild: () => {} },
head: { appendChild: (node: Record<string, unknown>) => void injected.push(node) },
};
g['location'] = { search: '?seed=555' };
const store = new Map<string, string>();
// Seeded BEFORE import: settings load once, at module top level, from whatever is already there.
store.set(
'station-master.settings.v1',
JSON.stringify({ districtMode: 'open', soundOn: true, zoom: 1.25 }),
);
g['localStorage'] = {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, v),
removeItem: (k: string) => void store.delete(k),
};
g['URLSearchParams'] = class {
search: string;
constructor(search: string) {
this.search = search;
}
get(k: string): string | null {
return new RegExp(`${k}=([^&]*)`).exec(this.search)?.[1] ?? null;
}
};
await import(`file://${join(dist, 'web/main.js')}?t=${Date.now()}`);
// The seeded settings took effect on load, before any click.
assert.match(String(els.get('sound')!['textContent']), /sound/, 'sound started ON, as seeded');
assert.equal(els.get('zoomlabel')!['textContent'], '125%', 'zoom started at the seeded level');
// Zooming in from 125% goes to 150% and persists; the button disables at the top of the range.
(els.get('zoomin')!['onclick'] as () => void)();
assert.equal(els.get('zoomlabel')!['textContent'], '150%');
assert.equal(els.get('zoomin')!['disabled'], true, 'already at the highest preset');
assert.equal(
(JSON.parse(store.get('station-master.settings.v1')!) as { zoom: number }).zoom,
1.5,
'the new zoom level was written back to localStorage',
);
// Muting persists too, independently of zoom.
(els.get('sound')!['onclick'] as () => void)();
assert.match(String(els.get('sound')!['textContent']), /muted/);
assert.equal(
(JSON.parse(store.get('station-master.settings.v1')!) as { soundOn: boolean }).soundOn,
false,
);
});
it('falls back to the defaults when settings are missing or corrupt, rather than throwing', async () => {
const els = new Map<string, Record<string, unknown>>();
const make = (): Record<string, unknown> => {
const node: Record<string, unknown> = {
textContent: '', style: {}, dataset: {}, onclick: null, disabled: false,
title: '', returnValue: '', open: false,
addEventListener: () => {},
showModal() {},
close() {},
classList: { add: () => {}, remove: () => {}, contains: () => false, toggle: () => {} },
querySelector: () => null,
querySelectorAll: () => [],
};
let html = '';
Object.defineProperty(node, 'innerHTML', { get: () => html, set: (v: string) => void (html = v) });
return node;
};
const served = new Set(
[...readFileSync(join(dist, 'play.html'), 'utf8').matchAll(/id="([a-zA-Z][\w-]*)"/g)].map(
(m) => m[1]!,
),
);
const g = globalThis as Record<string, unknown>;
g['document'] = {
getElementById: (id: string) => {
if (!served.has(id)) return null;
if (!els.has(id)) els.set(id, make());
return els.get(id);
},
createElement: () => make(),
addEventListener: () => {},
body: { appendChild: () => {} },
head: { appendChild: () => {} },
};
g['location'] = { search: '?seed=556' };
g['localStorage'] = {
// Neither a JSON parse error nor a thrown access should reach the page — a full or disabled
// localStorage must not take the game down with it, the same guard the save already has.
getItem: () => {
throw new Error('storage disabled');
},
setItem: () => {},
removeItem: () => {},
};
g['URLSearchParams'] = class {
search: string;
constructor(search: string) {
this.search = search;
}
get(k: string): string | null {
return new RegExp(`${k}=([^&]*)`).exec(this.search)?.[1] ?? null;
}
};
await import(`file://${join(dist, 'web/main.js')}?t=${Date.now()}`);
assert.match(String(els.get('sound')!['textContent']), /muted/, 'sound defaults OFF');
assert.equal(els.get('zoomlabel')!['textContent'], '100%', 'zoom defaults to 100%');
});
it('busts the cache on every module, so a deploy cannot half-load', () => {
// The first real deploy served a fresh index.html against a CACHED main.js: the HTML had
// dropped an element the old script still asked for, so the page threw `missing element:
@@ -2318,8 +2532,11 @@ describe('the Division map shows the whole route', () => {
seed: 7,
config: {
mode: players === 1 ? 'solitaire' : 'competitive',
victory: 'highestAfterDays',
length: 'standard',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
},
playerNames: ['A', 'B', 'C', 'D'].slice(0, players),
@@ -2334,7 +2551,7 @@ describe('the Division map shows the whole route', () => {
id: 'div-run',
seed: 7,
config: {
mode: 'solitaire', victory: 'highestAfterDays', length: 'standard',
mode: 'solitaire', days: 5, minCombinedRevenue: 0, maxCollisionsPerDay: 0, maxCollisionsTotal: 0, pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
},
playerNames: ['Solitaire'],
@@ -2387,7 +2604,7 @@ describe('the Division map shows the whole route', () => {
const s = createEngineGame({
id: 'div-chips', seed: 7,
config: {
mode: 'solitaire', victory: 'highestAfterDays', length: 'standard',
mode: 'solitaire', days: 5, minCombinedRevenue: 0, maxCollisionsPerDay: 0, maxCollisionsTotal: 0, pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
},
playerNames: ['Solitaire'],
@@ -2716,7 +2933,7 @@ describe('the tray is an engine plus its Rolling Stock', () => {
const s = createEngineGame({
id: 'eng', seed: 1038389,
config: {
mode: 'solitaire', victory: 'highestAfterDays', length: 'standard',
mode: 'solitaire', days: 5, minCombinedRevenue: 0, maxCollisionsPerDay: 0, maxCollisionsTotal: 0, pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
},
playerNames: ['Solitaire'],
@@ -2766,7 +2983,7 @@ describe('the tray is an engine plus its Rolling Stock', () => {
const s = createEngineGame({
id: 'yards', seed: 1038389,
config: {
mode: 'solitaire', victory: 'highestAfterDays', length: 'standard',
mode: 'solitaire', days: 5, minCombinedRevenue: 0, maxCollisionsPerDay: 0, maxCollisionsTotal: 0, pvpCardsAllowed: false,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
},
playerNames: ['Solitaire'],
@@ -2818,12 +3035,21 @@ describe('the New Game dialog', () => {
value,
checked: false,
}));
// The mode radios are real DOM inputs, so `onchange` has to actually fire when a test flips
// `checked` — `applyModePreset` is wired to it, not polled.
const modeRadios = ['solitaire', 'competitive', 'coop'].map((value) => ({
value,
checked: value === 'solitaire',
onchange: null as (() => void) | null,
}));
let html = '';
const node: Record<string, unknown> = {
id, value: '', textContent: '', title: '', returnValue: '', open: false,
style: {}, dataset: {}, onclick: null, scrollTop: 0, scrollHeight: 0,
checked: false, disabled: false,
classList: { add: () => {}, remove: () => {}, contains: () => false, toggle: () => {} },
radios,
modeRadios,
addEventListener: (type: string, fn: () => void) =>
void listeners.set(type, [...(listeners.get(type) ?? []), fn]),
showModal: () => void ((node as { open: boolean }).open = true),
@@ -2833,9 +3059,14 @@ describe('the New Game dialog', () => {
},
// Only the radio-group selectors the dialog actually uses; anything else is not this
// element's business and answering it with a guess would hide a typo in the real selector.
querySelectorAll: (sel: string) => (sel === 'input[name="ng-hand"]' ? radios : []),
querySelectorAll: (sel: string) =>
sel === 'input[name="ng-hand"]' ? radios : sel === 'input[name="ng-mode"]' ? modeRadios : [],
querySelector: (sel: string) =>
sel === 'input[name="ng-hand"]:checked' ? (radios.find((r) => r.checked) ?? null) : null,
sel === 'input[name="ng-hand"]:checked'
? (radios.find((r) => r.checked) ?? null)
: sel === 'input[name="ng-mode"]:checked'
? (modeRadios.find((r) => r.checked) ?? null)
: null,
};
Object.defineProperty(node, 'innerHTML', { get: () => html, set: (v: string) => void (html = v) });
return node;
@@ -2888,6 +3119,53 @@ describe('the New Game dialog', () => {
assert.deepEqual(checked.map((r) => r.value), ['sixRandom'], 'the opening hand in play was not preselected');
});
it('always reopens on Solitaire, Deal enabled, PvP forced off — the only mode a prior game could be', async () => {
const { els } = await load('?seed=430');
(els.get('newgame')!['onclick'] as () => void)();
const dlg = els.get('newgamedlg')!;
const modeRadios = dlg['modeRadios'] as { value: string; checked: boolean }[];
assert.deepEqual(
modeRadios.filter((r) => r.checked).map((r) => r.value),
['solitaire'],
'the dialog did not reopen on Solitaire',
);
assert.equal(els.get('ng-deal')!['disabled'], false, 'Deal was disabled for the one dealable mode');
assert.equal(els.get('ng-pvp')!['checked'], false, 'PvP defaulted on for Solitaire');
assert.equal(els.get('ng-pvp')!['disabled'], true, "Solitaire's PvP checkbox was left editable");
});
it('picking Competitive suggests a 4-player floor, turns PvP on, and disables Deal', async () => {
const { els } = await load('?seed=430');
(els.get('newgame')!['onclick'] as () => void)();
const dlg = els.get('newgamedlg')!;
const modeRadios = dlg['modeRadios'] as { value: string; checked: boolean; onchange: (() => void) | null }[];
const competitive = modeRadios.find((r) => r.value === 'competitive')!;
for (const r of modeRadios) r.checked = r === competitive;
competitive.onchange!();
assert.equal(els.get('ng-minrev')!['value'], '60', 'the suggested floor is not 3 * 4 players * 5 days');
assert.equal(els.get('ng-pvp')!['checked'], true, 'Competitive did not default PvP on');
assert.equal(els.get('ng-pvp')!['disabled'], false, "Competitive's PvP checkbox was left disabled");
assert.equal(els.get('ng-deal')!['disabled'], true, 'Deal was enabled for a mode with nowhere to go yet');
});
it('picking Co-op forces PvP off — no valid target for those cards when everyone is on one side', async () => {
const { els } = await load('?seed=430');
(els.get('newgame')!['onclick'] as () => void)();
const dlg = els.get('newgamedlg')!;
const modeRadios = dlg['modeRadios'] as { value: string; checked: boolean; onchange: (() => void) | null }[];
const coop = modeRadios.find((r) => r.value === 'coop')!;
for (const r of modeRadios) r.checked = r === coop;
coop.onchange!();
assert.equal(els.get('ng-pvp')!['checked'], false, 'Co-op defaulted PvP on');
assert.equal(els.get('ng-pvp')!['disabled'], true, "Co-op's PvP checkbox was left editable");
assert.equal(els.get('ng-deal')!['disabled'], true, 'Deal was enabled for a mode with nowhere to go yet');
});
it('puts the seed and all three settings into the URL when it deals', async () => {
const { els, nav } = await load('?seed=430');
(els.get('newgame')!['onclick'] as () => void)();
@@ -2901,7 +3179,10 @@ describe('the New Game dialog', () => {
dlg['returnValue'] = 'deal';
(dlg['close'] as () => void)();
assert.equal(nav.search, '?seed=99&hand=threeTrackThreeOther&passenger=5&freight=0&transit=2');
assert.equal(
nav.search,
'?seed=99&hand=threeTrackThreeOther&passenger=5&freight=0&transit=2&days=5&minrev=15&colday=3&coltotal=5',
);
});
it('deals nothing on cancel, and nothing on Esc', async () => {
@@ -2920,8 +3201,10 @@ describe('the New Game dialog', () => {
it('reloads when the answers are the URL the page already has, so a re-deal is not a no-op', async () => {
// Dealing a random seed, disliking it and dealing again at the same settings produces the same
// search string — and assigning `location.search` the value it already holds does nothing.
const url = '?hand=threeRandom&passenger=1&freight=1&transit=0';
// search string — and assigning `location.search` the value it already holds does nothing. Spells
// out the victory dials explicitly (rather than leaving them to default) so the URL Deal produces
// is byte-identical to the one the page loaded with.
const url = '?hand=threeRandom&passenger=1&freight=1&transit=0&days=5&minrev=15&colday=3&coltotal=5';
const { els, nav } = await load(url);
(els.get('newgame')!['onclick'] as () => void)();
const dlg = els.get('newgamedlg')!;
@@ -2950,7 +3233,11 @@ describe('the New Game dialog', () => {
dlg['returnValue'] = 'deal';
(dlg['close'] as () => void)();
assert.equal(nav.search, '?hand=threeRandom&passenger=1&freight=1&transit=0', 'a bad seed was carried into the URL');
assert.equal(
nav.search,
'?hand=threeRandom&passenger=1&freight=1&transit=0&days=5&minrev=15&colday=3&coltotal=5',
'a bad seed was carried into the URL',
);
});
});