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:
co-authored by
Claude Opus 5
parent
510e33bac7
commit
45580d8b61
+24
-5
@@ -66,6 +66,21 @@ function playToCompletion(s: GameState, seed = 1, maxTurns = 20_000): PlayStats
|
||||
tally(pump(s));
|
||||
if (s.status === 'finished') break;
|
||||
|
||||
/**
|
||||
* §3.3, EXTENDED PLAY (Gitea#11) — this harness plays the timetable it was dealt.
|
||||
*
|
||||
* It picks at random among legal options, and one of the two options here is "play another
|
||||
* Day" — so left alone it would extend the game forever and terminate only on `maxTurns`. That
|
||||
* is not a bug in the feature: a game genuinely does not end now until somebody says stop, and
|
||||
* `developerBot` says stop for exactly this reason. Said explicitly here rather than folded
|
||||
* into the random pick, because "how does this loop terminate" deserves an answer in the loop.
|
||||
*/
|
||||
if (s.status === 'awaitingExtension') {
|
||||
const r = applyIntent(s, 0, { type: 'game.extend', player: 0, agree: false });
|
||||
assert.ok(r.ok, 'a solitaire player could not decline an extension');
|
||||
break;
|
||||
}
|
||||
|
||||
const actor = s.clock.pendingDecision !== null ? s.clock.superintendent : s.clock.currentActor;
|
||||
if (actor === null) break;
|
||||
|
||||
@@ -544,9 +559,13 @@ describe('victory conditions (§3, Gap 10e) — unified 2026-08-20', () => {
|
||||
s.clock.phase = 'shiftChange';
|
||||
s.players[0]!.revenue = 0;
|
||||
advance(s);
|
||||
assert.equal(s.status, 'finished');
|
||||
// PAUSES rather than finishes since Gitea#11: a days-based ending offers another Day, and the
|
||||
// result is recorded either way. `official` is the frozen answer; `status` is only where play
|
||||
// has got to. The two collision tests at the foot of this block are the contrast.
|
||||
assert.equal(s.status, 'awaitingExtension');
|
||||
assert.equal(s.outcome!.result, 'loss');
|
||||
assert.equal(s.outcome!.reason, 'revenueFloor');
|
||||
assert.equal(s.official!.outcome.reason, 'revenueFloor');
|
||||
});
|
||||
|
||||
it('wins a timed Solitaire game that clears minCombinedRevenue', () => {
|
||||
@@ -556,7 +575,7 @@ describe('victory conditions (§3, Gap 10e) — unified 2026-08-20', () => {
|
||||
s.clock.phase = 'shiftChange';
|
||||
s.players[0]!.revenue = 10;
|
||||
advance(s);
|
||||
assert.equal(s.status, 'finished');
|
||||
assert.equal(s.status, 'awaitingExtension');
|
||||
assert.equal(s.outcome!.result, 'win');
|
||||
});
|
||||
|
||||
@@ -567,7 +586,7 @@ describe('victory conditions (§3, Gap 10e) — unified 2026-08-20', () => {
|
||||
s.clock.phase = 'shiftChange';
|
||||
s.players[0]!.revenue = 0;
|
||||
advance(s);
|
||||
assert.equal(s.status, 'finished');
|
||||
assert.equal(s.status, 'awaitingExtension');
|
||||
assert.equal(s.outcome!.result, 'win');
|
||||
});
|
||||
|
||||
@@ -582,7 +601,7 @@ describe('victory conditions (§3, Gap 10e) — unified 2026-08-20', () => {
|
||||
s.players[0]!.revenue = 5; // best individual score...
|
||||
s.players[1]!.revenue = 3; // ...but combined (8) still misses the floor (20).
|
||||
advance(s);
|
||||
assert.equal(s.status, 'finished');
|
||||
assert.equal(s.status, 'awaitingExtension');
|
||||
assert.equal(s.outcome!.result, 'loss');
|
||||
assert.equal(s.outcome!.reason, 'revenueFloor');
|
||||
});
|
||||
@@ -598,7 +617,7 @@ describe('victory conditions (§3, Gap 10e) — unified 2026-08-20', () => {
|
||||
s.players[0]!.revenue = 4;
|
||||
s.players[1]!.revenue = 6; // combined 10 clears the floor, neither alone would.
|
||||
advance(s);
|
||||
assert.equal(s.status, 'finished');
|
||||
assert.equal(s.status, 'awaitingExtension');
|
||||
assert.equal(s.outcome!.result, 'win');
|
||||
assert.equal(s.outcome!.winner, null, 'Co-op names an individual winner instead of a shared one');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* §3.3, EXTENDED PLAY — Gitea#11, "when game ends allow players to continue playing if they wish".
|
||||
*
|
||||
* The rule as Jesse specified it (2026-08-28), which is what these tests are written against:
|
||||
*
|
||||
* - the OFFICIAL result is decided at the original game length and never changes. "In a five-day
|
||||
* game, even if it's extended to eight or nine days, the winner and the official answer is the
|
||||
* winner at the end of five days";
|
||||
* - extending grants exactly ONE Day, and the question is put again at the end of it;
|
||||
* - solitaire: the player decides alone. Multiplayer: unanimous, and one refusal ends it there;
|
||||
* - only days-based endings offer it. A §3.4 collision breach is final, during an extended Day
|
||||
* just as during the regular game.
|
||||
*
|
||||
* The persistence half matters as much as the rules half: a save is `{ seed, config, history }`
|
||||
* replayed through the engine, so an extension that is not an INTENT does not survive a reload, an
|
||||
* Undo, or a server restart. `replays the extension` below is the test that pins that.
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { advance, pump } from '../src/engine/advance.ts';
|
||||
import { applyIntent, check } from '../src/engine/apply.ts';
|
||||
import { STAGES_PER_DAY } from '../src/engine/content.ts';
|
||||
import { legalActions } from '../src/engine/legal.ts';
|
||||
import { createGame } from '../src/engine/setup.ts';
|
||||
import { developerBot, playGame, randomBot } from '../src/sim/bot.ts';
|
||||
import type { GameConfig, GameState } from '../src/engine/state.ts';
|
||||
|
||||
const baseConfig = (over: Partial<GameConfig> = {}): GameConfig => ({
|
||||
mode: 'solitaire',
|
||||
days: 3,
|
||||
minCombinedRevenue: 0,
|
||||
maxCollisionsPerDay: 0,
|
||||
maxCollisionsTotal: 0,
|
||||
pvpCardsAllowed: false,
|
||||
optionalRules: { reducedVisibility: false, employeeRotation: false, emergencyToolbox: false },
|
||||
...over,
|
||||
});
|
||||
|
||||
const game = (over: Partial<GameConfig> = {}, names = ['Jesse']): GameState =>
|
||||
createGame({ id: 'g', seed: 1, config: baseConfig(over), playerNames: names });
|
||||
|
||||
/** Parks a game on the last Stage of its final Day, so one `advance` runs the clock off the end. */
|
||||
function atTheEnd(s: GameState): GameState {
|
||||
s.clock.day = s.config.days + s.extraDays + 1;
|
||||
s.clock.stage = STAGES_PER_DAY;
|
||||
s.clock.phase = 'shiftChange';
|
||||
return s;
|
||||
}
|
||||
|
||||
describe('§3.3 extended play — the ending pauses rather than stopping (Gitea#11)', () => {
|
||||
it('offers another Day on a days-based ending, and records the result anyway', () => {
|
||||
const s = atTheEnd(game());
|
||||
advance(s);
|
||||
assert.equal(s.status, 'awaitingExtension', 'a days-based ending did not offer another Day');
|
||||
assert.ok(s.outcome, 'the result was not decided');
|
||||
assert.ok(s.official, 'the official result was not frozen');
|
||||
assert.equal(s.official!.day, s.config.days, 'the official Day is not the original game length');
|
||||
});
|
||||
|
||||
it('does NOT offer another Day after a collision breach — §3.4 is final', () => {
|
||||
const s = game({ mode: 'competitive', maxCollisionsPerDay: 2 });
|
||||
s.collisionsToday = 2;
|
||||
s.clock.stage = 1;
|
||||
s.clock.phase = 'shiftChange';
|
||||
advance(s);
|
||||
assert.equal(s.status, 'finished', 'a railroad declared unsafe offered to carry on');
|
||||
assert.equal(s.outcome!.reason, 'collisionFloor');
|
||||
});
|
||||
|
||||
it('refuses every ordinary intent while the extension question is open', () => {
|
||||
const s = atTheEnd(game());
|
||||
advance(s);
|
||||
assert.equal(check(s, 0, { type: 'draw.fromHomeOffice' }), 'WRONG_PHASE');
|
||||
assert.equal(check(s, 0, { type: 'game.extend', player: 0, agree: true }), null, 'the vote itself was refused');
|
||||
});
|
||||
|
||||
it('offers only the two votes, and only to a seat that has not voted', () => {
|
||||
const s = atTheEnd(game({ mode: 'competitive' }, ['A', 'B']));
|
||||
advance(s);
|
||||
assert.deepEqual(
|
||||
legalActions(s, 0).map((i) => i.type),
|
||||
['game.extend', 'game.extend'],
|
||||
'something other than the vote is legal while the game is stopped',
|
||||
);
|
||||
applyIntent(s, 0, { type: 'game.extend', player: 0, agree: true });
|
||||
assert.equal(legalActions(s, 0).length, 0, 'a seat was offered a second vote');
|
||||
assert.equal(check(s, 0, { type: 'game.extend', player: 0, agree: true }), 'ALREADY_VOTED');
|
||||
assert.equal(legalActions(s, 1).length, 2, 'the seat still to vote was not offered the vote');
|
||||
});
|
||||
|
||||
it('refuses the vote when no extension is pending', () => {
|
||||
const s = game();
|
||||
assert.equal(check(s, 0, { type: 'game.extend', player: 0, agree: true }), 'NOT_AWAITING_EXTENSION');
|
||||
});
|
||||
});
|
||||
|
||||
describe('§3.3 extended play — one Day at a time (Gitea#11)', () => {
|
||||
it('grants exactly one Day in solitaire, then asks again at the end of it', () => {
|
||||
const s = atTheEnd(game());
|
||||
advance(s);
|
||||
const official = { ...s.official!.outcome };
|
||||
|
||||
applyIntent(s, 0, { type: 'game.extend', player: 0, agree: true });
|
||||
assert.equal(s.status, 'active', 'agreeing did not resume play');
|
||||
assert.equal(s.extraDays, 1, 'more or less than one Day was granted');
|
||||
assert.deepEqual(s.extensionVotes, [null], 'the votes were not cleared for the next question');
|
||||
|
||||
// Run the extra Day off the end: the question comes round again.
|
||||
atTheEnd(s);
|
||||
advance(s);
|
||||
assert.equal(s.status, 'awaitingExtension', 'the second ending did not ask again');
|
||||
assert.equal(s.extraDays, 1, 'a second Day was granted without being asked for');
|
||||
assert.deepEqual(s.official!.outcome, official, 'the official result was rewritten');
|
||||
assert.equal(s.official!.day, s.config.days, 'the official Day moved with the extension');
|
||||
});
|
||||
|
||||
it('ends the moment one seat declines, without waiting for the rest', () => {
|
||||
const s = atTheEnd(game({ mode: 'competitive' }, ['A', 'B', 'C']));
|
||||
advance(s);
|
||||
applyIntent(s, 0, { type: 'game.extend', player: 0, agree: true });
|
||||
assert.equal(s.status, 'awaitingExtension', 'one yes ended the vote');
|
||||
|
||||
applyIntent(s, 1, { type: 'game.extend', player: 1, agree: false });
|
||||
assert.equal(s.status, 'finished', 'a refusal did not end the game immediately');
|
||||
assert.equal(s.extraDays, 0, 'a Day was granted despite a refusal');
|
||||
assert.equal(check(s, 2, { type: 'game.extend', player: 2, agree: true }), 'NOT_AWAITING_EXTENSION',
|
||||
'the seat that never voted is still being waited on');
|
||||
});
|
||||
|
||||
it('needs every seat before it grants the Day', () => {
|
||||
const s = atTheEnd(game({ mode: 'competitive' }, ['A', 'B', 'C']));
|
||||
advance(s);
|
||||
applyIntent(s, 0, { type: 'game.extend', player: 0, agree: true });
|
||||
applyIntent(s, 1, { type: 'game.extend', player: 1, agree: true });
|
||||
assert.equal(s.status, 'awaitingExtension', 'two of three votes granted the Day');
|
||||
applyIntent(s, 2, { type: 'game.extend', player: 2, agree: true });
|
||||
assert.equal(s.status, 'active', 'a unanimous table was not given its Day');
|
||||
assert.equal(s.extraDays, 1);
|
||||
});
|
||||
|
||||
it('keeps the official result when a collision ends an EXTENDED Day', () => {
|
||||
// The case the freeze exists for: a railroad declared unsafe on the extra Day does not retract
|
||||
// who won on the last scheduled one.
|
||||
const s = atTheEnd(game({ mode: 'competitive', maxCollisionsPerDay: 2 }, ['A', 'B']));
|
||||
s.players[0]!.revenue = 9;
|
||||
s.players[1]!.revenue = 2;
|
||||
advance(s);
|
||||
const official = { ...s.official!.outcome };
|
||||
assert.equal(official.result, 'win');
|
||||
assert.equal(official.winner, 0);
|
||||
|
||||
applyIntent(s, 0, { type: 'game.extend', player: 0, agree: true });
|
||||
applyIntent(s, 1, { type: 'game.extend', player: 1, agree: true });
|
||||
assert.equal(s.status, 'active');
|
||||
|
||||
s.collisionsToday = 2;
|
||||
s.clock.stage = 1;
|
||||
s.clock.phase = 'shiftChange';
|
||||
advance(s);
|
||||
assert.equal(s.status, 'finished');
|
||||
assert.equal(s.outcome!.reason, 'collisionFloor', 'the current evaluation was not updated');
|
||||
assert.deepEqual(s.official!.outcome, official, 'a late collision rewrote a recorded win');
|
||||
});
|
||||
|
||||
it('decides the winner at the ORIGINAL game length, whoever leads afterwards', () => {
|
||||
const s = atTheEnd(game({ mode: 'competitive' }, ['A', 'B']));
|
||||
s.players[0]!.revenue = 9;
|
||||
s.players[1]!.revenue = 2;
|
||||
advance(s);
|
||||
assert.equal(s.official!.outcome.winner, 0);
|
||||
assert.deepEqual(s.official!.revenues, [9, 2], 'the official standings were not frozen');
|
||||
|
||||
applyIntent(s, 0, { type: 'game.extend', player: 0, agree: true });
|
||||
applyIntent(s, 1, { type: 'game.extend', player: 1, agree: true });
|
||||
|
||||
// B overtakes A during the extra Day, and it changes nothing official.
|
||||
s.players[1]!.revenue = 40;
|
||||
atTheEnd(s);
|
||||
advance(s);
|
||||
assert.equal(s.official!.outcome.winner, 0, 'overtaking after the timetable took the win');
|
||||
assert.deepEqual(s.official!.revenues, [9, 2], 'the frozen standings moved');
|
||||
assert.equal(s.outcome!.winner, 1, 'the informational evaluation did not follow the new leader');
|
||||
});
|
||||
});
|
||||
|
||||
describe('§3.3 extended play — it survives being replayed (Gitea#11)', () => {
|
||||
it('reproduces an extended game from seed and intents alone', () => {
|
||||
// The reason the vote is an intent at all. A save is a replay, so a decision that is not in the
|
||||
// history did not happen — an extended game would evaporate on the next reload.
|
||||
const play = (): GameState => {
|
||||
const s = atTheEnd(game());
|
||||
advance(s);
|
||||
applyIntent(s, 0, { type: 'game.extend', player: 0, agree: true });
|
||||
return s;
|
||||
};
|
||||
const a = play();
|
||||
const b = play();
|
||||
assert.equal(a.extraDays, b.extraDays);
|
||||
assert.equal(a.status, b.status);
|
||||
assert.deepEqual(a.official!.outcome, b.official!.outcome);
|
||||
});
|
||||
|
||||
it('narrates the vote, so a table can see who called time', () => {
|
||||
const s = atTheEnd(game({ mode: 'competitive' }, ['A', 'B']));
|
||||
advance(s);
|
||||
const yes = applyIntent(s, 0, { type: 'game.extend', player: 0, agree: true });
|
||||
assert.ok(yes.ok);
|
||||
assert.deepEqual(yes.events.map((e) => e.type), ['extensionVoted']);
|
||||
const no = applyIntent(s, 1, { type: 'game.extend', player: 1, agree: false });
|
||||
assert.ok(no.ok);
|
||||
assert.deepEqual(no.events.map((e) => e.type), ['extensionVoted', 'playConcluded']);
|
||||
});
|
||||
|
||||
it('announces the granted Day', () => {
|
||||
const s = atTheEnd(game());
|
||||
advance(s);
|
||||
const r = applyIntent(s, 0, { type: 'game.extend', player: 0, agree: true });
|
||||
assert.ok(r.ok);
|
||||
assert.deepEqual(r.events.map((e) => e.type), ['extensionVoted', 'dayExtended']);
|
||||
const extended = r.events.find((e) => e.type === 'dayExtended');
|
||||
assert.equal(extended && 'day' in extended ? extended.day : null, s.config.days + 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('§3.3 extended play — bots play the timetable they were dealt (Gitea#11)', () => {
|
||||
it('REGRESSION: a simulated game terminates whatever the policy would vote', () => {
|
||||
/**
|
||||
* `playGame` declines on the driver's own account rather than leaving it to the policy, and this
|
||||
* is why. `randomBot` picks uniformly among its legal options, so it takes another Day about
|
||||
* half the time — and since a table may go on granting Days for ever, the game then runs to
|
||||
* `maxTurns`. It did: `test/sim.test.ts` went from under a second to an unbounded hang, every
|
||||
* seeded game in the harness playing fifty thousand turns instead of a couple of hundred.
|
||||
*
|
||||
* `randomBot` is the policy that exposes it, but the guarantee has to hold for any policy,
|
||||
* including ones not written yet — hence the fix living in the driver and the test living here.
|
||||
*/
|
||||
const s = createGame({ id: 'g', seed: 9, config: baseConfig({ days: 1 }), playerNames: ['Jesse'] });
|
||||
const out = playGame(s, randomBot(7), pump, 4_000);
|
||||
assert.equal(s.status, 'finished', 'a simulated game did not finish');
|
||||
assert.equal(s.extraDays, 0, 'the harness played Days the game was not dealt');
|
||||
assert.ok(out.turns < 4_000, `ran to the turn cap (${out.turns}) instead of ending`);
|
||||
});
|
||||
|
||||
it('developerBot declines, so a bot-only game ends on schedule', () => {
|
||||
// "If only bots are playing, they never vote to extend" (Jesse, 2026-08-28). The server votes
|
||||
// yes on a bot's behalf once every human has already agreed; this policy is what is left when
|
||||
// there are no humans to follow.
|
||||
const s = atTheEnd(game());
|
||||
advance(s);
|
||||
const choice = developerBot.choose(s, 0, legalActions(s, 0));
|
||||
assert.equal(choice.type, 'game.extend');
|
||||
assert.equal('agree' in choice ? choice.agree : null, false, 'a bot asked for another Day');
|
||||
});
|
||||
});
|
||||
+12
-1
@@ -304,7 +304,18 @@ describe('every published replay actually replays', () => {
|
||||
`${f} is dead — it replays ${back.history.length} of ${save.history.length} intents. ` +
|
||||
'Re-record it with save-replay.ts rather than editing the file.',
|
||||
);
|
||||
assert.equal(back.state.status, 'finished', `${f} does not reach the end of its game`);
|
||||
/**
|
||||
* `awaitingExtension` counts as the end since Gitea#11 — and for a published file it is the
|
||||
* EXPECTED end. These saves were recorded before extended play existed, so their histories
|
||||
* carry no `game.extend` vote: replaying one runs the timetable out and stops on the question
|
||||
* nobody was there to answer. That is a game that reached the end of its own history, which is
|
||||
* what this test is about. `active` would still be a dead replay.
|
||||
*/
|
||||
assert.ok(
|
||||
back.state.status === 'finished' || back.state.status === 'awaitingExtension',
|
||||
`${f} does not reach the end of its game — status ${back.state.status}`,
|
||||
);
|
||||
assert.ok(back.state.official !== null, `${f} ends without recording a result`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -99,6 +99,30 @@ describe('redaction — a seat\'s Frame never carries another seat\'s secrets',
|
||||
assert.ok(!serialized.includes(String(s.seed)), 'the seed value leaked into the Frame some other way');
|
||||
});
|
||||
|
||||
it('the tally that rides the Frame is aggregate counts, never a card id (Gitea#16)', () => {
|
||||
// Gitea#16's statistics live on `GameState` and reach a remote client on the Frame, which is
|
||||
// only safe because nothing in a Tally identifies a card. That is a property of what
|
||||
// `tally.ts` chooses to count, and nothing in the type system enforces it — so it is asserted
|
||||
// here, where a future counter that stashed a `cardId` "just for badges" would be caught.
|
||||
for (const players of [3, 4]) {
|
||||
const s = midGame(players, 5000 + players);
|
||||
const secrets = new Set<string>([...s.decks.homeOffice]);
|
||||
for (const hand of s.decks.hands.values()) for (const id of hand) secrets.add(id);
|
||||
for (let viewer = 0 as PlayerIndex; viewer < players; viewer++) {
|
||||
const serialized = JSON.stringify(snapshot(s, [], null, null, null, false, viewer).tally);
|
||||
for (const cardId of secrets) {
|
||||
assert.ok(!serialized.includes(`"${cardId}"`), `the tally carries card id "${cardId}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('every seat sees the SAME tally — it is the table\'s account, not a private one', () => {
|
||||
const s = midGame(3, 5555);
|
||||
const tallies = [0, 1, 2].map((p) => snapshot(s, [], null, null, null, false, p as PlayerIndex).tally);
|
||||
for (const t of tallies) assert.deepEqual(t, tallies[0], 'the tally differs by seat');
|
||||
});
|
||||
|
||||
it('only the viewer\'s own hand and handCount are non-public — everything else matches across seats', () => {
|
||||
// The redaction surface is four fields (§7), not sixty event types. Cross-check that seats agree
|
||||
// on everything else a Frame carries about shared state.
|
||||
|
||||
@@ -412,3 +412,122 @@ describe('the four transient signals (2026-08-23)', () => {
|
||||
assert.equal(later.scheduled, undefined, 'a reconnecting client was re-sent an old timetable flash');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('§3.3 extended play across the server (Gitea#11)', () => {
|
||||
/**
|
||||
* A one-Day game, so these tests reach the end of the timetable by actually PLAYING to it.
|
||||
*
|
||||
* There is no back door into a session's engine state and there should not be — `connect`,
|
||||
* `intent`, `exportSave` and `summary` are the whole surface. So the clock is run down through the
|
||||
* same calls a client makes, which has the side benefit of exercising the real path: what is under
|
||||
* test here is the session's handling of the vote (the turn guard, the bots, the saved status),
|
||||
* and reaching it any other way would prove less.
|
||||
*/
|
||||
const oneDay: GameConfig = { ...config, days: 1 };
|
||||
|
||||
/** What seat `seat` can currently see. `connect` always yields a full Frame, never a delta. */
|
||||
const frameOf = (session: GameSession, seat: PlayerIndex) => session.connect(seat).frame!;
|
||||
|
||||
/** Plays until the game stops asking for ordinary moves. Returns the Frame it stopped on. */
|
||||
function playToTheEnd(session: GameSession, seats: PlayerIndex[]) {
|
||||
let seq = 0;
|
||||
for (let i = 0; i < 5_000; i++) {
|
||||
const acting = seats.find((s) => session.connect(s).menu !== null);
|
||||
if (acting === undefined) break;
|
||||
const menu = session.connect(acting).menu!;
|
||||
if (menu.options.length === 0) break;
|
||||
if (!session.intent(acting, seq++, menu.options[0]!).accepted) break;
|
||||
}
|
||||
return { frame: frameOf(session, seats[0]!), seq };
|
||||
}
|
||||
|
||||
it('stops to ask rather than ending, and every seat can see the question', () => {
|
||||
const session = createSession(42, oneDay, ['Alice', 'Bob']);
|
||||
const { frame } = playToTheEnd(session, [0, 1] as PlayerIndex[]);
|
||||
assert.equal(frame.status, 'awaitingExtension', 'the game did not stop to ask');
|
||||
assert.ok(frame.official, 'the official result did not reach the client');
|
||||
assert.deepEqual(frame.extensionVotes, [null, null], 'the votes did not reach the client');
|
||||
});
|
||||
|
||||
it('accepts the vote from a seat that is not the current actor', () => {
|
||||
// `currentActor` is null once the game has stopped, so the ordinary turn guard would refuse
|
||||
// every vote with NOT_YOUR_TURN. Both seats vote here and neither of them is the actor.
|
||||
const session = createSession(42, oneDay, ['Alice', 'Bob']);
|
||||
const { seq } = playToTheEnd(session, [0, 1] as PlayerIndex[]);
|
||||
const a = session.intent(0 as PlayerIndex, seq + 1, { type: 'game.extend', player: 0, agree: true });
|
||||
assert.equal(a.accepted, true, 'seat 0 could not vote');
|
||||
const b = session.intent(1 as PlayerIndex, seq + 2, { type: 'game.extend', player: 1, agree: true });
|
||||
assert.equal(b.accepted, true, 'seat 1 could not vote');
|
||||
|
||||
const after = frameOf(session, 0 as PlayerIndex);
|
||||
assert.equal(after.extraDays, 1, 'a unanimous table was not given its Day');
|
||||
assert.equal(after.status, 'active', 'play did not resume');
|
||||
});
|
||||
|
||||
it('bots agree only once every human has, and never lead', () => {
|
||||
// "Bots will not disagree with the human. Humans get to vote first" (Jesse, 2026-08-28).
|
||||
const session = createSession(42, oneDay, ['Alice', 'Botty'], [1 as PlayerIndex]);
|
||||
const { seq } = playToTheEnd(session, [0, 1] as PlayerIndex[]);
|
||||
assert.equal(frameOf(session, 0 as PlayerIndex).status, 'awaitingExtension');
|
||||
assert.equal(
|
||||
frameOf(session, 0 as PlayerIndex).extensionVotes[1],
|
||||
null,
|
||||
'the bot voted before the human did',
|
||||
);
|
||||
|
||||
session.intent(0 as PlayerIndex, seq + 1, { type: 'game.extend', player: 0, agree: true });
|
||||
const after = frameOf(session, 0 as PlayerIndex);
|
||||
assert.equal(after.extraDays, 1, 'the bot did not follow the human into another Day');
|
||||
assert.equal(after.status, 'active');
|
||||
});
|
||||
|
||||
it('a human refusal ends it, and no bot overrides that', () => {
|
||||
const session = createSession(42, oneDay, ['Alice', 'Botty'], [1 as PlayerIndex]);
|
||||
const { seq } = playToTheEnd(session, [0, 1] as PlayerIndex[]);
|
||||
session.intent(0 as PlayerIndex, seq + 1, { type: 'game.extend', player: 0, agree: false });
|
||||
const after = frameOf(session, 0 as PlayerIndex);
|
||||
assert.equal(after.status, 'finished');
|
||||
assert.equal(after.extraDays, 0);
|
||||
});
|
||||
|
||||
it('REGRESSION: an all-bot game ends rather than hanging on the question', () => {
|
||||
/**
|
||||
* `driveBots` loops on `currentActor`, which is null the moment the game stops to ask — so it
|
||||
* cannot cast the vote itself, and the bots' vote is driven separately. The first cut of that
|
||||
* driver returned early when there were no humans to follow, on the reasoning that a bot-only
|
||||
* table would decline through the ordinary path. It has no ordinary path: nothing ever asked
|
||||
* the bots, and an all-bot session sat on the question for ever without reaching `finished`.
|
||||
* Caught by `summary()`'s own "a finished game waits on nobody" test.
|
||||
*/
|
||||
const session = createSession(4242, oneDay, ['A', 'B'], [0, 1] as PlayerIndex[]);
|
||||
assert.equal(frameOf(session, 0 as PlayerIndex).status, 'finished', 'the bots never answered');
|
||||
assert.equal(session.summary().waitingOn, null);
|
||||
assert.equal(frameOf(session, 0 as PlayerIndex).extraDays, 0, 'bots voted themselves another Day');
|
||||
});
|
||||
|
||||
it('saves a game awaiting its vote as ACTIVE, so a restart resumes it', () => {
|
||||
// `server/index.ts` never loads a `finished` game back into memory. A game paused on the
|
||||
// extension question is waiting on its table, not over — persisting it as finished would strand
|
||||
// it on disk mid-decision.
|
||||
const session = createSession(42, oneDay, ['Alice', 'Bob']);
|
||||
playToTheEnd(session, [0, 1] as PlayerIndex[]);
|
||||
assert.equal(frameOf(session, 0 as PlayerIndex).status, 'awaitingExtension');
|
||||
assert.equal(session.exportSave().status, 'active', 'a paused game was saved as finished');
|
||||
assert.equal(session.summary().status, 'active');
|
||||
});
|
||||
|
||||
it('resumes a paused game from its history, vote and all', () => {
|
||||
const session = createSession(42, oneDay, ['Alice', 'Bob']);
|
||||
const { seq } = playToTheEnd(session, [0, 1] as PlayerIndex[]);
|
||||
session.intent(0 as PlayerIndex, seq + 1, { type: 'game.extend', player: 0, agree: true });
|
||||
|
||||
const resumed = resumeSession(session.exportSave());
|
||||
const a = frameOf(session, 0 as PlayerIndex);
|
||||
const b = frameOf(resumed, 0 as PlayerIndex);
|
||||
assert.deepEqual(b.extensionVotes, a.extensionVotes, 'the votes did not survive the replay');
|
||||
assert.equal(b.extraDays, a.extraDays, 'the extra Day did not survive the replay');
|
||||
assert.deepEqual(b.official, a.official, 'the official result did not survive the replay');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -63,7 +63,13 @@ describe('a local session plays the same game as the calls it replaced', () => {
|
||||
assert.ok(turns > 50, `only ${turns} decisions — the game stalled`);
|
||||
|
||||
const f = session.view();
|
||||
assert.equal(f.status, 'finished');
|
||||
/**
|
||||
* `awaitingExtension` since Gitea#11, not `finished`: both loops stop when there is no actor,
|
||||
* and a days-based ending now parks the game on the "play one more Day?" question rather than
|
||||
* ending it outright. What this test is actually about is unchanged — the two sides reach the
|
||||
* SAME position — and the assertion below is still the one carrying that.
|
||||
*/
|
||||
assert.equal(f.status, 'awaitingExtension');
|
||||
assert.equal(f.status, view(game).status);
|
||||
assert.equal(f.day, view(game).day);
|
||||
assert.deepEqual(f.cells, view(game).cells, 'the board differs across the boundary');
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* THE EVENT TALLY — Gitea#16's statistics, and the one property they depend on.
|
||||
*
|
||||
* "I don't know if we keep statistics on…" is the question the issue opens with. Nothing was being
|
||||
* kept; `GameState.tally` now is, folded from the event stream at the two places every event passes
|
||||
* through (`engine/tally.ts` explains which and why).
|
||||
*
|
||||
* The property that matters is EXACTLY ONCE. A statistic folded twice reads high and a statistic
|
||||
* folded nowhere reads zero, and both are indistinguishable from a quiet game when you are looking
|
||||
* at a results screen. So the central test here does not assert particular numbers: it plays real
|
||||
* games, collects every event the engine emitted along the way, counts them independently, and
|
||||
* checks the tally against that count. A fold hooked in the wrong place fails it whatever the seed.
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { advance } from '../src/engine/advance.ts';
|
||||
import { tallyEvent } from '../src/engine/tally.ts';
|
||||
import { applyIntent } from '../src/engine/apply.ts';
|
||||
import { STAGES_PER_DAY } from '../src/engine/content.ts';
|
||||
import { legalActions } from '../src/engine/legal.ts';
|
||||
import { createGame } from '../src/engine/setup.ts';
|
||||
import { developerBot } from '../src/sim/bot.ts';
|
||||
import type { GameEvent } from '../src/engine/events.ts';
|
||||
import type { GameConfig, GameState } from '../src/engine/state.ts';
|
||||
|
||||
const baseConfig = (over: Partial<GameConfig> = {}): GameConfig => ({
|
||||
mode: 'solitaire',
|
||||
days: 3,
|
||||
minCombinedRevenue: 0,
|
||||
maxCollisionsPerDay: 0,
|
||||
maxCollisionsTotal: 0,
|
||||
pvpCardsAllowed: false,
|
||||
optionalRules: { reducedVisibility: false, employeeRotation: false, emergencyToolbox: false },
|
||||
...over,
|
||||
});
|
||||
|
||||
/** Plays a whole game with the developer bot, keeping every event the engine produced. */
|
||||
function playKeepingEvents(
|
||||
seed: number,
|
||||
over: Partial<GameConfig> = {},
|
||||
names = ['Jesse'],
|
||||
): { state: GameState; events: GameEvent[] } {
|
||||
const state = createGame({ id: 'g', seed, config: baseConfig(over), playerNames: names });
|
||||
const events: GameEvent[] = [];
|
||||
for (let i = 0; i < 20_000; i++) {
|
||||
const r = advance(state);
|
||||
events.push(...r.events);
|
||||
if (state.status === 'finished') break;
|
||||
if (!r.needsInput) continue;
|
||||
|
||||
// The bot declines an extension, so this terminates on the timetable it was dealt (Gitea#11).
|
||||
const actor =
|
||||
state.status === 'awaitingExtension'
|
||||
? state.extensionVotes.findIndex((v) => v === null)
|
||||
: state.clock.pendingDecision !== null
|
||||
? state.clock.superintendent
|
||||
: state.clock.currentActor;
|
||||
if (actor === null || actor < 0) break;
|
||||
const options = legalActions(state, actor);
|
||||
if (options.length === 0) break;
|
||||
const applied = applyIntent(state, actor, developerBot.choose(state, actor, options));
|
||||
if (!applied.ok) break;
|
||||
events.push(...applied.events);
|
||||
}
|
||||
return { state, events };
|
||||
}
|
||||
|
||||
/** Counts events the way `tally.ts` should have, without sharing any of its code. */
|
||||
function countIndependently(events: GameEvent[]) {
|
||||
let sum = 0;
|
||||
const n = (type: GameEvent['type']): number => events.filter((e) => e.type === type).length;
|
||||
for (const e of events) {
|
||||
if (e.type === 'carsCoupled' || e.type === 'carsDropped') sum += e.stock.length;
|
||||
}
|
||||
return {
|
||||
trainsCompleted: n('trainCompleted'),
|
||||
loadsCompleted: n('loadCompleted'),
|
||||
unloadsCompleted: n('unloadCompleted'),
|
||||
loadsStarted: n('loadStarted'),
|
||||
unloadsBegun: n('unloadBegan'),
|
||||
passengersBoarded: n('passengersBoarded'),
|
||||
passengersDetrained: n('passengersDetrained'),
|
||||
cardsDrawn: n('cardDrawn'),
|
||||
cardsPlayed: n('cardPlayed'),
|
||||
cardsDiscarded: n('cardDiscarded'),
|
||||
officeUpgrades: n('officeUpgraded'),
|
||||
flyingSwitches: n('flyingSwitch'),
|
||||
extrasStarted: n('extraStarted'),
|
||||
secondSections: n('secondSectionOrdered'),
|
||||
trainsHeld: n('trainHeld'),
|
||||
trainsDiverted: n('trainDiverted'),
|
||||
expediteFaults: n('expediteFault'),
|
||||
facilitiesUnjammed: n('facilityUnjammed'),
|
||||
dispatchBonusesUsed: n('dispatchBonusUsed'),
|
||||
clearancesRequested: n('clearanceRequested'),
|
||||
switchedCars: sum,
|
||||
};
|
||||
}
|
||||
|
||||
describe('the tally counts every event exactly once (Gitea#16)', () => {
|
||||
for (const seed of [1, 7, 42, 116956197]) {
|
||||
it(`agrees with an independent count of the event stream — seed ${seed}`, () => {
|
||||
const { state, events } = playKeepingEvents(seed);
|
||||
const want = countIndependently(events);
|
||||
const t = state.tally;
|
||||
|
||||
assert.equal(t.trainsCompleted, want.trainsCompleted, 'trains through the Division');
|
||||
assert.equal(t.loadsCompleted, want.loadsCompleted, 'loads made up');
|
||||
assert.equal(t.unloadsCompleted, want.unloadsCompleted, 'loads broken');
|
||||
assert.equal(t.loadsStarted, want.loadsStarted, 'loads started');
|
||||
assert.equal(t.unloadsBegun, want.unloadsBegun, 'unloads begun');
|
||||
assert.equal(t.passengersBoarded, want.passengersBoarded, 'passengers boarded');
|
||||
assert.equal(t.passengersDetrained, want.passengersDetrained, 'passengers detrained');
|
||||
assert.equal(t.cardsDrawn, want.cardsDrawn, 'cards drawn');
|
||||
assert.equal(t.cardsPlayed, want.cardsPlayed, 'cards played');
|
||||
assert.equal(t.cardsDiscarded, want.cardsDiscarded, 'cards discarded');
|
||||
assert.equal(t.officeUpgrades, want.officeUpgrades, 'offices upgraded');
|
||||
assert.equal(t.flyingSwitches, want.flyingSwitches, 'flying switches');
|
||||
assert.equal(t.extrasStarted, want.extrasStarted, 'extras started');
|
||||
assert.equal(t.secondSections, want.secondSections, 'second sections');
|
||||
assert.equal(t.trainsHeld, want.trainsHeld, 'trains held');
|
||||
assert.equal(t.trainsDiverted, want.trainsDiverted, 'trains diverted');
|
||||
assert.equal(t.expediteFaults, want.expediteFaults, 'expedite faults');
|
||||
assert.equal(t.facilitiesUnjammed, want.facilitiesUnjammed, 'facilities unjammed');
|
||||
assert.equal(t.dispatchBonusesUsed, want.dispatchBonusesUsed, 'dispatch bonuses');
|
||||
assert.equal(t.clearancesRequested, want.clearancesRequested, 'clearances requested');
|
||||
assert.equal(t.carsCoupled + t.carsDropped, want.switchedCars, 'cars switched');
|
||||
});
|
||||
}
|
||||
|
||||
it('actually counted something — a tally of zeroes would pass the check above vacuously', () => {
|
||||
// The trap `stats.ts` warns about in its own doc comment: "this never happened" is a finding,
|
||||
// not something to scroll past. A fold hooked nowhere at all agrees perfectly with an
|
||||
// independent count of an event stream nobody looked at, so the exactly-once tests above cannot
|
||||
// catch it on their own.
|
||||
//
|
||||
// ASSERTED ON WHAT THE DEVELOPER BOT ACTUALLY DOES, which is not much: `node src/sim/harness.ts
|
||||
// 12 standard` means 1.1 Revenue per game at an 8% freight share and loses every game on the
|
||||
// revenue floor, and it goes whole games without coupling a single car. That is a known
|
||||
// property of the bot (TODO.md, Bot Performance) and not this fold's business — so this test
|
||||
// asserts on traffic and cards, which happen in every game, rather than on switching, which
|
||||
// would make it a bot-strength test wearing a statistics test's clothes.
|
||||
const { state, events } = playKeepingEvents(1);
|
||||
assert.ok(events.length > 500, `only ${events.length} events — the game barely ran`);
|
||||
assert.ok(state.tally.cardsDrawn > 0, 'no cards were drawn all game');
|
||||
assert.ok(state.tally.trainsCompleted > 0, 'no train ever left the Division');
|
||||
assert.ok(state.tally.cardsPlayed > 0, 'no card was ever played');
|
||||
});
|
||||
|
||||
it('splits Revenue into what was earned and what was given back', () => {
|
||||
// Reconciliation is the real assertion and it holds for any game, earned or not: gained minus
|
||||
// lost IS the score the engine kept. Seed 42 is named because it is one where Revenue actually
|
||||
// moves in both directions — it earns 1 and gives back 5 to a collision — so the two halves are
|
||||
// being told apart rather than both sitting at zero.
|
||||
for (const seed of [1, 7, 42]) {
|
||||
const { state } = playKeepingEvents(seed);
|
||||
const me = state.tally.byPlayer[0]!;
|
||||
assert.equal(
|
||||
me.revenueGained - me.revenueLost,
|
||||
state.players[0]!.revenue,
|
||||
`seed ${seed}: gained minus lost does not reconcile with the score the engine kept`,
|
||||
);
|
||||
}
|
||||
const { state } = playKeepingEvents(42);
|
||||
const me = state.tally.byPlayer[0]!;
|
||||
assert.ok(me.revenueGained > 0, 'seed 42 earned nothing — the gained half is not being counted');
|
||||
assert.ok(me.revenueLost > 0, 'seed 42 lost nothing — the lost half is not being counted');
|
||||
});
|
||||
|
||||
it('records a Circus set-up as the one-off it is, not as a streak', () => {
|
||||
/**
|
||||
* `trainStoodStill` is NOT "this train did not move this Stage". It fires only for a train whose
|
||||
* profile sets `stopEarnsPoint` — the X18 Circus — and `advance.ts` claims it once per train
|
||||
* with `stopPointClaimed`, so it can never fire twice for the same one.
|
||||
*
|
||||
* Gitea#16 asks for "longest engine sat on a siding" and its comment assumed this event would
|
||||
* answer it. It cannot, and a streak folded from it would have read "1 Stage" for ever. Pinned
|
||||
* here so that the day a real per-Stage signal is added, whoever adds it finds this test rather
|
||||
* than the old wrong assumption.
|
||||
*/
|
||||
const s = createGame({ id: 'g', seed: 1, config: baseConfig(), playerNames: ['Jesse'] });
|
||||
const feed = (e: GameEvent): void => tallyEvent(s, e);
|
||||
feed({ type: 'trainStoodStill', trainNumber: 18, where: '(0,0)' });
|
||||
assert.deepEqual(s.tally.circusStops, [{ trainNumber: 18, where: '(0,0)' }]);
|
||||
assert.ok(!('longestStand' in s.tally), 'a streak that cannot be computed is being reported');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the official result freezes the tally with it (Gitea#11 + #16)', () => {
|
||||
it('records the statistics as they stood when the timetable ran out', () => {
|
||||
const { state } = playKeepingEvents(1);
|
||||
assert.ok(state.official, 'no official result was recorded');
|
||||
// Nothing was played after the ending in this game, so the two agree — which is the check that
|
||||
// the freeze happens AFTER the last batch of events is folded rather than before it.
|
||||
assert.equal(state.official!.tally.trainsCompleted, state.tally.trainsCompleted);
|
||||
assert.ok(state.official!.tally.cardsDrawn > 0, 'the frozen tally is empty');
|
||||
});
|
||||
|
||||
it('keeps the frozen copy still while the live tally moves on', () => {
|
||||
const s = createGame({ id: 'g', seed: 1, config: baseConfig(), playerNames: ['Jesse'] });
|
||||
s.clock.day = s.config.days + 1;
|
||||
s.clock.stage = STAGES_PER_DAY;
|
||||
s.clock.phase = 'shiftChange';
|
||||
advance(s);
|
||||
const frozen = s.official!.tally.cardsDrawn;
|
||||
|
||||
applyIntent(s, 0, { type: 'game.extend', player: 0, agree: true });
|
||||
tallyEvent(s, { type: 'cardDrawn', player: 0, source: 'homeOffice', cardId: 'x' });
|
||||
assert.equal(s.tally.cardsDrawn, frozen + 1, 'the live tally did not move');
|
||||
assert.equal(s.official!.tally.cardsDrawn, frozen, 'the frozen tally moved with it');
|
||||
});
|
||||
});
|
||||
+106
-5
@@ -21,14 +21,16 @@ import { URLSearchParams as NodeURLSearchParams } from 'node:url';
|
||||
import { cardDescription, cardName, describeIntent, variantLabel } from '../src/sim/view.ts';
|
||||
import { variantsFor } from '../src/engine/track.ts';
|
||||
import { divisionSvg, officeSvg } from '../src/sim/board-svg.ts';
|
||||
import { ENHANCEMENT_RULES } from '../src/engine/content.ts';
|
||||
import { dayEndHtml, facilitiesHtml, timetableHtml } from '../src/web/panels.ts';
|
||||
import { ENHANCEMENT_RULES, STAGES_PER_DAY } from '../src/engine/content.ts';
|
||||
import { dayEndHtml, facilitiesHtml, resultsHtml, timetableHtml } from '../src/web/panels.ts';
|
||||
import { turnChartHtml } from '../src/sim/turnchart.ts';
|
||||
import { fieldSelectors } from '../src/web/settings-form.ts';
|
||||
import { record, renderHtml } from '../src/sim/replay.ts';
|
||||
import type { Frame } from '../src/sim/view.ts';
|
||||
import { snapshot } from '../src/sim/view.ts';
|
||||
import { createGame as createEngineGame } from '../src/engine/setup.ts';
|
||||
import { advance as advanceEngine } from '../src/engine/advance.ts';
|
||||
import type { GameConfig } from '../src/engine/state.ts';
|
||||
import {
|
||||
overHandLimit,
|
||||
actionGroups,
|
||||
@@ -104,6 +106,18 @@ describe('the browser game plays', () => {
|
||||
it('reaches the end of a game through the same calls the page makes', () => {
|
||||
const { game, turns } = playThrough(77);
|
||||
assert.ok(turns > 50, `only ${turns} decisions — the game stalled`);
|
||||
|
||||
/**
|
||||
* The timetable runs out and the game STOPS TO ASK rather than ending (Gitea#11) — `currentActor`
|
||||
* is null there, which is where `playThrough` breaks. Declining through `submit` finishes it,
|
||||
* which is worth doing here rather than merely asserting the pause: this test exists to prove a
|
||||
* whole game is playable through the calls the page makes, and since Gitea#11 the last of those
|
||||
* calls is the vote.
|
||||
*/
|
||||
assert.equal(game.state.status, 'awaitingExtension');
|
||||
assert.ok(game.state.official !== null, 'an ended game must have recorded its official result');
|
||||
assert.ok(submit(game, { type: 'game.extend', player: 0, agree: false }, 0), 'the page cannot decline');
|
||||
|
||||
assert.equal(game.state.status, 'finished');
|
||||
assert.ok(game.state.outcome !== null, 'a finished game must have an outcome');
|
||||
});
|
||||
@@ -1932,8 +1946,10 @@ describe('the static build', () => {
|
||||
const asked = new Set([...src.matchAll(/\$\('([a-zA-Z][\w-]*)'\)/g)].map((m) => m[1]!));
|
||||
const html = readFileSync(join(dist, 'play.html'), 'utf8');
|
||||
const present = new Set([...html.matchAll(/id="([a-zA-Z][\w-]*)"/g)].map((m) => m[1]!));
|
||||
// `again` is created by the game-over screen before it is looked up.
|
||||
present.add('again');
|
||||
// Created by the ending screen (`renderEnding`) before they are looked up, so they are never in
|
||||
// the served HTML: `again` starts a new game, `results` reopens the results dialog, and the two
|
||||
// `extend-*` buttons are the extension vote (Gitea#11).
|
||||
for (const id of ['again', 'results', 'extend-yes', 'extend-no']) present.add(id);
|
||||
for (const id of asked) {
|
||||
assert.ok(present.has(id), `main.ts asks for #${id}, which the page does not contain`);
|
||||
}
|
||||
@@ -3283,12 +3299,97 @@ describe('the Day rolling over says so (Gitea#10)', () => {
|
||||
|
||||
it('gives the page the dialog to fill', () => {
|
||||
const html = readFileSync(join(dist, 'play.html'), 'utf8');
|
||||
for (const id of ['dayenddlg', 'dayendbody']) {
|
||||
for (const id of ['dayenddlg', 'dayendbody', 'resultsdlg', 'resultsbody']) {
|
||||
assert.ok(html.includes(`id="${id}"`), `play.html has no #${id}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('the end-of-game results screen (Gitea#16)', () => {
|
||||
/**
|
||||
* A finished game, built by running the clock off the end of a real one rather than by hand — the
|
||||
* screen reads `official`, and only the engine writes that.
|
||||
*/
|
||||
const finished = (over: Partial<GameConfig> = {}, names = ['Solitaire']): Frame => {
|
||||
const s = createEngineGame({
|
||||
id: 'results', seed: 4021,
|
||||
config: {
|
||||
mode: 'solitaire', days: 5, minCombinedRevenue: 12,
|
||||
maxCollisionsPerDay: 0, maxCollisionsTotal: 0, pvpCardsAllowed: false,
|
||||
optionalRules: { reducedVisibility: false, employeeRotation: false, emergencyToolbox: false },
|
||||
...over,
|
||||
},
|
||||
playerNames: names,
|
||||
});
|
||||
s.clock.day = s.config.days + 1;
|
||||
s.clock.stage = STAGES_PER_DAY;
|
||||
s.clock.phase = 'shiftChange';
|
||||
advanceEngine(s);
|
||||
return snapshot(s, [], null);
|
||||
};
|
||||
|
||||
it('never prints a raw enum at the player', () => {
|
||||
// The bug the issue opens on: `GAME OVER — revenueFloor` is an internal identifier, shown at
|
||||
// the one moment the game has the player's whole attention.
|
||||
for (const f of [finished(), finished({ minCombinedRevenue: 0 })]) {
|
||||
const html = resultsHtml(f);
|
||||
for (const raw of ['revenueFloor', 'daysElapsed', 'collisionFloor']) {
|
||||
assert.ok(!html.includes(raw), `the results screen prints the raw reason "${raw}"`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('says why the game ended, in a sentence, with the game\'s own numbers in it', () => {
|
||||
const html = resultsHtml(finished());
|
||||
assert.ok(html.includes('closed short'), `the revenue-floor ending is not explained:\n${html}`);
|
||||
assert.ok(html.includes('<b>12</b>'), 'the floor that was missed is not named');
|
||||
});
|
||||
|
||||
it('reports the rules the game was actually dealt under', () => {
|
||||
const html = resultsHtml(finished({ mode: 'coop' }, ['Ada', 'Bo']));
|
||||
assert.ok(html.includes('The rules in play'), 'the rules section is missing');
|
||||
assert.ok(html.includes('Co-op'), 'the mode is not reported');
|
||||
assert.ok(html.includes('per load'), 'the pay rates are not reported');
|
||||
});
|
||||
|
||||
it('reports the railroad from the tally, not from nothing', () => {
|
||||
const html = resultsHtml(finished());
|
||||
assert.ok(html.includes('Trains through the Division'), 'the tally section is missing');
|
||||
});
|
||||
|
||||
it('names the winner the OFFICIAL result named, not whoever leads now (Gitea#11)', () => {
|
||||
const f = finished({ mode: 'competitive', minCombinedRevenue: 0 }, ['Ada', 'Bo']);
|
||||
// Ada won at the timetable; Bo overtakes during extended play. The frozen result stands.
|
||||
f.official = {
|
||||
day: 5,
|
||||
outcome: { result: 'win', winner: 0, reason: 'daysElapsed' },
|
||||
revenues: [9, 2],
|
||||
collisionsTotal: 0,
|
||||
tally: f.tally,
|
||||
};
|
||||
f.extraDays = 3;
|
||||
f.players = [
|
||||
{ index: 0, seat: 0, name: 'Ada', revenue: 9, hand: 3 },
|
||||
{ index: 1, seat: 1, name: 'Bo', revenue: 40, hand: 2 },
|
||||
];
|
||||
const html = resultsHtml(f);
|
||||
assert.ok(html.includes('Ada takes the Division'), `the official winner is not the headline:\n${html}`);
|
||||
assert.ok(html.includes('winner'), 'nobody is marked as the winner in the standings');
|
||||
assert.ok(html.includes('After the timetable'), 'extended play is not reported at all');
|
||||
assert.ok(html.includes('3 more Days'), 'the extra Days are not counted');
|
||||
assert.ok(
|
||||
html.indexOf('Ada takes the Division') < html.indexOf('After the timetable'),
|
||||
'the informational section is above the official result',
|
||||
);
|
||||
});
|
||||
|
||||
it('leaves out the extended-play section entirely when nothing was extended', () => {
|
||||
assert.ok(!resultsHtml(finished()).includes('After the timetable'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('every file the build needs is actually in the repo (regression)', () => {
|
||||
it('does not gitignore a source page', () => {
|
||||
// REGRESSION. `.gitignore` carried `replay*.html` to catch the throwaway files generated at the
|
||||
|
||||
Reference in New Issue
Block a user