v0.7.3 — a game that asks before it ends, and a results screen worth reading

Two issues off the tracker, and they are halves of one thing: the end of a game.
Neither ships on the 0.4.9 line — Jesse's call, that line may be complete and
these are not fixes people mid-playtest need.

EXTENDED PLAY (#11). The official result is settled at the original game length
and never changes: in a five-Day game extended to eight, the winner is whoever
led at the end of Day 5. Extending grants exactly one Day and the question is put
again at the end of it — solitaire the player decides alone, multiplayer it is
unanimous and one refusal ends it there. Only days-based endings offer it; a §3.4
collision breach is final, during an extended Day exactly as during the scheduled
game.

It could not be a client-side change. `check` refused every intent once `status`
left `active`; the server never loads a `finished` game back into memory; and a
save is `{ seed, config, history }` replayed through the engine, so a "continue"
the history does not record did not happen. Hence a fourth status,
`awaitingExtension`, and a `game.extend` intent. `config.days` never moves —
`extraDays` counts the borrowed Days and `official` freezes the outcome, the
standings and the statistics at the first ending.

THE RESULTS SCREEN (#16). `GAME OVER — revenueFloor` was `outcome.reason`, an
internal enum interpolated into the page at the one moment the game has the
player's whole attention. Every reason now has a sentence with the game's own
numbers in it. Around it: the result and winner, standings, the rules the game
was dealt under, a per-player breakdown, and the railroad — trains through the
Division and how many worked en route, loads made up and broken, passengers, cars
switched, trains destroyed. It shares the Day-end dialog's blocks rather than
reimplementing them, and stays reopenable so continuing does not cost you the
results.

Statistics are folded, not recorded: `state.tally` counts what the event stream
says happened, hooked at `applyIntent` and `advance` because `reduce` never sees
the phase driver's events — and those are the interesting ones. Nothing in the
rules reads it, and it rides the Frame, so multiplayer gets the same numbers as
solitaire from one implementation.

THREE BUGS FOUND IN TESTING, all of which would have shipped:

  - a saved game containing a vote could not be resumed (NO_ACTOR). A history is
    a flat Intent[] with no seat recorded; the replay derives who acted from the
    turn order, which cannot work for an intent every seat may send in any order.
    `game.extend` carries its voter, checked against the authenticated seat.
  - an all-bot game hung on the question for ever. `driveBots` loops on
    `currentActor`, null the moment the game stops, so it cannot cast a vote, and
    the bot-vote driver returned early with no humans to follow.
  - the balance harness became unbounded — `test/sim.test.ts` went from under a
    second to never finishing. `randomBot` took another Day about half the time,
    so every seeded game ran to playGame's 50,000-turn cap. Fixed in the driver,
    not in a policy, so it holds for bots not yet written.

All three have regression tests. 832 tests pass, against 793 before this change.

NOT BUILT, and a correction. #16's own comment said `trainStoodStill` "is emitted
per Stage, so a run of them is exactly the sat-on-a-siding streak". It is not:
reading advance.ts, it fires once per game and only for a train whose profile
sets `stopEarnsPoint` — the X18 Circus — with `stopPointClaimed` preventing a
second. The streak was built, rendered "1 Stage at (0,0)", and was taken out
again. There is no per-Stage "this train did not move" signal in the engine, so
"longest an engine sat on a siding" needs one first; TODO.md #36 records what it
would take, and the Circus set-up is reported instead. Badges remain the second
pass #16 asks for (TODO.md #33), and because the statistics are derived rather
than recorded, that pass can add any of them retroactively to games already
played and saved.

Extended play has not yet been played at a real table (TODO.md #35): the
multiplayer vote has only been driven through `session.intent`, never through two
browsers.

Closes #11
Closes #16

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EAgJSmeV8zrMh55Mj85ESb
This commit is contained in:
Jesse.Markowitz
2026-08-29 04:23:26 -04:00
co-authored by Claude Opus 5
parent 510e33bac7
commit 45580d8b61
30 changed files with 2264 additions and 91 deletions
+94 -10
View File
@@ -38,8 +38,9 @@ import type { GameEvent } from './events.ts';
// the legality test cannot disagree about which train is being assembled.
import { areaAtSeat, areaOf, trainNeedingCars } from './apply.ts';
import { legalActions } from './legal.ts';
import type { CrewTray, DivisionNode, GameState, PlayerIndex, RollingStock, SeatIndex, TrayId } from './state.ts';
import { coordKey, freshTurns, playerAtSeat, playerLeftOf, pooled, subdivisions, totalRevenue, turnOf } from './state.ts';
import type { CrewTray, DivisionNode, GameState, Outcome, PlayerIndex, RollingStock, SeatIndex, TrayId } from './state.ts';
import { cloneTally, coordKey, freshTurns, isExtendable, playerAtSeat, playerLeftOf, pooled, subdivisions, totalRevenue, turnOf } from './state.ts';
import { tallyEvent } from './tally.ts';
export type AdvanceResult = {
events: GameEvent[];
@@ -71,10 +72,58 @@ const step = (d: Direction): number => (d === 'east' ? 1 : -1);
// advance
// ---------------------------------------------------------------------------
/**
* The phase driver, plus the two things that have to happen around EVERY batch of events it
* produces. `advanceInner` below is the driver itself, unchanged.
*
* ORDER IS THE WHOLE POINT of this wrapper, and it is the one subtle thing in Gitea#16.
* `checkVictory` runs deep inside the driver, so if the official result froze a copy of the Tally
* from in there it would freeze it BEFORE this batch's events had been counted — and the batch that
* ends a game is exactly the one carrying the last Day's work. So the Tally is folded first and the
* result frozen second, both out here where the whole batch is in hand.
*
* Safe because both endings `return` the moment they fire: no scoring event is emitted after a game
* has ended within a single batch, so "everything in this batch" and "everything up to the ending"
* are the same set of events. `test/tally.test.ts` pins that.
*/
export function advance(s: GameState): AdvanceResult {
const r = advanceInner(s);
for (const e of r.events) tallyEvent(s, e);
freezeOfficial(s);
return r;
}
/**
* THE OFFICIAL RESULT, written once (Gitea#11).
*
* "The winner is based upon the original game length" — so the first ending is the real one and
* every later evaluation is informational. Idempotent by construction: it does nothing once
* `official` is set, which is what stops an extended Day, or a §3.4 breach during one, from
* rewriting a recorded win.
*/
function freezeOfficial(s: GameState): void {
if (s.official !== null || s.outcome === null) return;
s.official = {
day: s.config.days,
outcome: { ...s.outcome },
revenues: s.players.map((p) => p.revenue),
collisionsTotal: s.collisionsTotal,
tally: cloneTally(s.tally),
};
}
function advanceInner(s: GameState): AdvanceResult {
const events: GameEvent[] = [];
if (s.status === 'finished') return { events, needsInput: false };
/**
* §3.3 (Gitea#11) — the timetable has run out and the table is being asked whether to play one
* more Day. Nothing runs itself while that question is open, so this is `needsInput` rather than
* an ending: `pump` stops here, the server keeps the game in memory, and the only intent the
* rules will take is `game.extend`.
*/
if (s.status === 'awaitingExtension') return { events, needsInput: true };
// The Superintendent's clearance ruling interrupts the Mainline Phase (§8.1).
if (s.clock.pendingDecision !== null) return { events, needsInput: true };
@@ -1313,6 +1362,14 @@ function shiftChange(s: GameState, events: GameEvent[]): AdvanceResult {
s.config.maxCollisionsTotal > 0 && s.collisionsTotal >= s.config.maxCollisionsTotal;
if (perDayBreach || totalBreach) {
s.status = 'finished';
/**
* NOT EXTENDABLE, AND IT DOES NOT REWRITE A RECORDED RESULT (Gitea#11).
*
* A breach during an EXTENDED Day ends play at once, exactly as it would during the regular
* game — but by then the official result already exists, and a railroad declared unsafe on
* Day 9 does not retract who won on Day 5. `freezeOfficial` is what keeps that true: it
* writes only when `official` is still null, so assigning `outcome` here is safe.
*/
s.outcome = { result: 'loss', winner: null, reason: 'collisionFloor' };
return { events, needsInput: false };
}
@@ -1356,28 +1413,55 @@ function rotateSeats(s: GameState, events: GameEvent[]): void {
function checkVictory(s: GameState, _events: GameEvent[]): boolean {
const daysElapsed = s.clock.day - 1;
if (daysElapsed < s.config.days) return false;
/**
* `extraDays` is Gitea#11. `config.days` is never touched by an extension — it is what the
* OFFICIAL result is decided at — so the Day the timetable currently runs to is the sum of the
* two. On the first ending they are equal, which is why `freezeOfficial` can record `config.days`
* as the official Day without asking anything further.
*/
if (daysElapsed < s.config.days + s.extraDays) return false;
s.status = 'finished';
s.outcome = decideOutcome(s);
/**
* §3.3, EXTENDED PLAY — an ending the table may play past PAUSES rather than finishing.
*
* `freezeOfficial` (the `advance` wrapper) records the first of these as the official result, so
* by the time a second one is reached the winner is already settled and everything here is
* informational. The votes are cleared each time because the question is asked again at the end
* of every extended Day: agreeing once does not agree to the rest of the game.
*/
if (isExtendable(s.outcome.reason)) {
s.status = 'awaitingExtension';
s.extensionVotes = s.players.map(() => null);
} else {
s.status = 'finished';
}
return true;
}
/**
* WHO WON, on the evidence as it stands right now.
*
* Split out of `checkVictory` for Gitea#11: it is asked once per ending, and an extended game has
* more than one. Unchanged in substance — the revenue floor, then co-op's shared achievement, then
* the highest Revenue — it simply no longer writes to the state it is reasoning about.
*/
function decideOutcome(s: GameState): Outcome {
const combined = totalRevenue(s);
if (s.config.minCombinedRevenue > 0 && combined < s.config.minCombinedRevenue) {
s.outcome = { result: 'loss', winner: null, reason: 'revenueFloor' };
return true;
return { result: 'loss', winner: null, reason: 'revenueFloor' };
}
if (s.config.mode === 'coop') {
s.outcome = { result: 'win', winner: null, reason: 'daysElapsed' };
return true;
return { result: 'win', winner: null, reason: 'daysElapsed' };
}
const best = Math.max(...s.players.map((p) => p.revenue));
s.outcome = {
return {
result: 'win',
winner: s.players.findIndex((p) => p.revenue === best),
reason: 'daysElapsed',
};
return true;
}
// ---------------------------------------------------------------------------