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
+61 -49
View File
@@ -27,9 +27,7 @@ import {
MOVES_PER_LOCAL_OPS_NIGHT,
STAGES_PER_DAY,
STAGES_PER_SHIFT,
collectiveRevenueFloor,
houseRules,
lengthProfile,
officeProfile,
REGIONS_PER_MAINLINE_CARD,
mainlineProfile,
@@ -273,10 +271,23 @@ function newTrainPhase(s: GameState, events: GameEvent[]): AdvanceResult {
return { events, needsInput: true };
}
// Gap 9 — the car-placement round REPEATS until the consist is full or no suitable car remains.
/**
* Gap 9 — the car-placement round REPEATS until the consist is full or no suitable car remains,
* cycling Superintendent-then-left one car at a time (§7).
*
* `tray.consist.length` IS the round position: a freshly made-up tray always starts with
* `consist: []`, and each `newTrain.placeCar` appends exactly one car to it (`apply.ts`'s
* `carPlacedOnTrain` reducer), so it counts placements toward THIS tray without any new state —
* and resets to 0 naturally for the next train made up, which a phase-wide `actorOffset` cannot
* do. Reproduces the rulebook's worked example exactly: 2 players, 4-coach Limited → seats
* 0, 1, 0, 1.
*/
const filling = trainNeedingCars(s);
if (filling) {
s.clock.currentActor = actorAt(s, s.clock.actorOffset % s.players.length);
const tray = s.trays.get(filling)!;
const nextActor = actorAt(s, tray.consist.length % s.players.length);
if (s.clock.currentActor !== nextActor) events.push({ type: 'actorChanged', player: nextActor });
s.clock.currentActor = nextActor;
return { events, needsInput: true };
}
@@ -893,8 +904,13 @@ function arriveAtOffice(
// §8.3 — cars standing on the Running Track between the Limits and the Office. A train at speed
// is not expecting them (§A.4), so this is a collision too, not a coupling.
//
// A coach is the one exception (v0.5.0, §A.4's Office carve-out): it may be legally, deliberately
// parked at the Office while its engine switches, so it must not become a hazard to the next
// arrival. Anything else standing there is still illegal to have dropped in the first place —
// `canDropCarsAt` already refuses it — so this filter only ever excludes a coach in practice.
const officeCard = area.grid.get(coordKey(area.officeCoord));
if (officeCard && officeCard.standing.length > 0) {
if (officeCard && officeCard.standing.some((c) => c.type !== 'coach')) {
collide(s, playerAtSeat(s, seat), [id], events, 'cars fouling the Running Track', 'the Running Track');
return 'moved';
}
@@ -956,6 +972,7 @@ function collide(
}
s.collisionsToday += 1;
s.collisionsTotal += 1;
const player = s.players[faultPlayer];
if (player) {
player.revenue -= COLLISION_PENALTY;
@@ -1067,63 +1084,58 @@ function shiftChange(s: GameState, events: GameEvent[]): AdvanceResult {
events.push({ type: 'stageBegan', day: s.clock.day, stage: s.clock.stage });
}
// §3.4 — Competitive only: three collisions in one Day and everyone loses.
if (s.config.mode === 'competitive' && s.collisionsToday >= 3) {
s.status = 'finished';
s.outcome = { result: 'loss', winner: null, reason: 'collisionFloor' };
return { events, needsInput: false };
// §3.4 — every mode but competitive-and-coop-only: a Day's collisions against `maxCollisionsPerDay`
// and the game's running total against `maxCollisionsTotal`. `0` disables either check. Flat, not
// scaled by player count — Jesse's call, 2026-08-20: more players is more independent chances to
// collide, not a bigger shared budget.
if (s.config.mode === 'competitive' || s.config.mode === 'coop') {
const perDayBreach =
s.config.maxCollisionsPerDay > 0 && s.collisionsToday >= s.config.maxCollisionsPerDay;
const totalBreach =
s.config.maxCollisionsTotal > 0 && s.collisionsTotal >= s.config.maxCollisionsTotal;
if (perDayBreach || totalBreach) {
s.status = 'finished';
s.outcome = { result: 'loss', winner: null, reason: 'collisionFloor' };
return { events, needsInput: false };
}
}
return { events: [...events, ...enterPhase(s, 'localOps')], needsInput: false };
}
/** §3.3 — evaluated at the end of a Day. */
/**
* §3.3 — evaluated at the end of a Day.
*
* Unified 2026-08-20 across all three modes: play `config.days`, then whoever has the most Revenue
* wins — unless the table's combined Revenue missed `config.minCombinedRevenue`, in which case
* everyone loses. Solitaire is "everyone" with one player, so this is the same win/lose shape it
* always had, just against a configured floor instead of a `length`-preset `target`. Coop keeps its
* "the table's score is everyone's Revenue summed" model — winner stays null, the achievement is
* shared — now against the same configurable floor.
*/
function checkVictory(s: GameState, _events: GameEvent[]): boolean {
const profile = lengthProfile(s.config.length);
const daysElapsed = s.clock.day - 1;
if (s.config.victory === 'firstToTarget') {
const target =
s.config.mode === 'coop' ? profile.target * s.players.length : profile.target;
const score = s.config.mode === 'coop' ? totalRevenue(s) : Math.max(...s.players.map((p) => p.revenue));
if (score >= target) {
const winner =
s.config.mode === 'coop'
? null
: s.players.findIndex((p) => p.revenue === score);
s.status = 'finished';
s.outcome = { result: 'win', winner: winner === -1 ? null : winner, reason: 'targetReached' };
return true;
}
return false;
}
if (daysElapsed < profile.days) return false;
if (daysElapsed < s.config.days) return false;
s.status = 'finished';
if (s.config.mode === 'competitive') {
// §3.5 — all players' Revenue combined must clear the floor, or everyone loses.
if (totalRevenue(s) < collectiveRevenueFloor(s.players.length, profile.days)) {
s.outcome = { result: 'loss', winner: null, reason: 'revenueFloor' };
return true;
}
const best = Math.max(...s.players.map((p) => p.revenue));
s.outcome = {
result: 'win',
winner: s.players.findIndex((p) => p.revenue === best),
reason: 'daysElapsed',
};
const combined = totalRevenue(s);
if (s.config.minCombinedRevenue > 0 && combined < s.config.minCombinedRevenue) {
s.outcome = { result: 'loss', winner: null, reason: 'revenueFloor' };
return true;
}
// Solitaire and Co-op: the target doubles as a MINIMUM. Below it you lose regardless of score.
const target = s.config.mode === 'coop' ? profile.target * s.players.length : profile.target;
const score = s.config.mode === 'coop' ? totalRevenue(s) : (s.players[0]?.revenue ?? 0);
s.outcome =
score >= target
? { result: 'win', winner: null, reason: 'daysElapsed' }
: { result: 'loss', winner: null, reason: 'revenueFloor' };
if (s.config.mode === 'coop') {
s.outcome = { result: 'win', winner: null, reason: 'daysElapsed' };
return true;
}
const best = Math.max(...s.players.map((p) => p.revenue));
s.outcome = {
result: 'win',
winner: s.players.findIndex((p) => p.revenue === best),
reason: 'daysElapsed',
};
return true;
}
+10 -11
View File
@@ -697,25 +697,24 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
? tray.consist.slice(0, i.count)
: tray.consist.slice(tray.consist.length - i.count);
const dropRules = rulesOf(tray);
const dropArea = areaOf(s, player);
const atOffice = here.row === dropArea.officeCoord.row && here.col === dropArea.officeCoord.col;
/**
* Trains 7/8 Local — "coach must remain on station track if switching", i.e. the coach is
* never set out during switching at all.
*
* The intended reading was "set out only at the Office", but §A.4 makes that unimplementable:
* `canDropCarsAt` refuses the Office square outright — "the Office track is Operational Rail,
* but Rolling Stock may not be left there" — so "only at the Office" and "nowhere" are the same
* rule. What is left is the effect that matters: the Local may shunt its freight car around the
* district, and may not abandon its coach at an industry or on a siding while it does.
* Flagged in `TODO.md` in case the station track is meant to become a real place to leave one.
* Trains 7/8 Local — "coach must remain on station track if switching" — the coach may never
* be set out anywhere ELSE while switching. §A.4 now carries an exception for the Office
* square (v0.5.0, Jesse's call): any train may cut a coach loose there, which is exactly what
* "station track" meant on the card all along. So the coach is refused everywhere except the
* Office, rather than everywhere.
*/
if (dropRules.coachStaysOnStationTrack && cut.some((c) => c.type === 'coach')) {
if (dropRules.coachStaysOnStationTrack && cut.some((c) => c.type === 'coach') && !atOffice) {
return 'COACH_MUST_STAY';
}
const droppedFreight = cut.filter(isFreight).length;
if (droppedFreight > 0 && !freightBudgetLeft(s, player, tray, here, droppedFreight)) {
return 'FREIGHT_WORKED_HERE';
}
return canDropCarsAt(areaOf(s, player), here, i.count) ? null : 'CANNOT_DROP_HERE';
const coachesOnly = cut.every((c) => c.type === 'coach');
return canDropCarsAt(dropArea, here, i.count, coachesOnly) ? null : 'CANNOT_DROP_HERE';
}
case 'switch.sortConsist': {
+26 -7
View File
@@ -876,7 +876,13 @@ export function mainlineCardCount(players: number): number {
return players + 1;
}
/** Provisional; not in the recovered files. */
/**
* Sourced, not provisional: `rules-v0.2.md`:339, "There are only a limited number of Crew Trays
* and engine pieces [Gap 4b: player count + 3]." The rules tie Crew Trays and engine pieces
* together as ONE combined resource, not two independently-tracked supplies — an engine is never
* conjured separately from the tray it rides in, and the game has no state for "an engine with no
* tray" or "a tray with no engine". `state.ts`'s `freeTrays` pool already IS the engine supply.
*/
export function crewTrayCount(players: number): number {
return players + 3;
}
@@ -1003,7 +1009,11 @@ export const MOVES_PER_LOCAL_OPS = 6;
export const MOVES_PER_LOCAL_OPS_NIGHT = 5;
export const LABORER_ACTIONS_PER_LOAD = 4;
export const COLLISION_PENALTY = 5;
export const COLLISION_FLOOR_PER_DAY = 3;
/** Suggested defaults for `GameConfig`'s collision floors — see `state.ts`'s `GameConfig` doc. */
export const DEFAULT_MAX_COLLISIONS_PER_DAY = 3;
export const DEFAULT_MAX_COLLISIONS_TOTAL = 5;
/** Suggested default for `GameConfig.days`, all modes. */
export const DEFAULT_DAYS = 5;
/**
* Q3 — an expedited train left parked off the Office when a Mainline Phase begins is a Station
* Master fault: the train was not kept ready to highball the moment the Subdivision allowed it.
@@ -1011,18 +1021,27 @@ export const COLLISION_FLOOR_PER_DAY = 3;
*/
export const EXPEDITE_FAULT_PENALTY = 1;
/**
* The suggested default for `GameConfig.minCombinedRevenue` — a caller computes this before
* submitting a config; the engine itself never calls it (`state.ts`'s `GameConfig` doc explains why).
*/
export function collectiveRevenueFloor(players: number, days: number): number {
return 3 * players * days;
}
/**
* `GameLength` IS NOT PART OF `GameConfig` ANY MORE (2026-08-20) — `days` is a free variable there
* now, replacing the old `target`-bearing preset. This survives only as a convenience for sim/CLI
* tooling (`harness.ts`, `compare.ts`, `replay.ts`) that still wants a `short`/`standard`/`campaign`
* argument instead of a raw day count; `lengthProfile()` just resolves that argument to `days`.
*/
export type GameLength = 'short' | 'standard' | 'campaign';
export type LengthProfile = { length: GameLength; target: number; days: number };
export type LengthProfile = { length: GameLength; days: number };
/** Provisional and now unvalidated — the balance run they came from used a placeholder ruleset. */
export const LENGTH_PROFILES: readonly LengthProfile[] = [
{ length: 'short', target: 10, days: 3 },
{ length: 'standard', target: 20, days: 5 },
{ length: 'campaign', target: 45, days: 10 },
{ length: 'short', days: 3 },
{ length: 'standard', days: 5 },
{ length: 'campaign', days: 10 },
];
export function lengthProfile(length: GameLength): LengthProfile {
+16 -13
View File
@@ -53,13 +53,16 @@ export type SetupOptions = {
};
/** Builds the 52-card Home Office deck (§12.1). Unshuffled; caller shuffles with the seeded RNG. */
export function buildDeck(mode: GameConfig['mode'] = 'competitive'): Card[] {
export function buildDeck(mode: GameConfig['mode'] = 'competitive', pvpCardsAllowed = false): Card[] {
/**
* THE 22 OPPONENT-DIRECTED CARDS ARE OUT OF EVERY DECK FOR NOW, not just the solitaire one.
* THE 22 OPPONENT-DIRECTED CARDS ARE OUT OF EVERY DECK REGARDLESS OF `pvpCardsAllowed`, for now.
*
* Q6 took them out of solitaire because they have no legal target in a one-player game. They are
* out of the competitive deck too because `checkPlay` answers both categories `NOT_IMPLEMENTED`:
* leaving them in would make ~9% of draws reject outright, which is worse than not dealing them.
* `pvpCardsAllowed` (`GameConfig`, wired 2026-08-20) is the player-facing toggle, but ANDing it
* with `cardsImplemented` keeps it inert until Phase 5 actually builds the cards — flipping
* `pvpCardsAllowed` on today must not turn a working game into one where ~9% of draws reject.
*
* AND SO ARE THE SEVEN CARDS THAT ANSWER THEM — see below. They used to be dealt and sit dormant,
* which is the same dead draw by another name. Recorded in TODO.md as multiplayer work.
@@ -68,7 +71,8 @@ export function buildDeck(mode: GameConfig['mode'] = 'competitive'): Card[] {
* for these two categories today.
*/
void mode;
const opponentCardsInDeck = false;
const cardsImplemented = false;
const opponentCardsInDeck = pvpCardsAllowed && cardsImplemented;
const cards: Card[] = [];
let n = 0;
const push = (kind: Card['kind']): void => {
@@ -226,17 +230,15 @@ function buildDivision(players: number, rng: Rng): DivisionNode[] {
const mainline = (): DivisionNode => {
const card = kinds[rng.nextInt(kinds.length)]!;
const node: DivisionNode = { kind: 'mainline', card, transits: [] };
// The Heavy Grade card says "Player sets orientation", but setup has no decision point yet —
// createGame is synchronous and returns a ready state. Rolled for now so the orientation is at
// least deterministic and varies between games; it should become a real player choice when
// setup gains an interactive phase. See implications.md §10 Q11.
if (mainlineProfile(card).speed.kind === 'grade') {
/**
* TEMPORARY, and flagged in TODO. The card prints "(Up)" and "Player sets orientation", so
* which way a Heavy Grade climbs is the player's decision — but it is dealt during setup, and
* setup has no decision point at all. Rolled from the seed until it gains one, because the
* orientation MATTERS: it decides which direction climbs, and therefore what a Brakeman or
* Helpers card is worth.
* SETTLED, not provisional (v0.5.0, Jesse's call) — this overrides the card's own printed
* "Player sets orientation". A Heavy Grade sits on the shared west-to-east chain BETWEEN two
* players (§4.2), or beyond an end Division Point next to one — never inside one player's own
* district — so whichever direction climbs advantages one neighbour over the other, and there
* is no single player who owns that call fairly. Orientation is rolled from the seed instead,
* identically for solitaire and multiplayer, and this is not expected to change when setup
* eventually gains an interactive phase for other decisions. See implications.md §10 Q11.
*/
node.gradeUp = rng.nextInt(2) === 0 ? 'east' : 'west';
}
@@ -317,7 +319,7 @@ export function createGame(opts: SetupOptions): GameState {
*/
const rules = houseRules(config);
const deal = OPENING_DEALS[rules.startingHand];
const deck = buildDeck(config.mode);
const deck = buildDeck(config.mode, config.pvpCardsAllowed);
const cards = new Map<CardId, Card>();
for (const c of deck) cards.set(c.id, c);
@@ -409,6 +411,7 @@ export function createGame(opts: SetupOptions): GameState {
turns: freshTurns(playerCount, MOVES_PER_LOCAL_OPS),
movedThisPhase: new Set(),
collisionsToday: 0,
collisionsTotal: 0,
status: 'active',
outcome: null,
};
+43 -10
View File
@@ -12,7 +12,6 @@ import type {
Hand,
MainlineKind,
FreightKind,
GameLength,
HouseRuleOverrides,
ModifierKind,
OfficeTier,
@@ -326,6 +325,12 @@ export type CrewTray = {
*
* The engine is NOT one of the `consist` entries: §8.2 counts the consist as Rolling Stock, and
* the four-car limit (§A.4) is a limit on cars, not on the locomotive hauling them.
*
* This only records POSITION, not a supply — and that is not a gap. `rules-v0.2.md`:339 (Gap 4b)
* ties Crew Trays and engine pieces together as one combined resource, `player count + 3`
* (`crewTrayCount` in `content.ts`), so engine scarcity IS tray scarcity: `freeTrays` running out
* already blocks a new train exactly when the engine supply would. There is no state for "a tray
* with no engine" because the rules never separate the two.
*/
engineAt: number;
/**
@@ -540,12 +545,42 @@ export type Player = {
};
export type GameMode = 'solitaire' | 'competitive' | 'coop';
export type VictoryCondition = 'firstToTarget' | 'highestAfterDays';
/**
* VICTORY CONDITIONS — designed 2026-08-20, unified across all three modes.
*
* Replaces the old `length`-preset lookup (`LENGTH_PROFILES.target`) and the dead
* `VictoryCondition: 'firstToTarget'` (grepped: never selected anywhere in the codebase). Winner is
* whoever has the most Revenue when `days` run out — solitaire's own player counts as "everyone" —
* unless `minCombinedRevenue` was missed, in which case everyone loses. Coop keeps summing every
* player's Revenue into one table score, now against a configurable floor instead of
* `profile.target * players.length`.
*
* `0` means "off" for every numeric field below. `minCombinedRevenue`'s natural default is
* `collectiveRevenueFloor(players, days)` (`content.ts`), computed by whoever authors the config —
* the engine only ever reads a concrete number here, never resolves one lazily, because player count
* is not always known at config-authoring time (a lobby, a CLI flag, a dialog).
*
* `maxCollisionsPerDay`/`maxCollisionsTotal` are deliberately FLAT, not scaled by player count: more
* players means more independent chances to collide, not a bigger shared budget, so a multiplayer
* table is genuinely riskier than solitaire at the same default (Jesse's call).
*/
export type GameConfig = {
mode: GameMode;
victory: VictoryCondition;
length: GameLength;
/** How many Days the game runs. */
days: number;
/** Everyone loses if the table's total Revenue is below this when `days` run out. 0 = off. */
minCombinedRevenue: number;
/** Everyone loses immediately, mid-game, once collisions in one Day reach this. 0 = off. */
maxCollisionsPerDay: number;
/** Same, summed across the whole game, never reset. 0 = off. */
maxCollisionsTotal: number;
/**
* Whether the 22 opponent-directed cards are in the deck (`setup.ts`'s `buildDeck`). Forced off in
* `solitaire` and `coop` — neither has a valid target for them — on by default in `competitive`.
* Has no effect until those cards are built (Phase 5); see `TODO.md`.
*/
pvpCardsAllowed: boolean;
optionalRules: {
reducedVisibility: boolean;
sisterTrains: boolean;
@@ -562,11 +597,7 @@ export type GameConfig = {
houseRules?: HouseRuleOverrides;
};
export type OutcomeReason =
| 'targetReached'
| 'daysElapsed'
| 'collisionFloor'
| 'revenueFloor';
export type OutcomeReason = 'daysElapsed' | 'collisionFloor' | 'revenueFloor';
export type Outcome = {
result: 'win' | 'loss';
@@ -742,8 +773,10 @@ export type GameState = {
turns: Map<PlayerIndex, TurnState>;
/** Transient: trains already moved in the current Mainline Phase. Cleared when it ends. */
movedThisPhase: Set<TrayId>;
/** §3.4 — resets at the start of each Day. */
/** §3.4 — resets at the start of each Day; checked against `config.maxCollisionsPerDay`. */
collisionsToday: number;
/** §3.4 — never reset; checked against `config.maxCollisionsTotal`. */
collisionsTotal: number;
status: 'setup' | 'active' | 'finished';
outcome: Outcome | null;
};
+10 -3
View File
@@ -667,12 +667,19 @@ export function canPlaceAt(area: OfficeArea, coord: GridCoord, card: TrackCard):
}
/**
* §A.4 — the Office track is Operational Rail, but Rolling Stock may not be left there.
* §A.4 — the Office track is Operational Rail, but Rolling Stock may not be left there — WITH ONE
* EXCEPTION (Jesse's call, v0.5.0): any train may set out one or more coaches at the Office. It is
* the one car type a passenger platform is meant to hold, and it is what makes the ENGINE-boxcar-
* coach Local arrangement workable — the coach drops here while the engine and freight car switch
* freely. Freight and cabooses stay banned at the Office for every train, no exception.
*
* An industry track also has a finite length (§9.3), so it can be full.
*/
export function canDropCarsAt(area: OfficeArea, coord: GridCoord, count = 1): boolean {
if (sameCoord(coord, area.officeCoord)) return false;
export function canDropCarsAt(area: OfficeArea, coord: GridCoord, count = 1, coachesOnly = false): boolean {
const card = cardAt(area, coord);
if (sameCoord(coord, area.officeCoord)) {
return coachesOnly && !!card && isOperationalRail(card) && spaceOn(card) >= count;
}
if (!card || !isOperationalRail(card)) return false;
return spaceOn(card) >= count;
}
+197
View File
@@ -0,0 +1,197 @@
/**
* The HTTP/SSE wiring — Phase 2 of `docs/architecture/multiplayer.md` (§8-9, §12 steps 8 and 12).
*
* Plain `node:http`, no framework: the project has zero runtime dependencies
* (`package.json`), and `scripts/build-web.ts` already shells out to `tsc` directly rather than
* reaching for a bundler — this matches that everywhere-else choice rather than introducing the
* first framework dependency for one route table.
*
* All the game logic lives in `session.ts`; this file is deliberately thin — routing, the join-secret
* gate, SSE mechanics, and static file serving for the built client (`dist/`, D16: the server serves
* the client, which is what makes same-origin work with no CORS).
*/
import { createServer } from 'node:http';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { createReadStream } from 'node:fs';
import { stat } from 'node:fs/promises';
import { extname, join, normalize } from 'node:path';
import type { Intent } from '../engine/intents.ts';
import type { GameConfig, PlayerIndex } from '../engine/state.ts';
import { appendTiming, writeGame } from './persistence.ts';
import { createSession } from './session.ts';
import type { GameSession, Push } from './session.ts';
export type ServerOptions = {
port: number;
bindAddress: string;
/** D14 — a server-wide secret, passed out of band. Gates every `/api/*` route. */
joinSecret: string;
/** The built client (`npm run build:web`'s `dist/`), served at `/` (D16). */
distDir: string;
/** Where `game.json`/`turn-timings.json` live (Phase 3). */
dataDir: string;
/** `package.json`'s version — stamped onto every write, checked on every load (§12 step 15). */
engineVersion: string;
/** Already reconstructed by `index.ts`'s load-on-start, or `null` for a fresh server. */
initialSession: GameSession | null;
};
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml',
};
const HEARTBEAT_MS = 20_000;
async function readJson(req: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const text = Buffer.concat(chunks).toString('utf8');
return text.trim() === '' ? {} : JSON.parse(text);
}
function sendJson(res: ServerResponse, status: number, body: unknown): void {
const text = JSON.stringify(body);
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(text) });
res.end(text);
}
async function serveStatic(distDir: string, urlPath: string, res: ServerResponse): Promise<void> {
const rel = urlPath === '/' ? '/index.html' : urlPath;
// `normalize` collapses `..`, and the join is then checked to still be inside `distDir` — a request
// for `/../../etc/passwd` must not escape the one directory this is allowed to read from.
const full = join(distDir, normalize(rel));
if (!full.startsWith(distDir)) {
sendJson(res, 400, { error: 'bad path' });
return;
}
try {
const info = await stat(full);
if (!info.isFile()) throw new Error('not a file');
res.writeHead(200, { 'Content-Type': MIME[extname(full)] ?? 'application/octet-stream', 'Content-Length': info.size });
createReadStream(full).pipe(res);
} catch {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('not found');
}
}
export function startServer(opts: ServerOptions): void {
let session: GameSession | null = opts.initialSession;
// One open SSE response per seat — a second connection from the same seat replaces the first
// rather than fanning out to both (Phase 2 has no concept of "the same seat from two tabs").
const connections = new Map<PlayerIndex, ServerResponse>();
const eventIds = new Map<PlayerIndex, number>();
function checkSecret(url: URL, res: ServerResponse): boolean {
if (url.searchParams.get('secret') === opts.joinSecret) return true;
sendJson(res, 403, { error: 'bad or missing secret' });
return false;
}
function writeSse(seat: PlayerIndex, push: Push): void {
const res = connections.get(seat);
if (!res) return; // that seat is not currently connected — Phase 4's reconnect story, not this one
const id = (eventIds.get(seat) ?? 0) + 1;
eventIds.set(seat, id);
res.write(`id: ${id}\ndata: ${JSON.stringify(push)}\n\n`);
}
function broadcast(pushes: Map<PlayerIndex, Push>): void {
for (const [seat, push] of pushes) writeSse(seat, push);
}
const server = createServer((req, res) => {
void (async () => {
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
if (url.pathname === '/api/game' && req.method === 'POST') {
if (!checkSecret(url, res)) return;
if (session) {
sendJson(res, 409, { error: 'a game already exists on this server' });
return;
}
const body = (await readJson(req)) as { config?: GameConfig; playerNames?: string[]; seed?: number };
if (!body.config || !Array.isArray(body.playerNames) || body.playerNames.length < 1) {
sendJson(res, 400, { error: 'expected { config, playerNames }' });
return;
}
session = createSession(body.seed ?? Math.floor(Math.random() * 1e9), body.config, body.playerNames);
// Persisted immediately, empty history and all — a crash one second after creation should
// still resume as "the game exists, day 1, nobody has moved" rather than vanish entirely.
await writeGame(opts.dataDir, session.exportSave(), opts.engineVersion);
sendJson(res, 200, { ok: true, playerCount: session.playerCount });
return;
}
if (url.pathname === '/api/stream' && req.method === 'GET') {
if (!checkSecret(url, res)) return;
if (!session) {
sendJson(res, 404, { error: 'no game yet' });
return;
}
const seat = Number(url.searchParams.get('seat')) as PlayerIndex;
if (!Number.isInteger(seat) || seat < 0 || seat >= session.playerCount) {
sendJson(res, 400, { error: 'bad or missing ?seat=' });
return;
}
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
connections.set(seat, res);
writeSse(seat, session.connect(seat));
// Idle for minutes at a time is the expected shape of this game (multiplayer.md §9) — a
// silent SSE connection is exactly what a proxy in the path may reap. A comment line is not a
// real event (EventSource ignores lines starting with `:`), so it costs the client nothing.
const heartbeat = setInterval(() => res.write(': ping\n\n'), HEARTBEAT_MS);
req.on('close', () => {
clearInterval(heartbeat);
if (connections.get(seat) === res) connections.delete(seat);
});
return;
}
if (url.pathname === '/api/intent' && req.method === 'POST') {
if (!checkSecret(url, res)) return;
if (!session) {
sendJson(res, 404, { error: 'no game yet' });
return;
}
const seat = Number(url.searchParams.get('seat')) as PlayerIndex;
if (!Number.isInteger(seat) || seat < 0 || seat >= session.playerCount) {
sendJson(res, 400, { error: 'bad or missing ?seat=' });
return;
}
const body = (await readJson(req)) as { seq?: number; intent?: Intent };
if (typeof body.seq !== 'number' || !body.intent) {
sendJson(res, 400, { error: 'expected { seq, intent }' });
return;
}
const result = session.intent(seat, body.seq, body.intent);
if (result.accepted) {
// Persisted BEFORE the response goes out — "accepted" should mean "durably on disk" at
// this scale, not just "applied in memory" (§12 step 14).
await writeGame(opts.dataDir, session.exportSave(), opts.engineVersion);
if (result.timing) await appendTiming(opts.dataDir, result.timing);
}
sendJson(res, 200, result.accepted ? { ok: true } : { ok: false, code: result.code });
if (result.accepted) broadcast(result.pushes);
return;
}
await serveStatic(opts.distDir, url.pathname, res);
})().catch((err: unknown) => {
sendJson(res, 500, { error: err instanceof Error ? err.message : 'internal error' });
});
});
server.listen(opts.port, opts.bindAddress);
}
+51
View File
@@ -0,0 +1,51 @@
/**
* Process bootstrap — Phase 2 §12 step 8, extended for Phase 3 (§12 steps 14-15) load-on-start.
*
* Run with: node src/server/index.ts
*
* Env-configured, no config file — matches how the rest of this project's dev-side tooling reads
* `process.env` directly (`scripts/build-web.ts`'s `BUILD_DIST_DIR`).
*/
import { readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { startServer } from './http.ts';
import { loadGame } from './persistence.ts';
import { resumeSession } from './session.ts';
import type { GameSession } from './session.ts';
const port = Number(process.env['PORT'] ?? 8081);
const bindAddress = process.env['BIND_ADDRESS'] ?? '0.0.0.0';
const joinSecret = process.env['JOIN_SECRET'];
const distDir = resolve(process.env['DIST_DIR'] ?? 'dist');
const dataDir = resolve(process.env['DATA_DIR'] ?? 'data');
if (!joinSecret) {
console.error('JOIN_SECRET must be set — a server-wide secret, passed out of band (D14).');
process.exit(1);
}
// `package.json`'s version IS `engineVersion` (§12 step 15) — the same reading `scripts/build-web.ts`'s
// `buildStamp()` already does, just from `src/server/` rather than the repo root script directory.
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
const engineVersion = (JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version: string }).version;
let initialSession: GameSession | null = null;
const loaded = await loadGame(dataDir, engineVersion);
if (loaded.found && loaded.ok) {
initialSession = resumeSession(loaded.saved);
console.log(`Resumed a saved game from ${dataDir} (${loaded.saved.history.length} intents replayed).`);
} else if (loaded.found && !loaded.ok) {
// Refused explicitly (§12 step 15) — never silently replayed under rules it wasn't recorded
// under. The file is left untouched: rolling the running version back would let it load again.
console.error(
`Refusing to load ${dataDir}/game.json: it was saved under engine version ` +
`${loaded.storedVersion}, this server is running ${engineVersion}. Starting with no active ` +
`game. The saved file has not been touched.`,
);
}
startServer({ port, bindAddress, joinSecret, distDir, dataDir, engineVersion, initialSession });
console.log(`Station Master multiplayer server on ${bindAddress}:${port}, serving ${distDir}`);
+69
View File
@@ -0,0 +1,69 @@
/**
* Persistence — Phase 3 of `docs/architecture/multiplayer.md` (§12 steps 14-15;
* `lobby-and-sessions.md` §6 specifies the exact shape and reasoning).
*
* One game per process (Phase 2's scope, unchanged) — two files in `DATA_DIR`, no index and no
* `gameId`, both deferred to Phase 4's multi-game generalization same as the server core deferred
* them. Every write is a full-file atomic rewrite (write to `.tmp`, `rename` over the real path)
* rather than true on-disk appending: §6 says the storage mechanism is genuinely open as long as the
* LOGICAL history is never rewritten or reordered, which a full rewrite of an always-growing array
* satisfies — and at the measured scale (~350 intents, a few hundred bytes per game) there is nothing
* to optimize yet.
*/
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import type { SavedGame, TurnTiming } from './session.ts';
const GAME_FILE = 'game.json';
const TIMINGS_FILE = 'turn-timings.json';
type PersistedGame = SavedGame & { engineVersion: string };
async function atomicWrite(path: string, text: string): Promise<void> {
const tmp = `${path}.tmp`;
await writeFile(tmp, text);
await rename(tmp, path);
}
export async function writeGame(dataDir: string, saved: SavedGame, engineVersion: string): Promise<void> {
await mkdir(dataDir, { recursive: true });
const payload: PersistedGame = { engineVersion, ...saved };
await atomicWrite(join(dataDir, GAME_FILE), JSON.stringify(payload, null, 1));
}
export type LoadResult =
| { found: false }
| { found: true; ok: true; saved: SavedGame }
/** §12 step 15 — refused explicitly, never silently replayed under the wrong rules. */
| { found: true; ok: false; storedVersion: string; currentVersion: string };
export async function loadGame(dataDir: string, currentVersion: string): Promise<LoadResult> {
let text: string;
try {
text = await readFile(join(dataDir, GAME_FILE), 'utf8');
} catch {
return { found: false };
}
const payload = JSON.parse(text) as PersistedGame;
if (payload.engineVersion !== currentVersion) {
return { found: true, ok: false, storedVersion: payload.engineVersion, currentVersion };
}
const { engineVersion: _engineVersion, ...saved } = payload;
return { found: true, ok: true, saved };
}
/** Appended once per closed turn span (`GameSession.intent`'s `timing` result) — read-modify-write at
* this scale rather than real appending, same reasoning as `writeGame`. */
export async function appendTiming(dataDir: string, timing: TurnTiming): Promise<void> {
await mkdir(dataDir, { recursive: true });
const path = join(dataDir, TIMINGS_FILE);
let existing: TurnTiming[];
try {
existing = JSON.parse(await readFile(path, 'utf8')) as TurnTiming[];
} catch {
existing = [];
}
existing.push(timing);
await atomicWrite(path, JSON.stringify(existing, null, 1));
}
+200
View File
@@ -0,0 +1,200 @@
/**
* The game session host — Phases 2 and 3 of `docs/architecture/multiplayer.md` (§8, §12 steps 9,
* 14-16).
*
* Pure logic, no sockets, no filesystem — `src/server/http.ts` is the thin wiring that calls into
* this, and `src/server/persistence.ts` is what actually reads/writes disk. One `GameSession` per
* in-memory game (Phase 2 is one game per process; Phase 4 generalizes to many).
*
* REUSES `src/web/game.ts`'s `Game`/`submit`/`drain`/`currentActor`/`actionMenu` wholesale — all pure
* logic already, with no DOM dependency, exactly as `LocalSession` uses them client-side. Building a
* second copy of "apply an intent, narrate it, compute the Menu" here would drift from what solitaire
* already does and is tested against.
*
* ONE THING `game.ts`'s `submit` DOES NOT DO: verify who is calling it. `submit(game, intent)` reads
* `currentActor(game)` itself and applies the intent AS that player, regardless of who asked — safe
* for `LocalSession` (there is only ever one possible caller: the one browser). A server has more than
* one seat submitting, so THIS file is where "is `seat` actually allowed to act right now?" has to be
* checked, before `submit` is ever called — see `intent()` below.
*/
import { check } from '../engine/apply.ts';
import type { Intent } from '../engine/intents.ts';
import type { GameConfig, PlayerIndex } from '../engine/state.ts';
import { actionMenu, currentActor, fromMultiplayerSave, newMultiplayerGame, submit } from '../web/game.ts';
import type { Game, Menu } from '../web/game.ts';
import { deltaFrame } from '../sim/frame-delta.ts';
import type { FrameDelta } from '../sim/frame-delta.ts';
import { snapshot } from '../sim/view.ts';
import type { Frame } from '../sim/view.ts';
export type Push = {
frame: FrameDelta;
/** Non-null only for the seat that may currently act — never guess otherwise (`game.ts`'s `actionMenu` guards this too, but the host must still only compute/send it for the actor). */
menu: Menu | null;
/** Narration since the LAST push to this specific seat, not the whole game's log. */
lines: { text: string; tone: string }[];
};
/**
* `lobby-and-sessions.md` §5 — "wall-clock at the start of a turn, wall-clock at the intent that
* ends it, per player per phase." Computed entirely here, never touching the engine (which has no
* clock and must stay deterministic) and never stored inside `history` (a replay must reproduce a
* game from decisions alone).
*/
export type TurnTiming = {
player: PlayerIndex;
phase: string;
day: number;
stage: number;
startedAt: number;
endedAt: number;
};
/** Everything `persistence.ts` needs to write `game.json` and rebuild a session from it later. */
export type SavedGame = {
seed: number;
config: GameConfig;
playerNames: string[];
history: Intent[];
status: 'active' | 'finished';
createdAt: number;
};
export type IntentResult =
| { accepted: true; pushes: Map<PlayerIndex, Push>; timing: TurnTiming | null }
| { accepted: false; code: string };
export type GameSession = {
readonly playerCount: number;
/** A new SSE connection (or a reconnect) for `seat` — always a full Frame, never a delta. */
connect(seat: PlayerIndex): Push;
intent(seat: PlayerIndex, seq: number, i: Intent): IntentResult;
/** Everything needed to persist this game and, later, rebuild it via `resumeSession`. */
exportSave(): SavedGame;
};
type OpenSpan = { player: PlayerIndex; phase: string; day: number; stage: number; startedAt: number };
function buildSession(game: Game, playerNames: string[], createdAt: number): GameSession {
const lastSeq = new Map<PlayerIndex, number>();
const lastFrame = new Map<PlayerIndex, Frame>();
const sentLines = new Map<PlayerIndex, number>();
const openSpanFor = (now: number): OpenSpan | null => {
const actor = currentActor(game);
if (actor === null) return null;
return { player: actor, phase: game.state.clock.phase, day: game.state.clock.day, stage: game.state.clock.stage, startedAt: now };
};
let open: OpenSpan | null = openSpanFor(Date.now());
function frameFor(seat: PlayerIndex): Frame {
return snapshot(game.state, game.log, null, null, null, false, seat);
}
function linesSince(seat: PlayerIndex): { text: string; tone: string }[] {
const already = sentLines.get(seat) ?? 0;
sentLines.set(seat, game.log.length);
return game.log.slice(already);
}
function menuFor(seat: PlayerIndex): Menu | null {
return seat === currentActor(game) ? actionMenu(game, seat) : null;
}
function pushFor(seat: PlayerIndex): Push {
const frame = frameFor(seat);
const delta = deltaFrame(lastFrame.get(seat) ?? null, frame);
lastFrame.set(seat, frame);
return { frame: delta, menu: menuFor(seat), lines: linesSince(seat) };
}
function pushesForAll(): Map<PlayerIndex, Push> {
const out = new Map<PlayerIndex, Push>();
for (let seat = 0; seat < playerNames.length; seat++) out.set(seat as PlayerIndex, pushFor(seat as PlayerIndex));
return out;
}
/**
* Closes the open span if the acting player, phase, Day or Stage moved since it opened, and opens
* the next one (or none, in the automatic Mainline Phase). Returns the just-closed span, if any,
* for the caller to persist — a "turn" here is exactly the contiguous stretch where none of those
* four things changed, which can span several intents (draw, then play, then end) as one span.
*/
function settleTiming(): TurnTiming | null {
const now = Date.now();
const next = openSpanFor(now);
const same =
open !== null &&
next !== null &&
open.player === next.player &&
open.phase === next.phase &&
open.day === next.day &&
open.stage === next.stage;
if (same) return null;
const closed: TurnTiming | null = open === null ? null : { ...open, endedAt: now };
open = next;
return closed;
}
return {
playerCount: playerNames.length,
connect(seat) {
// A (re)connect always starts from a clean slate — no cache to trust across a lost connection
// (or a server restart, Phase 3) — so the honest thing is a full Frame, not a delta.
lastFrame.delete(seat);
return pushFor(seat);
},
intent(seat, seq, i) {
// Idempotent resend (protocol.md §5): a repeat of an ALREADY-APPLIED seq is a no-op success,
// with no pushes to re-broadcast. A repeat after a REJECTION is not remembered here — it was
// never applied, so it is worth trying again (see the `lastSeq.set` below: only on success).
if (lastSeq.get(seat) === seq) return { accepted: true, pushes: new Map(), timing: null };
if (seat !== currentActor(game)) return { accepted: false, code: 'NOT_YOUR_TURN' };
// Checked directly, rather than via `submit`'s boolean, for two reasons: `submit` writes a
// "that is not allowed" line into the SHARED `game.log` on rejection, which would otherwise
// broadcast one seat's illegal attempt to the whole table on their next push (rejection
// feedback is private, to the submitter only); and calling `check` first means an intent
// already known to be illegal never touches the engine at all.
const code = check(game.state, seat, i);
if (code) return { accepted: false, code };
const applied = submit(game, i);
/* c8 ignore next -- `check` above already proved this intent is legal; `submit` cannot then refuse it. */
if (!applied) return { accepted: false, code: 'REJECTED' };
lastSeq.set(seat, seq);
const timing = settleTiming();
return { accepted: true, pushes: pushesForAll(), timing };
},
exportSave() {
return {
seed: game.seed,
config: game.state.config,
playerNames: [...playerNames],
history: [...game.history],
status: game.state.status === 'finished' ? 'finished' : 'active',
createdAt,
};
},
};
}
export function createSession(seed: number, config: GameConfig, playerNames: string[]): GameSession {
return buildSession(newMultiplayerGame(seed, config, playerNames), playerNames, Date.now());
}
/**
* Phase 3 — rebuild a session from a persisted `SavedGame` (`persistence.ts`). The engine-version
* check happens before this is ever called; by the time `saved.history` reaches here it is already
* known to have been recorded under the currently-running rules.
*/
export function resumeSession(saved: SavedGame): GameSession {
const game = fromMultiplayerSave(saved.seed, saved.config, saved.playerNames, saved.history);
return buildSession(game, saved.playerNames, saved.createdAt);
}
+70 -7
View File
@@ -474,6 +474,65 @@ export function officeSvg(
return out;
};
/**
* A 45° LEG, drawn as a smooth curve rather than two straight segments meeting at a hard corner.
*
* It is an EASEMENT, not an arbitrary curve: tangent to horizontal at `p0` (the east or west edge),
* so an abutting straight card's through-rail still reads as one unbroken line, and tangent to
* exactly 45° at `p3` (the north or south edge), so two stacked curves still read as one continuous
* diagonal and the edge-crossing angle the matching rule depends on is unchanged. `p1`/`p2` are
* cubic-Bezier control points chosen to hit those two tangents — see the call site.
*
* Sampled as a short polyline rather than left as one SVG path command, because the two parallel
* rails and the tie marks all need points evenly spaced ALONG THE CURVE with the local tangent at
* each one — `rail()`'s straight-line version does the same sampling, just on a line.
*/
const curvedRail = (
p0: { x: number; y: number },
p1: { x: number; y: number },
p2: { x: number; y: number },
p3: { x: number; y: number },
): string => {
const at = (t: number): { x: number; y: number } => {
const u = 1 - t;
return {
x: u * u * u * p0.x + 3 * u * u * t * p1.x + 3 * u * t * t * p2.x + t * t * t * p3.x,
y: u * u * u * p0.y + 3 * u * u * t * p1.y + 3 * u * t * t * p2.y + t * t * t * p3.y,
};
};
const tangentAt = (t: number): { x: number; y: number } => {
const u = 1 - t;
return {
x: 3 * u * u * (p1.x - p0.x) + 6 * u * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x),
y: 3 * u * u * (p1.y - p0.y) + 6 * u * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y),
};
};
const N = 24;
const left: string[] = [];
const right: string[] = [];
let ties = '';
for (let i = 0; i <= N; i++) {
const t = i / N;
const pt = at(t);
const tan = tangentAt(t);
const tlen = Math.hypot(tan.x, tan.y) || 1;
const nx = (-tan.y / tlen) * 2.5;
const ny = (tan.x / tlen) * 2.5;
left.push(`${pt.x + nx} ${pt.y + ny}`);
right.push(`${pt.x - nx} ${pt.y - ny}`);
// Every third sample — the same rough 9px spacing `rail()` uses for a straight run of similar
// length, not tied to `N` itself.
if (i % 3 === 0) {
ties += `<line class="bs-tie" x1="${pt.x + nx * 1.8}" y1="${pt.y + ny * 1.8}" x2="${pt.x - nx * 1.8}" y2="${pt.y - ny * 1.8}"/>`;
}
}
return (
`<path class="bs-rail" fill="none" d="M${left.join(' L')}"/>` +
`<path class="bs-rail" fill="none" d="M${right.join(' L')}"/>` +
ties
);
};
// Where each port meets the card edge. East and west sit at the rail height — the card's middle —
// so a straight run stays straight across the whole row; north and south are centred on the edge.
const port = (p: string): { x: number; y: number } => {
@@ -534,19 +593,23 @@ export function officeSvg(
out += rail(port(from).x, port(from).y, port(to).x, port(to).y);
} else {
/**
* A 45° LEG, drawn as the card prints it: along the centre line from the east or west edge
* to the FROG, then out at exactly 45° through the middle of the north or south edge.
* A 45° LEG — drawn as a smooth curve (v0.5.0) that still passes through the same FROG the
* old two-segment version bent at, so the underlying geometry (and the `frog` position used
* elsewhere for the actual joining/matching rules) is unchanged; only the picture is.
*
* The frog is `H/2` from the centre because a 45° run climbing half the card's height
* travels half its height sideways. This used to be a fixed elbow at (W/2, RAIL+(H-RAIL)/2)
* — below the rail on the assumption everything diverged downward — which drew a leg
* reaching north as a hook that dropped past the rail and came back up, and drew nothing at
* any angle the matching rule cares about.
* travels half its height sideways. The control points sit halfway from each endpoint to the
* frog, which is what gives the curve a horizontal tangent at the e/w edge (matching an
* abutting straight card's through-rail) and an exact 45° tangent at the n/s edge (matching
* the card above or below) — see `curvedRail`.
*/
const side = vertical === from ? to : from;
const frog = { x: W / 2 + (side === 'e' ? H / 2 : -H / 2), y: RAIL };
const start = port(side);
const edge = port(vertical);
out += rail(port(side).x, port(side).y, frog.x, frog.y) + rail(frog.x, frog.y, edge.x, edge.y);
const c1 = { x: start.x + 0.5 * (frog.x - start.x), y: start.y };
const c2 = { x: edge.x + 0.5 * (frog.x - edge.x), y: edge.y + 0.5 * (frog.y - edge.y) };
out += curvedRail(start, c1, c2, edge);
}
}
+24 -11
View File
@@ -31,6 +31,12 @@
import { pump } from '../engine/advance.ts';
import { createGame } from '../engine/setup.ts';
import {
DEFAULT_MAX_COLLISIONS_PER_DAY,
DEFAULT_MAX_COLLISIONS_TOTAL,
collectiveRevenueFloor,
lengthProfile,
} from '../engine/content.ts';
import type { GameLength } from '../engine/content.ts';
import type { GameConfig, GameMode } from '../engine/state.ts';
import type { BotPolicy, BotTweaks } from './bot.ts';
@@ -56,17 +62,24 @@ export type PairedResult = {
variantStats: GameStats[];
};
const SOLO = (length: GameLength, mode: GameMode): GameConfig => ({
mode,
victory: 'highestAfterDays',
length,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
employeeRotation: false,
emergencyToolbox: false,
},
});
// Always one bot (`runOne` below), so the revenue floor is `collectiveRevenueFloor(1, days)`.
const SOLO = (length: GameLength, mode: GameMode): GameConfig => {
const days = lengthProfile(length).days;
return {
mode,
days,
minCombinedRevenue: collectiveRevenueFloor(1, days),
maxCollisionsPerDay: DEFAULT_MAX_COLLISIONS_PER_DAY,
maxCollisionsTotal: DEFAULT_MAX_COLLISIONS_TOTAL,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
employeeRotation: false,
emergencyToolbox: false,
},
};
};
/**
* One game, one seed, one policy.
+53
View File
@@ -0,0 +1,53 @@
/**
* Live per-seat Frame delta — Phase 2 of `docs/architecture/multiplayer.md`.
*
* `src/sim/replay.ts`'s `compress()` looked like the thing to reuse here (D2/D3's "2.9 KB per push
* with the board omitted when unchanged" cites it) but it solves a different problem: it interns
* card/description strings across a WHOLE recorded array of frames, which only pays off when
* bundling many frames into one replay file. A live server pushes one frame at a time and has
* nothing to intern against. The part that genuinely carries over is much smaller — a one-step-back
* "null if unchanged since the last thing sent to THIS seat" check on the three fields that make up
* almost all of a Frame's size: `cells`, `facilities`, `division` (`replay.ts`'s own `keys` array).
*
* Node-free by design, unlike `replay.ts` (which imports `node:fs`) — both the server and a browser
* `RemoteSession` import this file directly.
*/
import type { CellView, DivisionView, FacilityView, Frame } from './view.ts';
/** A `Frame` with the three board-shaped fields replaced by `null` where unchanged since `previous`. */
export type FrameDelta = Omit<Frame, 'cells' | 'facilities' | 'division'> & {
cells: CellView[] | null;
facilities: FacilityView[] | null;
division: DivisionView[] | null;
};
const BOARD_KEYS = ['cells', 'facilities', 'division'] as const;
/**
* `previous` is the last Frame actually sent to THIS seat, or `null` for a first connect / a
* reconnect after a gap — Phase 2 has no persistence to replay a gap against (Phase 3), so a
* reconnect always gets a full Frame here rather than a delta.
*/
export function deltaFrame(previous: Frame | null, next: Frame): FrameDelta {
const out = { ...next } as unknown as FrameDelta;
for (const key of BOARD_KEYS) {
const unchanged = previous !== null && JSON.stringify(previous[key]) === JSON.stringify(next[key]);
(out as Record<string, unknown>)[key] = unchanged ? null : next[key];
}
return out;
}
/** The receiving side: merges a delta back onto the last full Frame this seat actually has. */
export function applyDelta(previous: Frame | null, delta: FrameDelta): Frame {
const out = { ...delta } as unknown as Frame;
for (const key of BOARD_KEYS) {
if (delta[key] === null) {
if (previous === null) {
throw new Error(`deltaFrame said "${key}" is unchanged, but there is no previous Frame to merge onto`);
}
(out as Record<string, unknown>)[key] = previous[key];
}
}
return out;
}
+15 -6
View File
@@ -12,7 +12,12 @@
*/
import { pump } from '../engine/advance.ts';
import { collectiveRevenueFloor, lengthProfile } from '../engine/content.ts';
import {
DEFAULT_MAX_COLLISIONS_PER_DAY,
DEFAULT_MAX_COLLISIONS_TOTAL,
collectiveRevenueFloor,
lengthProfile,
} from '../engine/content.ts';
import { createGame } from '../engine/setup.ts';
import type { GameLength } from '../engine/content.ts';
import type { GameConfig, GameMode } from '../engine/state.ts';
@@ -60,11 +65,15 @@ function statsOf(xs: number[]): Stats {
};
}
function configFor(mode: GameMode, length: GameLength): GameConfig {
function configFor(mode: GameMode, length: GameLength, players: number): GameConfig {
const days = lengthProfile(length).days;
return {
mode,
victory: 'highestAfterDays',
length,
days,
minCombinedRevenue: collectiveRevenueFloor(players, days),
maxCollisionsPerDay: DEFAULT_MAX_COLLISIONS_PER_DAY,
maxCollisionsTotal: DEFAULT_MAX_COLLISIONS_TOTAL,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
@@ -83,7 +92,7 @@ export function simulate(opts: SimOptions): SimReport {
const s = createGame({
id: `sim-${i}`,
seed,
config: configFor(opts.mode, opts.length),
config: configFor(opts.mode, opts.length, opts.players.length),
playerNames: opts.players,
});
// The probe watches the game as it is played: the funnel gates are conditions at a moment, not
@@ -154,7 +163,7 @@ export function formatReport(r: SimReport, length: GameLength, players: number):
// The provisional numbers this exists to test.
out.push('\n against the provisional targets:');
out.push(` target ${profile.target} over ${profile.days} Days`);
out.push(` ${profile.days} Days`);
out.push(
` predicted ~5-6 revenue/player/Day steady state; observed mean ` +
`${r.revenuePerPlayerPerDay.mean.toFixed(1)}`,
+16 -5
View File
@@ -21,7 +21,14 @@ import { writeFileSync } from 'node:fs';
import { advance } from '../engine/advance.ts';
import { applyIntent, areaOf, facilityCarType, laborersLeft, portersLeft } from '../engine/apply.ts';
import type { GameLength } from '../engine/content.ts';
import { MAINLINE_PROFILES, lengthProfile, officeProfile } from '../engine/content.ts';
import {
DEFAULT_MAX_COLLISIONS_PER_DAY,
DEFAULT_MAX_COLLISIONS_TOTAL,
MAINLINE_PROFILES,
collectiveRevenueFloor,
lengthProfile,
officeProfile,
} from '../engine/content.ts';
import type { GameEvent } from '../engine/events.ts';
import type { Intent } from '../engine/intents.ts';
import { legalActions } from '../engine/legal.ts';
@@ -51,10 +58,14 @@ import { playCue } from '../web/sound.ts';
export type Recording = { seed: number; length: GameLength; frames: Frame[]; outcome: string };
export function record(seed: number, length: GameLength, maxSteps = 100_000): Recording {
const days = lengthProfile(length).days;
const config: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length,
days,
minCombinedRevenue: collectiveRevenueFloor(1, days),
maxCollisionsPerDay: DEFAULT_MAX_COLLISIONS_PER_DAY,
maxCollisionsTotal: DEFAULT_MAX_COLLISIONS_TOTAL,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
@@ -263,7 +274,7 @@ export function rehydrateCells(
}
export function renderHtml(rec: Recording): string {
const target = lengthProfile(rec.length);
const profile = lengthProfile(rec.length);
return `<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
@@ -360,7 +371,7 @@ kbd{background:#2a3038;border:1px solid var(--line);border-radius:3px;padding:0
</style></head><body>
<header>
<h1>Station Master — replay · seed ${rec.seed} · ${rec.length} (target ${target.target} over ${target.days} Days) · ${esc(rec.outcome)}</h1>
<h1>Station Master — replay · seed ${rec.seed} · ${rec.length} (${profile.days} Days) · ${esc(rec.outcome)}</h1>
<div class="bar">
<span class="dim">fedora <span id="super">—</span></span>
<span>revenue <b class="big" id="rev">0</b></span>
+50 -8
View File
@@ -24,6 +24,7 @@ import {
import {
ACTION_CARDS,
ENHANCEMENT_CARDS,
HAND_LIMIT,
MAINLINE_MODIFIER_CARDS,
MAINLINE_PROFILES,
MANEUVER_CARDS,
@@ -37,7 +38,6 @@ import {
industryProfile,
mainlineProfile,
modifierProfile,
lengthProfile,
officeProfile,
trainProfile,
houseRules,
@@ -348,6 +348,18 @@ export type Frame = {
* must be able to answer. Resolved, never partial, so nobody downstream re-applies defaults.
*/
houseRules: HouseRules;
/**
* The victory-condition dials this game was configured with (`GameConfig`, `state.ts`), plus the
* running collision counts — same reasoning as `houseRules`: a remote client holds no `GameState`
* and needs to show live progress ("2 of 3 collisions today") without guessing a default. `0` on
* any `max*`/`minCombinedRevenue` field means that check is off.
*/
days: number;
minCombinedRevenue: number;
maxCollisionsPerDay: number;
maxCollisionsTotal: number;
collisionsToday: number;
collisionsTotal: number;
status: GameState['status'];
outcome: GameState['outcome'];
/**
@@ -360,6 +372,13 @@ export type Frame = {
players: { index: number; seat: number; name: string; revenue: number; hand: number }[];
/** How many cards the VIEWER holds. Other players' counts are in `players`. */
handCount: number;
/**
* True when the VIEWER's hand is over §6.2's limit and their turn cannot end until it is played
* down. Duplicates `game.ts`'s `overHandLimit(game, seat)` at the engine-data level rather than
* importing the web layer here — a `RemoteSession` (Phase 2) has no `GameState` to compute this
* from, only a `Frame`, so it has to already be resolved on the wire.
*/
overHandLimit: boolean;
lines: { text: string; tone: string }[];
where: { row: number; col: number } | null;
/** Origin of a Move, so the crew's journey is visible rather than a chip teleporting. */
@@ -1207,6 +1226,12 @@ export function snapshot(
wasted,
option: turnOf(s, viewer).option,
houseRules: houseRules(s.config),
days: s.config.days,
minCombinedRevenue: s.config.minCombinedRevenue,
maxCollisionsPerDay: s.config.maxCollisionsPerDay,
maxCollisionsTotal: s.config.maxCollisionsTotal,
collisionsToday: s.collisionsToday,
collisionsTotal: s.collisionsTotal,
status: s.status,
outcome: s.outcome,
players: s.players.map((p) => ({
@@ -1217,6 +1242,8 @@ export function snapshot(
hand: (s.decks.hands.get(p.index) ?? []).length,
})),
handCount: (s.decks.hands.get(viewer) ?? []).length,
overHandLimit:
(s.decks.hands.get(viewer) ?? []).length > (s.decks.redFlags.get(viewer) ? HAND_LIMIT + 1 : HAND_LIMIT),
objective: objectiveOf(s, viewer),
runningRow: area.runningRow,
limits: { west: area.limitsWest.col, east: area.limitsEast.col },
@@ -1633,21 +1660,36 @@ const SIMPLE_CARDS = [
...ACTION_CARDS,
];
/** The goal, and whether the VIEWER's score is keeping up with the clock. */
/**
* The goal, and whether the VIEWER's score is keeping up with the clock.
*
* `target` is `config.minCombinedRevenue` now (2026-08-20) — the floor below which everyone loses,
* not a per-player win threshold; `days` and `daysLeft` come off `config.days`. Paced against the
* VIEWER's own Revenue, same as before: exact for solitaire (the viewer IS the whole table), an
* approximation for competitive/coop until Phase 2 gives the objective panel a combined-progress
* view of its own. `0` means no floor is configured — nothing to pace against.
*/
function objectiveOf(s: GameState, viewer: PlayerIndex): Frame['objective'] {
const profile = lengthProfile(s.config.length);
const { days, minCombinedRevenue: target } = s.config;
const revenue = s.players[viewer]?.revenue ?? 0;
const daysLeft = Math.max(0, profile.days - s.clock.day + 1);
const elapsed = profile.days - daysLeft + 1;
const daysLeft = Math.max(0, days - s.clock.day + 1);
const elapsed = days - daysLeft + 1;
if (target <= 0) {
const note =
daysLeft === 0
? 'the last Day is over'
: `${revenue} · ${daysLeft} Day${daysLeft === 1 ? '' : 's'} left · no minimum this game`;
return { target: 0, days, daysLeft, onPace: true, note };
}
// Straight-line pace: by the end of Day N you want N/days of the target.
const expected = (profile.target * elapsed) / profile.days;
const expected = (target * elapsed) / days;
const onPace = revenue >= expected;
const note =
daysLeft === 0
? 'the last Day is over'
: `${revenue} of ${profile.target} · ${daysLeft} Day${daysLeft === 1 ? '' : 's'} left · ` +
: `${revenue} of ${target} · ${daysLeft} Day${daysLeft === 1 ? '' : 's'} left · ` +
(onPace ? 'on pace' : `behind pace (about ${Math.ceil(expected)} by now)`);
return { target: profile.target, days: profile.days, daysLeft, onPace, note };
return { target, days, daysLeft, onPace, note };
}
/**
+102 -5
View File
@@ -44,9 +44,13 @@ import {
variantLabel,
} from '../sim/view.ts';
import {
DEFAULT_DAYS,
DEFAULT_HOUSE_RULES,
DEFAULT_MAX_COLLISIONS_PER_DAY,
DEFAULT_MAX_COLLISIONS_TOTAL,
HAND_LIMIT,
LEGACY_HOUSE_RULES,
collectiveRevenueFloor,
houseRules,
mainlineProfile,
trainProfile,
@@ -57,10 +61,19 @@ import { connectionsFor, joins, neighbour, variantsFor } from '../engine/track.t
import { areaOf, destinationsFor, selectDestination, trainNeedingCars } from '../engine/apply.ts';
import type { Frame } from '../sim/view.ts';
/**
* The canonical "what does a fresh solitaire game look like" config — also what the New Game
* dialog's solitaire defaults are drawn from (`main.ts`). One player, so `minCombinedRevenue` uses
* `collectiveRevenueFloor(1, DEFAULT_DAYS)` — the same formula multiplayer configs use, just at
* player count 1.
*/
export const SOLO_CONFIG: GameConfig = {
mode: 'solitaire',
victory: 'highestAfterDays',
length: 'standard',
days: DEFAULT_DAYS,
minCombinedRevenue: collectiveRevenueFloor(1, DEFAULT_DAYS),
maxCollisionsPerDay: DEFAULT_MAX_COLLISIONS_PER_DAY,
maxCollisionsTotal: DEFAULT_MAX_COLLISIONS_TOTAL,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
sisterTrains: false,
@@ -72,9 +85,29 @@ export const SOLO_CONFIG: GameConfig = {
houseRules: DEFAULT_HOUSE_RULES,
};
/**
* Everything the New Game dialog can set for a solitaire game — the opening deal and the three
* revenue rates (`houseRules`, unchanged), plus the four victory-condition dials added 2026-08-20.
* Solitaire's `pvpCardsAllowed` is not here: it is forced off (`SOLO_CONFIG`), never a player choice.
*/
export type NewGameOptions = {
houseRules?: HouseRuleOverrides;
days?: number;
minCombinedRevenue?: number;
maxCollisionsPerDay?: number;
maxCollisionsTotal?: number;
};
/** The same config with the New Game dialog's answers in it. */
export function configWith(rules: HouseRuleOverrides): GameConfig {
return { ...SOLO_CONFIG, houseRules: houseRules({ houseRules: rules }) };
export function configWith(opts: NewGameOptions): GameConfig {
return {
...SOLO_CONFIG,
days: opts.days ?? SOLO_CONFIG.days,
minCombinedRevenue: opts.minCombinedRevenue ?? SOLO_CONFIG.minCombinedRevenue,
maxCollisionsPerDay: opts.maxCollisionsPerDay ?? SOLO_CONFIG.maxCollisionsPerDay,
maxCollisionsTotal: opts.maxCollisionsTotal ?? SOLO_CONFIG.maxCollisionsTotal,
houseRules: houseRules(opts.houseRules ? { houseRules: opts.houseRules } : {}),
};
}
/** A group of legal actions of one kind, ready to put on screen. */
@@ -237,6 +270,23 @@ export function newGame(seed: number, config: GameConfig = SOLO_CONFIG): Game {
return game;
}
/**
* `newGame`'s multi-player sibling — the server session host (Phase 2) needs a `Game` wrapper for
* more than one seat, and `newGame` hardcodes `[SOLO_PLAYER]`. Kept as a separate function rather
* than a shared parametrized helper: `newGame` is exercised by every solitaire test and save, and
* reordering its log-then-drain sequence to share code with this risks nothing for a marginal DRY
* gain. `submit`/`drain`/`actionMenu`/`currentActor` all work on either unchanged, since none of them
* know or care how many players a `Game` has.
*/
export function newMultiplayerGame(seed: number, config: GameConfig, playerNames: string[]): Game {
const state = createGame({ id: `mp-${seed}`, seed, config, playerNames });
const game: Game = { state, seed, history: [], log: [], mustPlayCard: false, cues: [], scheduled: null, justDrawn: null, announced: null };
game.log.push({ text: 'Game Begins', tone: 'start' });
game.log.push({ text: `${config.mode} · ${playerNames.length} players · seed ${seed}`, tone: 'quiet' });
drain(game);
return game;
}
/**
* Run the engine forward until it needs a decision.
*
@@ -530,7 +580,16 @@ export type Menu = {
/** The action list as the page shows it: direct actions, plus subject-then-location for the rest. */
export function actionMenu(game: Game, seat: PlayerIndex = 0): Menu {
const { options, groups } = actionGroups(game);
/**
* SEAT-SAFETY. `actionGroups`/`legalActions` answer for `currentActor(game)`, not for `seat` — there
* is exactly one acting player at a time, so a Menu built for anyone else must show no actions at
* all, only their own hand (found the hard way: calling this for a non-acting seat used to hand
* back the ACTOR's legal moves paired with the WRONG seat's cards). Emptying `options`/`groups` here
* degrades every downstream computation (`direct`, `placeable`, `makeUp`) to empty for free — the
* hand section below still reads `seat`'s own cards correctly either way.
*/
const isActor = seat === currentActor(game);
const { options, groups } = isActor ? actionGroups(game) : { options: [] as Intent[], groups: [] as ActionGroup[] };
const direct: ActionGroup[] = [];
const placeableByTitle = new Map<string, Map<string, Placeable>>();
@@ -1079,3 +1138,41 @@ export function fromSave(save: Save, config: GameConfig = SOLO_CONFIG): Game {
}
return game;
}
/**
* `fromSave`'s multi-player sibling — Phase 3 (`docs/architecture/multiplayer.md`): "a mid-game
* server restart is a replay rather than a recovery" (`lobby-and-sessions.md` §6). Built on
* `newMultiplayerGame` instead of `newGame` since a saved multiplayer game did not deal to
* `[SOLO_PLAYER]`. The engine-version check belongs to the caller (`src/server/persistence.ts`) —
* this function only ever reconstructs from history that is already known to have been recorded
* under the currently-running rules.
*
* UNLIKE `fromSave`'s loop, this passes `actor` to `record()` (matching `submit`'s own call,
* `game.ts` above) — found while testing Phase 3's resume path: without it, every replayed line loses
* its "Player X" attribution and reads as anonymous "Chose to..." narration, which `record`'s own
* comment calls "unreadable the moment there is more than one seat" — exactly the multiplayer case a
* resumed game hits every time. `fromSave` has the same gap (it predates multiplayer and nothing ever
* compares its output against a LIVE-played log, so it has gone unnoticed — `undo`'s rebuilt game is
* itself `fromSave`-built, so `test/web.test.ts`'s replay-fidelity test only ever compares one
* unattributed replay against another). Flagged in `TODO.md` rather than fixed there in this pass —
* out of scope for Phase 3 and used far more widely, so worth its own careful look rather than a
* touch-in-passing.
*/
export function fromMultiplayerSave(
seed: number,
config: GameConfig,
playerNames: string[],
history: Intent[],
): Game {
const game = newMultiplayerGame(seed, config, playerNames);
for (const intent of history) {
const actor = currentActor(game);
if (actor === null) break;
const result = applyIntent(game.state, actor, intent);
if (!result.ok) break;
game.history.push(intent);
record(game, result.events, actor);
drain(game);
}
return game;
}
+263 -37
View File
@@ -12,21 +12,89 @@ import type { Menu, Save } from './game.ts';
import { PANEL_CSS, blockedHtml, facilitiesHtml, pilesHtml, timetableHtml, yardHtml } from './panels.ts';
import { TOOLTIP_CSS, installTooltips } from './tooltip.ts';
import { playCue } from './sound.ts';
import { MOVES_PER_LOCAL_OPS, STARTING_HAND_LABELS, houseRules } from '../engine/content.ts';
import {
DEFAULT_MAX_COLLISIONS_PER_DAY,
DEFAULT_MAX_COLLISIONS_TOTAL,
MOVES_PER_LOCAL_OPS,
STARTING_HAND_LABELS,
collectiveRevenueFloor,
houseRules,
} from '../engine/content.ts';
import type { HouseRuleOverrides, HouseRules, RevenueRules, StartingHand } from '../engine/content.ts';
import type { LocalSession } from './session.ts';
import { createLocalSession } from './session.ts';
import type { NewGameOptions } from './game.ts';
import type { LocalSession, Session } from './session.ts';
import { createLocalSession, createRemoteSession } from './session.ts';
import type { PlayerIndex } from '../engine/state.ts';
const SAVE_KEY = 'station-master.save.v1';
const SETTINGS_KEY = 'station-master.settings.v1';
/** Preset board zoom levels — a fraction applied to the rendered SVG's own pixel dimensions. */
const ZOOM_LEVELS = [0.75, 1, 1.25, 1.5] as const;
/**
* The game, behind the Session boundary.
*
* Typed as `LocalSession` because this page is the solitaire client and uses undo, local saves and
* new-game — all of which are local-only. The parts that draw and submit go through the plain
* `Session` surface, which is what a remote client will provide unchanged.
* Small persisted preferences, kept in a `localStorage` key of their own — separate from
* `SAVE_KEY`. A save is the seed plus the intents and has to stay portable; none of this belongs
* in it, and in a multiplayer game two players may reasonably want these set differently. Grows as
* more of the page's display state earns a preference; `districtMode`/`soundOn`/`zoom` are the
* first three.
*/
let session: LocalSession;
type Settings = {
districtMode: 'auto' | 'open' | 'closed';
soundOn: boolean;
zoom: number;
};
const DEFAULT_SETTINGS: Settings = { districtMode: 'auto', soundOn: false, zoom: 1 };
function loadSettings(): Settings {
try {
const raw = localStorage.getItem(SETTINGS_KEY);
const parsed = raw ? (JSON.parse(raw) as Partial<Settings>) : {};
// A missing key, a corrupt value, or a level dropped from `ZOOM_LEVELS` since it was saved all
// fall back to the default for that one field, rather than rejecting the whole object.
return {
districtMode:
parsed.districtMode === 'open' || parsed.districtMode === 'closed' ? parsed.districtMode : 'auto',
soundOn: typeof parsed.soundOn === 'boolean' ? parsed.soundOn : DEFAULT_SETTINGS.soundOn,
zoom:
typeof parsed.zoom === 'number' && (ZOOM_LEVELS as readonly number[]).includes(parsed.zoom)
? parsed.zoom
: DEFAULT_SETTINGS.zoom,
};
} catch {
// A full or disabled localStorage must not take the game down with it — same guard as the save.
return { ...DEFAULT_SETTINGS };
}
}
let settings = loadSettings();
function saveSettings(patch: Partial<Settings>): void {
settings = { ...settings, ...patch };
try {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
} catch {
/* nothing to do */
}
}
/**
* The game, behind the Session boundary — `LocalSession` (solitaire, `?seat=` absent from the URL)
* or `RemoteSession` (`?seat=` present, Phase 2). Typed as the common `Session` surface; every
* LocalSession-only touch (undo, local saves, dealing a new game) goes through `isLocal` below rather
* than assuming, since `session` may now be either.
*/
let session: Session;
/**
* The three `Capabilities` (`undo`/`saveLocal`/`newGame`) travel together — all `true` for a
* `LocalSession`, all `false` for a `RemoteSession` (`session.ts`) — so any one of them is a safe
* discriminant. `newGame` is used here since it reads clearly at every call site: "only if this
* session can deal locally."
*/
function isLocal(s: Session): s is LocalSession {
return s.capabilities.newGame;
}
/** Which card or track piece is picked, waiting for a location. */
let selected: string | null = null;
/**
@@ -49,18 +117,20 @@ let pendingAt: string | null = null;
*
* 'auto' follows the phase; 'open' and 'closed' are the player overriding it and stay put until
* they change it again. Display only — in a multiplayer game two players may reasonably want it
* set differently, so this must never become part of game state.
* set differently, so this must never become part of game state. Persisted in `settings`, not the
* save, for exactly that reason.
*/
let districtMode: 'auto' | 'open' | 'closed' = 'auto';
let districtMode: 'auto' | 'open' | 'closed' = settings.districtMode;
/**
* Sound, OFF until asked for.
* Sound, OFF by default until a player asks for it once — then remembered via `settings`.
*
* Everything it plays is synthesised rather than recorded, so it is a placeholder for real audio
* rather than the finished thing — and a playtester who did not ask for noise should not get any.
* One click in the title bar turns it on, and that click is also the gesture browsers require
* before any audio may start.
* rather than the finished thing. One click in the title bar turns it on, and that click is also
* the gesture browsers require before any audio may start.
*/
let soundOn = false;
let soundOn = settings.soundOn;
/** Preset board zoom (see `ZOOM_LEVELS`), persisted in `settings`. */
let zoom = settings.zoom;
/**
* The phase the page last drew, so a change of phase can be announced.
*
@@ -99,6 +169,23 @@ const $ = (id: string): HTMLElement => {
const esc = (s: string): string =>
s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c);
/**
* Size a freshly-rendered board SVG off its own `viewBox`, at the current `zoom`.
*
* `#grid` and `#division` already scroll horizontally when their content is wider than the column
* (`overflow-x:auto` in `play.html`) — that mechanism is untouched. This only changes how big the
* SVG itself renders, in real pixels rather than a CSS `transform` (which would leave the container's
* scrollable area the wrong size), so zooming in genuinely grows the scrollable area and zooming out
* genuinely shrinks it.
*/
function applyZoom(container: HTMLElement): void {
const svg = container.querySelector('svg');
const box = svg?.viewBox.baseVal;
if (!svg || !box || box.width === 0) return;
svg.style.width = `${box.width * zoom}px`;
svg.style.height = `${box.height * zoom}px`;
}
/**
* A DRAWING OF THE PIECE A PLACEMENT WOULD LAY.
*
@@ -153,19 +240,27 @@ function renderHouseRules(rules: HouseRules): void {
}
/**
* THE HOUSE RULES TRAVEL IN THE URL, BESIDE THE SEED.
* THE HOUSE RULES AND VICTORY DIALS TRAVEL IN THE URL, BESIDE THE SEED.
*
* A seed on its own no longer names a game: `?seed=430` dealt three random cards is a different
* railroad from `?seed=430` dealt three track and three other, and at 0 Revenue per transit it is a
* different economy again. The link has to carry all of it or "same link, same deal" stops being
* true — and the New Game dialog navigates by URL, so this is also how its answers reach `start()`.
* different economy again — and now a game with `minrev=15` is a different game from one with
* `minrev=0`. The link has to carry all of it or "same link, same deal" stops being true — and the
* New Game dialog navigates by URL, so this is also how its answers reach `start()`.
*
* Absent parameters mean the DEFAULTS, not the legacy rules: a bare `?seed=430` is a new game at
* today's settings. It is a save with no rules in it that is old (`game.ts`, `configFor`).
*/
const RULE_PARAMS = { passenger: 'passengerPerCoach', freight: 'freightPerLoad', transit: 'trainPerTransit' } as const;
/** The four victory-condition dials added 2026-08-20 (`GameConfig`), same URL-round-trip convention. */
const VICTORY_PARAMS = {
days: 'days',
minrev: 'minCombinedRevenue',
colday: 'maxCollisionsPerDay',
coltotal: 'maxCollisionsTotal',
} as const;
function rulesFromUrl(params: URLSearchParams): HouseRuleOverrides {
function gameOptionsFromUrl(params: URLSearchParams): NewGameOptions {
const rules: HouseRuleOverrides = {};
const hand = params.get('hand');
if (STARTING_HAND_LABELS.some((o) => o.value === hand)) rules.startingHand = hand as StartingHand;
@@ -178,29 +273,62 @@ function rulesFromUrl(params: URLSearchParams): HouseRuleOverrides {
if (raw !== null && raw.trim() !== '' && Number.isFinite(Number(raw))) revenue[key] = Number(raw);
}
if (Object.keys(revenue).length > 0) rules.revenue = revenue;
return rules;
const options: NewGameOptions = { houseRules: rules };
for (const [param, key] of Object.entries(VICTORY_PARAMS)) {
const raw = params.get(param);
// Negative or fractional values from a hand-edited URL are clamped the same way `configWith`'s
// defaults are — a stray `minrev=-5` should mean "off-ish", not a config the engine never sees.
if (raw !== null && raw.trim() !== '' && Number.isFinite(Number(raw))) {
options[key] = Math.max(0, Math.round(Number(raw)));
}
}
return options;
}
function rulesToUrl(rules: HouseRules, seed: string): string {
function rulesToUrl(rules: HouseRules, options: NewGameOptions, seed: string): string {
const params = new URLSearchParams();
if (seed !== '') params.set('seed', seed);
params.set('hand', rules.startingHand);
for (const [param, key] of Object.entries(RULE_PARAMS)) params.set(param, String(rules.revenue[key]));
for (const [param, key] of Object.entries(VICTORY_PARAMS)) {
const value = options[key];
if (value !== undefined) params.set(param, String(value));
}
return `?${params}`;
}
/**
* `?seat=` PRESENT means multiplayer (D4 — one bundle, runtime switch). The seed, house rules and
* URL-carried save/restore logic below are all solitaire concepts: a remote game's rules come from
* whatever the server was configured with, not from this browser's URL or `localStorage`.
*/
function start(): void {
const params = new URLSearchParams(location.search);
const requested = params.get('seed');
const seatParam = params.get('seat');
if (seatParam !== null) {
const seat = Number(seatParam) as PlayerIndex;
session = createRemoteSession(seat, params.get('secret') ?? '');
applyCapabilities();
// A LocalSession has data the instant it is constructed; a RemoteSession does not — its first
// real Frame only exists once the SSE connection's first push arrives, so the first render waits
// for `subscribe`'s callback rather than firing immediately (`session.ts`'s own doc comment on
// `createRemoteSession` explains why `view()` would otherwise throw).
session.subscribe(render);
return;
}
const requested = params.get('seed');
// A seed in the URL makes a game shareable and reproducible: same link, same deal.
const seed = requested !== null ? Number(requested) || 1 : Math.floor(Math.random() * 1e9);
session = createLocalSession(seed, rulesFromUrl(params));
const local = createLocalSession(seed, gameOptionsFromUrl(params));
session = local;
// A saved game carries its OWN rules and re-deals itself under them, whatever the URL says — see
// `configFor`. That is why the restore happens after the session is built rather than feeding it.
const saved = load();
if (saved && requested === null) session.restore(saved);
if (saved && requested === null) local.restore(saved);
applyCapabilities();
// Every render goes through the session, so the page redraws whenever the game says it changed —
@@ -263,11 +391,14 @@ function render(): void {
const obj = $('objective');
obj.textContent = `${f.revenue} of ${f.objective.target} · ${f.objective.daysLeft} Day${f.objective.daysLeft === 1 ? '' : 's'} left`;
obj.className = 'pace';
$('seed').textContent = String(session.seed());
// The seed is never sent to a remote client at all (it would leak every future shuffle and roll,
// `multiplayer.md` §7) — `RemoteSession` has no `.seed()` because there is nothing to return.
$('seed').textContent = isLocal(session) ? String(session.seed()) : `Seat ${session.seat()}`;
renderHouseRules(f.houseRules);
// -- division
$('division').innerHTML = divisionSvg(f.division);
applyZoom($('division'));
// -- board. Both renderers are shared with the replay so the two can never draw different
// pictures of the same position.
@@ -302,6 +433,7 @@ function render(): void {
return [{ row: cell.row, col: cell.col, label }];
});
grid.innerHTML = officeSvg(f.cells, f.runningRow, ghostCoords, legalCaps, f.limits, selectedCrew);
applyZoom(grid);
// Wire the roster chips: clicking one sets `selectedCrew`, the same value the "Which train are
// you switching?" picker writes, so the board and the action panel drive one value either way.
@@ -593,14 +725,18 @@ function render(): void {
*/
function renderUndo(): void {
const btn = document.getElementById('undo') as HTMLButtonElement | null;
if (!btn || !session.capabilities.undo) return;
const n = session.steps();
if (!btn || !isLocal(session)) return;
// Captured as a `const` rather than read as `session` again inside the closure below: `session` is
// a mutable module-level `let`, so TypeScript cannot carry the `isLocal` narrowing across a closure
// boundary — a local const it can never see reassigned keeps the narrowed `LocalSession` type.
const local = session;
const n = local.steps();
btn.disabled = n === 0;
btn.textContent = n === 0 ? 'Undo' : `Undo (${n})`;
btn.onclick = () => {
// The session drops the rebuilt game's cues and draws — replaying the history re-records them,
// and none of it is news to a player who just stepped back.
if (!session.undo()) return;
if (!local.undo()) return;
selected = null;
mode = null;
pendingAt = null;
@@ -657,6 +793,7 @@ function renderDistrict(f: Frame): void {
btn.onclick = () => {
// auto -> pin it to the opposite of what auto is doing -> back to auto.
districtMode = districtMode === 'auto' ? (open ? 'closed' : 'open') : 'auto';
saveSettings({ districtMode });
render();
};
}
@@ -980,6 +1117,10 @@ function renderActions(
* where a rendered page would have been megabytes.
*/
function downloadSave(): void {
// The button this fires from is hidden by `applyCapabilities()` for any session that cannot save
// (`#savefile`), but nothing stops this function being called directly, so the guard is repeated
// here rather than only trusted to the DOM.
if (!isLocal(session)) return;
const data = JSON.stringify(session.save(), null, 1);
const blob = new Blob([data], { type: 'application/json' });
const url = URL.createObjectURL(blob);
@@ -991,7 +1132,7 @@ function downloadSave(): void {
}
function save(): void {
if (!session.capabilities.saveLocal) return;
if (!isLocal(session)) return;
try {
localStorage.setItem(SAVE_KEY, JSON.stringify(session.save()));
} catch {
@@ -1043,32 +1184,79 @@ const newBtn = document.getElementById('newgame');
const dlg = document.getElementById('newgamedlg') as HTMLDialogElement | null;
if (newBtn && dlg) {
const field = <T extends HTMLElement>(id: string): T => document.getElementById(id) as T;
type Mode = 'solitaire' | 'competitive' | 'coop';
/**
* ASK FOR ALL THREE, rather than documenting URL parameters in the title bar.
* PICKING A TYPE JUST SETS THE FIELDS BELOW TO THAT TYPE'S DEFAULTS (Jesse's design, 2026-08-20) —
* every number stays editable afterward, so "Competitive" isn't a fixed ruleset, it's a starting
* point. `players = 4` for Competitive/Co-op is a nominal stand-in: there's no lobby yet to ask who
* is actually seated (Phase 4), so this is a suggestion a real seat count will replace.
*
* Only Solitaire can be dealt today — Deal disables itself for the other two, with a note, rather
* than pretending a click would do something (`RemoteSession` is Phase 2).
*/
function applyModePreset(mode: Mode): void {
const days = 5;
const players = mode === 'solitaire' ? 1 : 4;
field<HTMLInputElement>('ng-days').value = String(days);
field<HTMLInputElement>('ng-minrev').value = String(collectiveRevenueFloor(players, days));
field<HTMLInputElement>('ng-colday').value = String(DEFAULT_MAX_COLLISIONS_PER_DAY);
field<HTMLInputElement>('ng-coltotal').value = String(DEFAULT_MAX_COLLISIONS_TOTAL);
// No valid target for these cards in Solitaire or Co-op — forced off, not merely defaulted off.
const pvp = field<HTMLInputElement>('ng-pvp');
pvp.checked = mode === 'competitive';
pvp.disabled = mode !== 'competitive';
field<HTMLButtonElement>('ng-deal').disabled = mode !== 'solitaire';
field<HTMLElement>('ng-multiplayer-note').style.visibility = mode === 'solitaire' ? 'hidden' : 'visible';
}
for (const input of dlg.querySelectorAll<HTMLInputElement>('input[name="ng-mode"]')) {
input.onchange = () => applyModePreset(input.value as Mode);
}
/**
* ASK FOR ALL OF IT, rather than documenting URL parameters in the title bar.
*
* It asked for the seed alone, through `prompt()`. The opening hand and the three revenue rates
* were constants in the source, so trying a variation meant an edit and a rebuild — and balance is
* the open question this game has (`TODO.md`). A dialog is what lets a playtest be a playtest.
*
* The dialog OPENS ON THE RULES IN PLAY rather than on the defaults: dealing a second game to
* compare against the first is the common case, and re-entering four settings each time is how a
* comparison silently stops comparing.
* compare against the first is the common case, and re-entering settings each time is how a
* comparison silently stops comparing. Mode always reopens on Solitaire — it's the only one a
* previous session could actually have been, since Deal is disabled for the other two.
*/
newBtn.onclick = () => {
const f = session.view();
// The button itself is hidden for a session that cannot deal (`applyCapabilities`), but the
// dialog's whole answer-reading/URL-navigating flow below assumes a LocalSession throughout, so
// the guard is repeated — and `local` is captured as a `const` so the narrowing survives the
// closures below it (see `renderUndo`'s identical note on why `session` itself cannot be).
if (!isLocal(session)) return;
const local = session;
const f = local.view();
const day = f.day;
const started = f.status === 'active' && (day > 1 || f.stage > 1);
if (started && !confirm(`Forget this game (seed ${session.seed()}, Day ${day}) and deal a new one?`)) return;
if (started && !confirm(`Forget this game (seed ${local.seed()}, Day ${day}) and deal a new one?`)) return;
const current = session.view().houseRules;
const current = f.houseRules;
field<HTMLInputElement>('ng-seed').value = '';
for (const input of dlg.querySelectorAll<HTMLInputElement>('input[name="ng-mode"]')) {
input.checked = input.value === 'solitaire';
}
applyModePreset('solitaire');
for (const input of dlg.querySelectorAll<HTMLInputElement>('input[name="ng-hand"]')) {
input.checked = input.value === current.startingHand;
}
field<HTMLInputElement>('ng-passenger').value = String(current.revenue.passengerPerCoach);
field<HTMLInputElement>('ng-freight').value = String(current.revenue.freightPerLoad);
field<HTMLInputElement>('ng-transit').value = String(current.revenue.trainPerTransit);
// Overwrite the preset with the actual rules in play — solitaire is the only real session today.
field<HTMLInputElement>('ng-days').value = String(f.days);
field<HTMLInputElement>('ng-minrev').value = String(f.minCombinedRevenue);
field<HTMLInputElement>('ng-colday').value = String(f.maxCollisionsPerDay);
field<HTMLInputElement>('ng-coltotal').value = String(f.maxCollisionsTotal);
dlg.showModal();
};
@@ -1078,6 +1266,8 @@ if (newBtn && dlg) {
*
* The answers go into the URL and the page navigates, which is the same path `?seed=` already
* took: `start()` reads them back, so there is exactly one place that turns a URL into a game.
* Deal is disabled whenever the mode radio isn't Solitaire, so this never actually runs for the
* other two — nothing here needs to branch on mode.
*/
dlg.addEventListener('close', () => {
if (dlg.returnValue !== 'deal') return;
@@ -1097,9 +1287,15 @@ if (newBtn && dlg) {
},
},
});
const victory: NewGameOptions = {
days: Math.max(1, Math.round(Number(field<HTMLInputElement>('ng-days').value)) || 5),
minCombinedRevenue: Math.max(0, Math.round(Number(field<HTMLInputElement>('ng-minrev').value)) || 0),
maxCollisionsPerDay: Math.max(0, Math.round(Number(field<HTMLInputElement>('ng-colday').value)) || 0),
maxCollisionsTotal: Math.max(0, Math.round(Number(field<HTMLInputElement>('ng-coltotal').value)) || 0),
};
clearSave();
const next = rulesToUrl(rules, seed);
const next = rulesToUrl(rules, victory, seed);
// Assigning the search string the page ALREADY has does nothing at all, which reads as a button
// that did not work — and it is the common case: deal a random seed, decide it was a bad deal,
// deal another at the same settings. Reload instead, and `start()` rolls a fresh seed.
@@ -1108,6 +1304,35 @@ if (newBtn && dlg) {
});
}
const zoomOutBtn = document.getElementById('zoomout') as HTMLButtonElement | null;
const zoomInBtn = document.getElementById('zoomin') as HTMLButtonElement | null;
const zoomLabel = document.getElementById('zoomlabel');
if (zoomOutBtn && zoomInBtn && zoomLabel) {
const paintZoom = (): void => {
zoomLabel.textContent = `${Math.round(zoom * 100)}%`;
zoomOutBtn.disabled = zoom <= ZOOM_LEVELS[0]!;
zoomInBtn.disabled = zoom >= ZOOM_LEVELS[ZOOM_LEVELS.length - 1]!;
};
const setZoom = (level: number): void => {
zoom = level;
saveSettings({ zoom });
paintZoom();
// Re-apply to whichever boards are already on the page — no full re-render needed, this is
// display-only sizing, same as `render()`'s own calls after each innerHTML assignment.
applyZoom($('division'));
applyZoom($('grid'));
};
zoomOutBtn.onclick = () => {
const i = ZOOM_LEVELS.indexOf(zoom as (typeof ZOOM_LEVELS)[number]);
if (i > 0) setZoom(ZOOM_LEVELS[i - 1]!);
};
zoomInBtn.onclick = () => {
const i = ZOOM_LEVELS.indexOf(zoom as (typeof ZOOM_LEVELS)[number]);
if (i >= 0 && i < ZOOM_LEVELS.length - 1) setZoom(ZOOM_LEVELS[i + 1]!);
};
paintZoom();
}
const soundBtn = document.getElementById('sound');
if (soundBtn) {
const paint = (): void => {
@@ -1115,6 +1340,7 @@ if (soundBtn) {
};
soundBtn.onclick = () => {
soundOn = !soundOn;
saveSettings({ soundOn });
paint();
// Confirm the change audibly — the one press where a sound is unambiguously wanted, and it
// doubles as the user gesture the browser needs before any audio may start.
+33
View File
@@ -33,6 +33,9 @@ header button:hover{border-color:#4d6fa8}
stops inviting the press. */
header button:disabled{opacity:.45;cursor:not-allowed;border-color:#2c333d}
header button:disabled:hover{border-color:#2c333d}
.zoom{display:inline-flex;align-items:center;gap:4px}
.zoom button{padding:3px 9px;line-height:1}
.zoom #zoomlabel{font-size:11px;color:var(--dim);min-width:32px;text-align:center;display:inline-block}
.build{margin-left:auto;font-size:10px;opacity:.55;white-space:nowrap}
.home{color:inherit;text-decoration:none;border-bottom:1px dotted #5f6b7a}
.home:hover{color:#5aa9e6}
@@ -221,6 +224,12 @@ ul.blocked li{padding:2px 0}
to keep the header on one line; the tooltip spells it out. -->
<span class="dim" id="houserules" title="">—</span>
<button id="sound" title="Whistle at the end of each Stage, the crossing bell at the end of each Day, and the conductor when a train is built. Currently synthesised, not recorded.">🔇 muted</button>
<!-- BOARD ZOOM. Applies to the Division map and the Office Area grid alike — both already scroll
horizontally (`#division`, `#grid`) when they run wide, so this only ever needs to resize the
rendered SVG's own pixel dimensions; the existing scrollbar keeps doing the panning. -->
<span class="zoom" title="Zoom the Division map and your Office Area. Both already scroll — this only changes their size.">
<button id="zoomout" aria-label="Zoom out">−</button><span id="zoomlabel">100%</span><button id="zoomin" aria-label="Zoom in">+</button>
</span>
<button id="undo" title="Take the last action back. The save is the seed plus the moves made, so this replays the game without the last one — as far back as you like.">Undo</button>
<button id="savefile" title="Download this game as a save file you can replay or share">Save replay</button>
<button id="newgame" title="Deal a fresh game. You choose the seed, the opening hand and what the three economies pay. Undo steps back one action at a time; this throws the whole game away, so download the replay first if you want to keep it.">New game</button>
@@ -309,6 +318,15 @@ ul.blocked li{padding:2px 0}
<form method="dialog" id="newgameform">
<h2 class="big" id="ng-title">New game</h2>
<h3>Game type</h3>
<p class="ng-note">Picking a type just sets the fields below to that type's defaults — every number stays yours to change afterward. Solitaire is the only type that can be dealt today; Competitive and Co-op need a server (coming soon).</p>
<label class="ng-radio"><input type="radio" name="ng-mode" value="solitaire" checked>
<span><b>Solitaire</b><br><span class="dim">One railroad, one player. Everything below is real today.</span></span></label>
<label class="ng-radio"><input type="radio" name="ng-mode" value="competitive">
<span><b>Competitive</b><br><span class="dim">Highest Revenue wins, unless the table misses the combined minimum — then everyone loses.</span></span></label>
<label class="ng-radio"><input type="radio" name="ng-mode" value="coop">
<span><b>Co-op</b><br><span class="dim">Everyone's Revenue counts as one table score, against the same kind of combined minimum.</span></span></label>
<h3>Seed</h3>
<p class="ng-note">The same seed and the same settings always deal the same railroad, so a game can be shared, compared or replayed. Leave it blank for a random one.</p>
<input id="ng-seed" type="text" inputmode="numeric" autocomplete="off" placeholder="blank for a random seed">
@@ -332,7 +350,22 @@ ul.blocked li{padding:2px 0}
<input id="ng-transit" type="number" min="0" max="5" step="1" value="0"></label>
<p class="ng-note">A transit pays every player, once, when a train runs off the end of the Division — the one thing nobody has to work for. It defaults to 0 for that reason.</p>
<h3>Victory conditions</h3>
<p class="ng-note">How long the game runs, and the ways it can end. 0 turns any of these off. The combined-Revenue suggestion updates for Competitive/Co-op — it assumes a 4-player table until there's a lobby to ask who's actually seated.</p>
<label class="ng-num"><span>Days</span>
<input id="ng-days" type="number" min="1" max="20" step="1" value="5"></label>
<label class="ng-num"><span>Minimum combined Revenue to avoid a loss</span>
<input id="ng-minrev" type="number" min="0" step="1" value="15"></label>
<label class="ng-num"><span>Collisions in one Day that end the game</span>
<input id="ng-colday" type="number" min="0" step="1" value="3"></label>
<label class="ng-num"><span>Collisions across the whole game that end it</span>
<input id="ng-coltotal" type="number" min="0" step="1" value="5"></label>
<label class="ng-num"><span>Allow the opponent-directed cards</span>
<input id="ng-pvp" type="checkbox"></label>
<p class="ng-note" id="ng-pvp-note">Not yet built (<code>TODO.md</code>) — this has no effect either way until then.</p>
<menu class="ng-buttons">
<span class="ng-note" id="ng-multiplayer-note" style="margin:0 auto 0 0">Multiplayer needs a server — coming soon.</span>
<button value="cancel" id="ng-cancel" type="submit" formnovalidate>Cancel</button>
<button value="deal" id="ng-deal" type="submit">Deal</button>
</menu>
+83 -9
View File
@@ -18,8 +18,9 @@
import type { Intent } from '../engine/intents.ts';
import type { Frame } from '../sim/view.ts';
import type { PlayerIndex } from '../engine/state.ts';
import type { HouseRuleOverrides } from '../engine/content.ts';
import type { Game, Menu, Save } from './game.ts';
import { applyDelta } from '../sim/frame-delta.ts';
import type { FrameDelta } from '../sim/frame-delta.ts';
import type { Game, Menu, NewGameOptions, Save } from './game.ts';
import {
actionMenu,
configWith,
@@ -115,14 +116,14 @@ export type LocalSession = Session & {
* `Game` is mutated in place by `submit`, so the wrapper keeps a mutable reference rather than
* copying — `undo` and `restore` replace the whole game, which is why `game` is a getter.
*
* It takes `rules` rather than a whole `GameConfig` because DEALING is the only thing on the far
* side of this that the page is allowed to decide. A config carries the mode, the victory condition
* and the optional rules — table settings a lobby owns — and handing main.ts a `GameConfig` to build
* meant importing the engine's own defaults into the page, which is the boundary `session.test.ts`
* guards. The seed and the house rules are the two things a player picks when they press New game.
* It takes `NewGameOptions` rather than a whole `GameConfig` because DEALING is the only thing on the
* far side of this that the page is allowed to decide. A config carries the mode and the optional
* rules — table settings a lobby owns — and handing main.ts a `GameConfig` to build meant importing
* the engine's own defaults into the page, which is the boundary `session.test.ts` guards. The seed,
* the house rules and the victory-condition dials are what a player picks when they press New game.
*/
export function createLocalSession(seed: number, rules?: HouseRuleOverrides): LocalSession {
let game: Game = rules ? newGame(seed, configWith(rules)) : newGame(seed);
export function createLocalSession(seed: number, options?: NewGameOptions): LocalSession {
let game: Game = options ? newGame(seed, configWith(options)) : newGame(seed);
const listeners = new Set<() => void>();
const changed = (): void => {
for (const fn of [...listeners]) fn();
@@ -187,3 +188,76 @@ export function createLocalSession(seed: number, rules?: HouseRuleOverrides): Lo
},
};
}
/** The push envelope `src/server/session.ts` sends over SSE — mirrored here rather than imported,
* so this file never depends on anything under `src/server/` even at the type level. */
type Push = { frame: FrameDelta; menu: Menu | null; lines: { text: string; tone: string }[] };
/**
* A session backed by a server (Phase 2). Holds no authoritative state — no deck order, no other
* seat's hand — only the last `Frame`/`Menu` a push actually told it. `capabilities` are all `false`:
* undo would have to un-see what other players already saw, a local save is meaningless when the
* server is the store, and dealing a new game is the lobby's job (Phase 4).
*
* Construction is synchronous (the `Session` interface has no async surface), but the first real
* `Frame` only exists once the SSE connection's first push arrives — `main.ts` accounts for this by
* not rendering until `subscribe`'s callback fires at least once for a session whose `capabilities`
* are all `false` (a `LocalSession` always has data the instant it is constructed; this does not).
*/
export function createRemoteSession(seat: PlayerIndex, secret: string): Session {
let frame: Frame | null = null;
let menu: Menu | null = null;
let lines: { text: string; tone: string }[] = [];
let nextSeq = 1;
const listeners = new Set<() => void>();
const changed = (): void => {
for (const fn of [...listeners]) fn();
};
const qs = `seat=${seat}&secret=${encodeURIComponent(secret)}`;
const source = new EventSource(`/api/stream?${qs}`);
source.onmessage = (ev: MessageEvent<string>) => {
const push = JSON.parse(ev.data) as Push;
frame = applyDelta(frame, push.frame);
menu = push.menu;
lines = [...lines, ...push.lines];
changed();
};
const need = (): Frame => {
if (frame === null) throw new Error('RemoteSession.view() called before the first Frame arrived');
return frame;
};
return {
view: need,
menu: () => menu ?? { options: [], direct: [], placeable: [], hand: [], makeUp: null },
seat: () => seat,
actor: () => need().actor,
overHandLimit: () => need().overHandLimit,
handPlayable: () => (menu?.hand ?? []).map((h) => h.playNow !== null),
async submit(intent: Intent): Promise<boolean> {
const seq = nextSeq++;
const res = await fetch(`/api/intent?${qs}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ seq, intent }),
});
const result = (await res.json()) as { ok: boolean; code?: string };
// The visible update arrives via the SSE push (broadcast to every seat, including this one),
// not from this response — this only reports whether the rules accepted it.
return result.ok;
},
subscribe(fn: () => void) {
listeners.add(fn);
return () => listeners.delete(fn);
},
capabilities: { undo: false, saveLocal: false, newGame: false },
lines: () => lines,
takeCues: () => [],
takeScheduled: () => null,
takeAnnouncement: () => null,
justDrawn: () => null,
};
}