Compare commits
@@ -50,3 +50,9 @@ __pycache__/
|
||||
# one that is worth publishing.
|
||||
/playtests/*
|
||||
!/playtests/README.md
|
||||
|
||||
# The Jitsi harness is NOT scrubbed — four of its files carry a real domain and real
|
||||
# participant names (workspace AGENTS.local.md). Ignored so that a `git add -A` cannot sweep it
|
||||
# into a history that would be permanently exposed if this repo is ever made public. When it is
|
||||
# promoted in Phase 1, scrub it FIRST, then `git add -f tools/`.
|
||||
tools/
|
||||
|
||||
+1058
File diff suppressed because it is too large
Load Diff
@@ -131,6 +131,18 @@ is the thing this machinery exists to prevent.
|
||||
and they do not reconstruct the position. The phase driver mutates state and then describes it, so
|
||||
roughly a third of the event types are never reduced at all. Anything that needs to rebuild a game
|
||||
replays the intents.
|
||||
- **A save is only guaranteed to replay on the version that wrote it.** This is the cost of the
|
||||
property above and is not a bug to be fixed case by case: a save is a list of moves, so it reopens
|
||||
by being *re-played through the current rules*. Any rules change that makes a once-legal move
|
||||
illegal will stop an older save at that move — **a change to the deck is the likeliest breaker**,
|
||||
since a history that names a card the deck no longer deals has no legal answer at all, but any
|
||||
narrowing of what is permitted does it. It fails safe in every case: the load is declined, the
|
||||
offending move is named, and the file is left untouched, so nothing a player has is destroyed.
|
||||
Assume an older save may not open, tell players so wherever a build is announced, and read "this
|
||||
save will not load" in a bug report as this before treating it as a fault. **Versioned, migratable
|
||||
replays are a post-1.0 question** — deliberately not worth the effort while the rules are still
|
||||
moving this fast, since every migration would have to be written against rules that changed again
|
||||
next release.
|
||||
- **Never call `Math.random()`.** One ambient random call silently breaks replay.
|
||||
- **The Mainline Phase can stop and ask, and there are three questions it asks.** §8.1's clearance
|
||||
ruling goes to the Superintendent; the Yard Office offer and the Red Flag prompt go to the owner of
|
||||
|
||||
@@ -0,0 +1,978 @@
|
||||
# Station Master Jitsi Common Board Implementation Plan
|
||||
|
||||
**Status (2026-09-07):** **STEP 1 IS BUILT AND SHIPPED. Steps 2-7 are unimplemented.**
|
||||
|
||||
Step 1 landed across four releases rather than one — v0.7.9.2 (the two narration leaks), v0.7.9.4
|
||||
(the projection helpers and the redaction net), v0.7.9.5 (the narration path), and v0.7.9.8 (this
|
||||
reconciliation). One of its items is struck off rather than built; see § Public game projection.
|
||||
|
||||
**This document has drifted from the code and is no longer the authority on what exists.** It was
|
||||
written on 2026-08-27 against the code of that date, and the "Current code findings" under each step
|
||||
describe faults that were then real — several are now fixed, and reading them as present tense will
|
||||
send you to fix things twice. Where a step is marked built, `src/sim/view.ts`, `src/server/`, and the
|
||||
tests named in TODO.md are the authority. Steps 2-7 were never implemented and their findings have
|
||||
NOT been re-verified against the current code; check each before building on it.
|
||||
|
||||
## Summary
|
||||
|
||||
Add a privacy-safe common game board that can be viewed in a browser and published into the game’s Jitsi meeting by a server-managed headless Chromium participant.
|
||||
|
||||
The publisher represents the game table, not a player or bot. Human and bot actions both update the same public board. No hands, objectives, legal moves, random seed, private draws, or other player-only state may enter the display data path.
|
||||
|
||||
The implementation is divided into independently useful stages:
|
||||
|
||||
1. Establish a secure public-state projection and close existing narration leaks.
|
||||
2. Add a public display stream, credentials, persistence, and reconnect behavior.
|
||||
3. Build the reusable 1280×720 common-board renderer.
|
||||
4. Preserve individual human and bot actions as display animation steps.
|
||||
5. Add a minimal visual-only Jitsi engine.
|
||||
6. Supervise one headless Chromium process per published game.
|
||||
7. Integrate lifecycle, configuration, packaging, health, and live verification.
|
||||
|
||||
The browser display remains useful without Jitsi. The public projection and leak fixes improve multiplayer security even if no visual display is deployed.
|
||||
|
||||
## Research incorporated
|
||||
|
||||
This plan is based on the current Station Master server, engine, multiplayer view, persistence, and untracked Jitsi harness, plus a read-only review of the sibling `jitsi-transcription` packaging repository at commit `9cae1877a9d9a9f489de8f870dad6ff011521c9d`.
|
||||
|
||||
The Jitsi Transcription review materially changes the earlier architecture:
|
||||
|
||||
- Use direct `child_process.spawn` Chromium supervision, not Playwright or CDP.
|
||||
- Use one Chromium process and temporary browser profile per published game, not multiple contexts in one shared browser.
|
||||
- Copy the minimal proven Jitsi/control patterns into Station Master; do not create a runtime dependency on the sibling repository.
|
||||
- Treat `conference.authenticationRequired` as a retryable “waiting for moderator” state.
|
||||
- Use the exact StartOS-proven Chromium flag set.
|
||||
- Explicitly disable third-party requests in `JitsiMeetJS.init`.
|
||||
- Gracefully leave Jitsi before terminating Chromium to reduce ghost participants.
|
||||
- Package Chromium and `tini`; visual-only publishing needs neither PulseAudio nor Xvfb.
|
||||
- Default to one concurrent publisher until target-hardware measurements justify more.
|
||||
|
||||
The sibling repository had unrelated local modifications and untracked files. They are not part of this plan.
|
||||
|
||||
## Public interfaces and types
|
||||
|
||||
### Public game projection
|
||||
|
||||
Introduce dedicated allow-listed types. Do not derive them with `Omit<Frame, ...>` because new private `Frame` fields could then leak automatically.
|
||||
|
||||
> **RECONCILED 2026-09-07 (v0.7.9.8).** Step 1 is BUILT, and what shipped is not shaped like the
|
||||
> sketch below. This block was the design; `PublicFrame` in `src/sim/view.ts` is now the authority,
|
||||
> and `test/redaction.test.ts`'s allow-list is the enumeration of it that fails when it changes.
|
||||
> **Read those two, not this**, when building steps 2-7. The differences that matter:
|
||||
>
|
||||
> - **The shape is FLAT, not grouped.** There is no `clock`, `config`, `scoring` or `deckCounts`
|
||||
> object. Their contents sit at the top level — `day`, `stage`, `clock` (a time string), `phase`,
|
||||
> `phaseKey`, `actor`, `superintendent`, `deck`, `departments`, `departmentDepth`, `salvage`,
|
||||
> `yards`, `mode`, `days`, `optionalRules`, `houseRules`, `minCombinedRevenue`,
|
||||
> `maxCollisionsPerDay`, `maxCollisionsTotal`, `collisionsToday`, `collisionsTotal`, `status`,
|
||||
> `outcome`, `extraDays`, `extensionVotes`, `official`, `tally`, `openingRolls`, `timetable`,
|
||||
> `timetableWhat`, `trains`, `players`, `division`, `districts`.
|
||||
> - **`protocolVersion` was NOT built** and exists nowhere in the repo. Step 2 is the reconnecting
|
||||
> display stream, which is the first thing that would want one — decide there whether to add it,
|
||||
> rather than assuming it is already on the wire.
|
||||
> - **`redFlagHeld` is STRUCK OFF**, not deferred. See below.
|
||||
> - **Fields gained since this was written** that the renderer should know about: `crewTrays` and
|
||||
> `queued` (#98, the Crew Tray pool and the trains waiting for one), and on each district's cells
|
||||
> `heldAtLimits` (#99, a train stopped on the Limit Track) and `enhancementsSpent` (#101, a
|
||||
> dispatch device spent for the Day).
|
||||
>
|
||||
> **Why `redFlagHeld` is struck off rather than built.** The premise does not hold in this codebase.
|
||||
> `decks.redFlags` is written in exactly one place — `setup.ts`, from
|
||||
> `config.optionalRules.emergencyToolbox` — and never again; `redFlag.play` emits `phaseEnded` and
|
||||
> does not spend it. So every player holds one or none does, decided before the deal. A per-player
|
||||
> `redFlagHeld` would be `optionalRules.emergencyToolbox` copied N times, already public, while
|
||||
> telling every reader of the common board that it varies by player and may change mid-game. The
|
||||
> invariant is pinned by test (`test/display-gaps.test.ts`) so this does not get re-raised from the
|
||||
> plan text: if the rule ever becomes per-player, that test fails.
|
||||
|
||||
The design as originally written, kept for the reasoning:
|
||||
|
||||
```ts
|
||||
type PublicPlayerView = {
|
||||
index: PlayerIndex;
|
||||
seat: PlayerIndex;
|
||||
name: string;
|
||||
revenue: number;
|
||||
handCount: number;
|
||||
redFlagHeld: boolean;
|
||||
};
|
||||
|
||||
type PublicDistrictView = {
|
||||
seat: PlayerIndex;
|
||||
player: PlayerIndex;
|
||||
cells: readonly CellView[];
|
||||
facilities: readonly FacilityView[];
|
||||
runningRow: number;
|
||||
limits: unknown;
|
||||
};
|
||||
|
||||
type PublicFrame = {
|
||||
protocolVersion: 1;
|
||||
status: GameState['status'];
|
||||
clock: PublicClockView;
|
||||
config: PublicConfigView;
|
||||
scoring: PublicScoringView;
|
||||
players: readonly PublicPlayerView[];
|
||||
division: readonly DivisionView[];
|
||||
districts: readonly PublicDistrictView[];
|
||||
deckCounts: PublicDeckCounts;
|
||||
departments: PublicDepartmentsView;
|
||||
salvage: PublicSalvageView;
|
||||
yards: PublicYardsView;
|
||||
timetable: PublicTimetableView;
|
||||
};
|
||||
```
|
||||
|
||||
Reuse existing view types only after verifying every reused field is public. Create narrower public variants where an existing type includes viewer-specific or private data.
|
||||
|
||||
The projection must never include:
|
||||
|
||||
- `viewer`
|
||||
- card identities in any player’s hand
|
||||
- `justDrawn`
|
||||
- objectives
|
||||
- decisions or private prompts
|
||||
- menus, actions, legal moves, or blocked reasons
|
||||
- seed or RNG state
|
||||
- raw `GameState`
|
||||
- intent history
|
||||
- private event details
|
||||
- unresolved internal ordering data
|
||||
- full shared narration logs
|
||||
|
||||
### Display stream
|
||||
|
||||
```ts
|
||||
type PublicFrameDelta = PartialPublicFrameDelta;
|
||||
|
||||
type DisplayReset = {
|
||||
type: 'display.reset';
|
||||
seq: number;
|
||||
frame: PublicFrame;
|
||||
};
|
||||
|
||||
type DisplayStep = {
|
||||
type: 'display.step';
|
||||
seq: number;
|
||||
actor: {
|
||||
player: PlayerIndex;
|
||||
seat: PlayerIndex;
|
||||
source: 'human' | 'bot';
|
||||
};
|
||||
frame: PublicFrameDelta;
|
||||
lines: readonly PublicNarrationLine[];
|
||||
};
|
||||
|
||||
type DisplayMessage = DisplayReset | DisplayStep;
|
||||
```
|
||||
|
||||
A new or reconnected display client always receives `display.reset`. Subsequent accepted intents produce ordered `display.step` messages. The server does not replay missed steps; reconnecting clients reset to the latest public state.
|
||||
|
||||
### Jitsi publisher state
|
||||
|
||||
```ts
|
||||
type JitsiPublisherState =
|
||||
| 'disabled'
|
||||
| 'queued'
|
||||
| 'launching'
|
||||
| 'connecting'
|
||||
| 'waiting-for-admission'
|
||||
| 'waiting-for-moderator'
|
||||
| 'publishing'
|
||||
| 'reconnecting'
|
||||
| 'stopping'
|
||||
| 'failed';
|
||||
```
|
||||
|
||||
Expose sanitized state, last transition time, and a safe error summary through the existing session/health surfaces. Never expose meeting credentials, display credentials, Jitsi tokens, XMPP service credentials, or browser launch URLs.
|
||||
|
||||
## Step 1 — Secure public-state projection
|
||||
|
||||
> **BUILT — v0.7.9.2 through v0.7.9.5.** Everything in "Required changes" below shipped except the
|
||||
> Red Flag holder, which is struck off (§ Public game projection). Mapping to the work items in
|
||||
> TODO.md: the projection helpers and `currentActorOfState` are **#95**, the systematic redaction
|
||||
> net and its allow-list are **#91**, the seed and blind-draw narration leaks are **#92**, and
|
||||
> "stop passing the full game log into `frameFor()`" is **#97** — which also fixed a reconnect bug
|
||||
> the duplicate had been masking, so read that entry before touching narration in step 2.
|
||||
>
|
||||
> **The findings below are as of 2026-08-27 and are now HISTORY, not a task list.** Two are worth
|
||||
> carrying forward anyway: districts must be keyed by SEAT with ownership resolved through
|
||||
> `playerAtSeat` (Employee Rotation), and the public view must be composed UPWARD from shared
|
||||
> helpers, never by calling the player `snapshot()` once per seat. Both are load-bearing for step 3.
|
||||
>
|
||||
> One finding was struck off on measurement rather than fixed: it warns that a display reading
|
||||
> `clock.currentActor` could highlight the wrong district during a decision. Across six seeds and
|
||||
> 3,600 decision points that field and `actingPlayer` never disagreed. `currentActorOfState` exists
|
||||
> anyway as the one place to ask — and **#96** later found a real instance of the same class in a
|
||||
> state nobody had checked, the §3.3 vote, where the game is not `active` at all.
|
||||
|
||||
### Current code findings
|
||||
|
||||
`src/sim/view.ts` currently builds `Frame` for one real viewer and defaults that viewer to player zero. It combines shared table state, one district, and viewer-private fields. Calling it for a spectator would silently expose player zero’s district and private information.
|
||||
|
||||
`src/server/session.ts` calls:
|
||||
|
||||
```ts
|
||||
snapshot(game.state, game.log, ..., seat)
|
||||
```
|
||||
|
||||
This embeds the complete shared narration log in every `Frame`, while `Push.lines` also sends narration incrementally.
|
||||
|
||||
Existing narration has at least two privacy leaks:
|
||||
|
||||
- `newMultiplayerGame()` places the seed in the shared log.
|
||||
- A blind Home Office draw can resolve the drawn card to its real name in shared narration.
|
||||
|
||||
Existing redaction tests pass `[]` for narration and mainly search internal IDs, so they do not detect resolved card names or seed text in the full serialized payload.
|
||||
|
||||
`currentActor(game)` accounts for Superintendent/pending decisions, while `snapshot()` reads `state.clock.currentActor`. A public display using the latter could highlight the wrong district.
|
||||
|
||||
Employee Rotation means district ownership cannot be assumed to match player index. Districts must be keyed by seat, with current ownership resolved through `playerAtSeat`.
|
||||
|
||||
### Required changes
|
||||
|
||||
Create explicit projection helpers in the simulation/view layer:
|
||||
|
||||
- `projectDistrict(state, seat)`
|
||||
- `projectDivision(state)`
|
||||
- `projectSharedTable(state)`
|
||||
- `publicSnapshot(state)`
|
||||
- `currentActorOfState(state)`
|
||||
|
||||
Refactor the player snapshot and public snapshot to share only safe lower-level projection helpers. Do not implement the public view by repeatedly calling the player `snapshot()` function.
|
||||
|
||||
Make the existing actor logic use the same engine-level helper so player views, bot execution, and the common board agree during decisions and Superintendent actions.
|
||||
|
||||
Add the Red Flag holder to the public player projection. It is public game state but is currently absent from `Frame`.
|
||||
|
||||
Remove seed narration from multiplayer game creation. Retain the seed only in persistence and administrative/replay data.
|
||||
|
||||
Change blind-draw narration to a generic public line such as “Home Office drew a card.” Keep the card identity available only to the drawing player through the existing owner-only `justDrawn` mechanism.
|
||||
|
||||
Stop passing the full game log into `frameFor()`. Continue sending sanitized incremental narration through `Push.lines`.
|
||||
|
||||
### Tests
|
||||
|
||||
Add tests that serialize the entire public frame and player pushes, then search for:
|
||||
|
||||
- every opponent hand card ID
|
||||
- every opponent hand card display name
|
||||
- current objective IDs and names
|
||||
- `justDrawn` for the wrong player
|
||||
- seed values and seed narration
|
||||
- private decision/menu/action data
|
||||
|
||||
Cover:
|
||||
|
||||
- a newly created multiplayer game
|
||||
- a blind Home Office draw
|
||||
- a pending decision
|
||||
- Superintendent acting
|
||||
- Employee Rotation before and after ownership changes
|
||||
- reconnect pushes
|
||||
- a finished game
|
||||
|
||||
Acceptance requires an allow-list review of every `PublicFrame` property. Passing redaction tests alone is insufficient.
|
||||
|
||||
## Step 2 — Display credentials, stream, and persistence
|
||||
|
||||
### Display metadata
|
||||
|
||||
Create separate per-game display metadata rather than extending the authoritative game save:
|
||||
|
||||
```ts
|
||||
type SavedDisplayMetadata = {
|
||||
schemaVersion: 1;
|
||||
room: string;
|
||||
viewToken: string;
|
||||
publisherToken: string;
|
||||
nextSequence: number;
|
||||
createdAt: number;
|
||||
};
|
||||
```
|
||||
|
||||
Store it in the same per-game data directory as `display.json`, using the persistence layer’s existing atomic-write pattern.
|
||||
|
||||
Generate:
|
||||
|
||||
- a cryptographically random Jitsi room name
|
||||
- a high-entropy `viewToken`
|
||||
- a separate high-entropy `publisherToken`
|
||||
|
||||
Do not derive any token from game ID, room name, player token, seed, or timestamp.
|
||||
|
||||
For older saves without `display.json`, generate the metadata once on resume and persist it. Failure to initialize display metadata must disable display/Jitsi for that game without preventing the underlying game from resuming.
|
||||
|
||||
### HTTP endpoints
|
||||
|
||||
Add:
|
||||
|
||||
- `GET /display.html#token=<viewToken>` — manual common-board page
|
||||
- `GET /api/display/stream?token=<viewToken>` — public-board SSE
|
||||
- `GET /display-agent.html` — internal headless publisher page
|
||||
- WebSocket upgrade at `/api/display/control` — supervisor/agent control
|
||||
|
||||
Extend the authenticated game/session response with:
|
||||
|
||||
- display URL
|
||||
- Jitsi meeting URL
|
||||
- sanitized publisher state
|
||||
|
||||
The browser display reads the fragment token, removes it from the visible address if practical, and supplies it to the SSE request. Fragments keep the credential out of the initial HTTP request and normal server access logs.
|
||||
|
||||
Do not add a publisher-configuration HTTP endpoint. The internal agent receives its meeting configuration and view token over the authenticated control WebSocket.
|
||||
|
||||
### SSE behavior
|
||||
|
||||
Maintain a display subscriber set per game.
|
||||
|
||||
On connection:
|
||||
|
||||
1. Authenticate `viewToken`.
|
||||
2. Produce the latest `PublicFrame`.
|
||||
3. Send `display.reset` with the current sequence.
|
||||
4. Continue existing heartbeat behavior.
|
||||
5. Send later `display.step` messages in sequence order.
|
||||
|
||||
Use a dedicated public-frame delta function rather than the player `Frame` delta. The observed public snapshot grows enough during longer games that full frames for every action would be wasteful.
|
||||
|
||||
If an SSE client is slow or disconnected, close it and let EventSource reconnect to a new reset. Do not keep an unbounded replay buffer.
|
||||
|
||||
### Security requirements
|
||||
|
||||
- Compare tokens without placing them in error messages.
|
||||
- Do not log query strings or control registration messages containing tokens.
|
||||
- Never accept game intents through display endpoints.
|
||||
- Do not let a view token register as a publisher.
|
||||
- Apply payload and connection limits independently from player SSE.
|
||||
- Keep display failure isolated from player pushes and game persistence.
|
||||
|
||||
### Tests
|
||||
|
||||
Add HTTP tests after refactoring `startServer()` to return the server/listening handle needed by tests.
|
||||
|
||||
Cover:
|
||||
|
||||
- valid and invalid view tokens
|
||||
- publisher token rejected as a view token
|
||||
- reset on first connect and reconnect
|
||||
- monotonically increasing sequence IDs
|
||||
- public deltas reconstruct the same frame as a fresh reset
|
||||
- heartbeat behavior
|
||||
- no private fields in raw SSE bytes
|
||||
- legacy save migration
|
||||
- atomic `display.json` persistence
|
||||
- display failure not interrupting `/api/intent` or player SSE
|
||||
|
||||
## Step 3 — Reusable common-board renderer
|
||||
|
||||
### Renderer structure
|
||||
|
||||
Build one renderer shared by:
|
||||
|
||||
- the manual browser display
|
||||
- the headless Jitsi publisher page
|
||||
|
||||
Use a fixed 1280×720 canvas at 10 frames per second. Set the captured video track’s `contentHint` to `"detail"`.
|
||||
|
||||
Keep the canvas palette stable. The Jitsi Transcription prototype deliberately changed color themes to prove updates were arriving; that behavior strobes during frequent game actions and must not enter the product.
|
||||
|
||||
Separate the renderer into:
|
||||
|
||||
- a pure layout/view-model stage
|
||||
- image/SVG preparation
|
||||
- canvas drawing
|
||||
- animation queue management
|
||||
|
||||
### Layout
|
||||
|
||||
Use this fixed layout:
|
||||
|
||||
- Header: game name/status, day/stage/phase, current actor, Red Flag.
|
||||
- Main left: persistent Division board.
|
||||
- Main right: focused district.
|
||||
- Footer/side panels: player standings, hand counts, timetable, public decks/resources, and recent narration.
|
||||
- Compact district summaries: every district’s owner, revenue, and operational status.
|
||||
|
||||
The focused district is:
|
||||
|
||||
1. the acting player’s current seat;
|
||||
2. otherwise the most recent actor’s seat;
|
||||
3. otherwise seat zero.
|
||||
|
||||
Resolve owner from seat on every frame so Employee Rotation updates the labels without moving the district itself.
|
||||
|
||||
The complete `PublicFrame` carries all public districts even though the 720p layout focuses one at a time.
|
||||
|
||||
### Existing assets
|
||||
|
||||
Reuse the existing Division and office SVG generators and exported board CSS. Adapt their APIs so the Division roster can be rendered without a private viewer.
|
||||
|
||||
Render SVG output into canvas-safe images. Cache images by serialized SVG/content key and invalidate only when the corresponding public model changes.
|
||||
|
||||
Do not recreate game rules or labels inside the renderer. The projection layer supplies display-ready public labels.
|
||||
|
||||
### Display behavior
|
||||
|
||||
- Human and bot actions use the same animation path.
|
||||
- Normal display-step duration: 700 ms.
|
||||
- If the queue exceeds 12 steps, use 200 ms catch-up transitions.
|
||||
- A reset clears queued animations and renders immediately.
|
||||
- Rendering or asset failure keeps the previous good frame and reports a sanitized diagnostic.
|
||||
- Recent narration is bounded and uses only sanitized `DisplayStep.lines`.
|
||||
- No server-side sleeps are permitted.
|
||||
|
||||
Update `scripts/build-web.ts` to explicitly build/copy the new display entry points, HTML pages, styles, and Jitsi vendor asset. The current static build manually lists its artifacts, so relying on automatic discovery will omit the pages.
|
||||
|
||||
### Tests
|
||||
|
||||
Test the pure layout model for:
|
||||
|
||||
- focused-district selection
|
||||
- Employee Rotation ownership
|
||||
- Superintendent decisions
|
||||
- two through four players
|
||||
- empty and dense boards
|
||||
- long player/facility names
|
||||
- finished-game state
|
||||
|
||||
Test renderer lifecycle with a fake canvas/image layer:
|
||||
|
||||
- reset clears the queue
|
||||
- step order is preserved
|
||||
- catch-up speed activates at the threshold
|
||||
- stopped renderers stop timers and media tracks
|
||||
- no private input type is accepted
|
||||
|
||||
Perform visual review at 1280×720 and as a reduced Jitsi tile. Text and train positions must remain legible without opening a tooltip.
|
||||
|
||||
## Step 4 — Preserve individual human and bot actions
|
||||
|
||||
### Current code findings
|
||||
|
||||
`GameSession.intent()` applies the human intent, runs `driveBots()`, and only then creates player pushes.
|
||||
|
||||
`driveBots()` can call `submit()` many times. Player deltas intentionally collapse those moves into one final state, which is appropriate for gameplay but would make bots appear to teleport through several actions on the common board.
|
||||
|
||||
Engine events cannot be replayed into display state. One accepted intent may run automatic `drain()` work and emit several events, and the event list is not a complete reducer.
|
||||
|
||||
### Required changes
|
||||
|
||||
Introduce a display-step collector inside `GameSession`.
|
||||
|
||||
After every successful `submit()`:
|
||||
|
||||
1. Resolve the acting player and current seat.
|
||||
2. Produce the sanitized narration lines added by that submission.
|
||||
3. Create the next `PublicFrame` immediately.
|
||||
4. Delta it against the last emitted public frame.
|
||||
5. Assign the next display sequence.
|
||||
6. Emit one `DisplayStep`.
|
||||
|
||||
Apply this both to:
|
||||
|
||||
- the human submission in `intent()`
|
||||
- every successful bot submission inside `driveBots()`
|
||||
|
||||
Capture the frame immediately. Do not retain a mutable `GameState` reference for later projection because every retained reference would otherwise resolve to the final state.
|
||||
|
||||
One display step corresponds to one accepted intent, including automatic consequences drained by that intent. Do not create one step per low-level `GameEvent`.
|
||||
|
||||
Keep player pushes unchanged: players still receive the final coalesced result after all immediately due bots finish.
|
||||
|
||||
Opening bot moves that occur before any client connects do not need replay. Persist the resulting game state and sequence; a later display receives the final reset.
|
||||
|
||||
### Failure isolation
|
||||
|
||||
Display projection or broadcasting must not invalidate an already accepted game move.
|
||||
|
||||
If step generation fails:
|
||||
|
||||
- record a sanitized server diagnostic
|
||||
- mark the publisher/display state degraded
|
||||
- send a fresh reset on the next successful display update
|
||||
- continue normal game and player push processing
|
||||
|
||||
### Tests
|
||||
|
||||
Cover:
|
||||
|
||||
- one human intent with no bot response
|
||||
- one human intent followed by several bot intents
|
||||
- consecutive bot turns
|
||||
- bot pending decisions
|
||||
- automatic engine work within one intent
|
||||
- ordering of narration and frames
|
||||
- sequence continuity
|
||||
- player pushes remaining coalesced
|
||||
- reconstructed display state matching `publicSnapshot()` after the final step
|
||||
|
||||
## Step 5 — Minimal visual-only Jitsi engine
|
||||
|
||||
### Source strategy
|
||||
|
||||
Port the smallest relevant production patterns from `jitsi-transcription` into Station Master with attribution where required. Do not import the sibling repository at runtime, add it as a submodule, or copy its transcription/audio/chat features.
|
||||
|
||||
Retain only:
|
||||
|
||||
- Jitsi configuration parsing
|
||||
- connection/conference lifecycle
|
||||
- lobby handling
|
||||
- reconnect classification/backoff
|
||||
- generated-display track creation
|
||||
- generated-display cleanup and republishing
|
||||
- normalized state/error events
|
||||
- minimal control protocol
|
||||
|
||||
Pin the known working `lib-jitsi-meet` release:
|
||||
|
||||
```text
|
||||
v2192.0.0+d6f3312f
|
||||
```
|
||||
|
||||
Add `ws` for the Node control broker. Do not add Playwright.
|
||||
|
||||
### Agent page
|
||||
|
||||
`display-agent.html` must:
|
||||
|
||||
1. Validate its opaque session ID and publisher token from the URL fragment.
|
||||
2. Connect to `/api/display/control`.
|
||||
3. Register as the engine for exactly one session.
|
||||
4. Wait for a supervisor command before joining Jitsi.
|
||||
5. Connect to the public display SSE using the supplied view token.
|
||||
6. Render the same common-board canvas as the manual page.
|
||||
7. Capture the canvas stream at 10 fps.
|
||||
8. Join Jitsi and publish it as a desktop video track.
|
||||
9. Report normalized lifecycle state over the control channel.
|
||||
10. Leave and stop all tracks on supervisor command or `pagehide`.
|
||||
|
||||
Meeting server, room, XMPP configuration, and view token are delivered over the control WebSocket, not placed in query parameters.
|
||||
|
||||
### Jitsi publishing
|
||||
|
||||
Use:
|
||||
|
||||
```ts
|
||||
canvas.captureStream(10)
|
||||
JitsiMeetJS.createLocalTracksFromMediaStreams([{
|
||||
mediaType: 'video',
|
||||
sourceType: 'generated',
|
||||
stream,
|
||||
track: stream.getVideoTracks()[0],
|
||||
videoType: 'desktop'
|
||||
}])
|
||||
```
|
||||
|
||||
Require exactly one generated video track. Dispose any unexpected auxiliary tracks.
|
||||
|
||||
Wait for the first video frame before publishing and report a diagnostic if it does not arrive. Do not automatically recycle a healthy track merely because a remote participant initially sees a blank publication; the existing harness observed occasional first-publication blankness on the Jitsi side.
|
||||
|
||||
On reconnect:
|
||||
|
||||
- retain the program-owned canvas stream
|
||||
- remove/dispose the stale Jitsi local track
|
||||
- reconnect and rejoin
|
||||
- create a fresh Jitsi wrapper track around a clone of the retained stream
|
||||
- republish it
|
||||
|
||||
### Jitsi initialization and privacy
|
||||
|
||||
Initialize with:
|
||||
|
||||
```ts
|
||||
JitsiMeetJS.init({
|
||||
disableAudioLevels: true,
|
||||
enableAnalyticsLogging: false,
|
||||
disableThirdPartyRequests: true
|
||||
});
|
||||
```
|
||||
|
||||
The pinned library declarations confirm `disableThirdPartyRequests` is supported.
|
||||
|
||||
Do not initialize microphones, cameras, remote audio sinks, chat, TTS, STT, analytics, or rtcstats endpoints.
|
||||
|
||||
Before release, capture browser network destinations during a live session and verify that traffic is limited to:
|
||||
|
||||
- Station Master loopback/server endpoints
|
||||
- the configured Jitsi deployment and its advertised media infrastructure
|
||||
|
||||
Unexpected telemetry destinations fail acceptance.
|
||||
|
||||
### Meeting states
|
||||
|
||||
Handle these explicitly:
|
||||
|
||||
- `waiting-for-admission`: the participant joined a lobby and is waiting for a moderator.
|
||||
- `waiting-for-moderator`: the guest cannot create the room because no authenticated moderator has opened it.
|
||||
- `reconnecting`: a previously joined publisher lost its connection and is retrying.
|
||||
- `failed`: malformed configuration, exhausted retry budget, unrecoverable Jitsi error, or repeated browser failure.
|
||||
|
||||
`conference.authenticationRequired` may arrive asynchronously as a conference error after the initial join command appears successful. Handle both synchronous and event paths.
|
||||
|
||||
For waiting-for-moderator:
|
||||
|
||||
- leave/disconnect the failed attempt
|
||||
- retry every 8 seconds
|
||||
- stop after `JITSI_WAIT_FOR_MODERATOR_SECONDS`, default 600
|
||||
- immediately continue when a human moderator opens the meeting
|
||||
|
||||
For lobby admission, remain connected until admitted, stopped, or the configured join deadline expires.
|
||||
|
||||
### Tests
|
||||
|
||||
Port/adapt the sibling repository’s proven tests for:
|
||||
|
||||
- generated-display track contract
|
||||
- lifecycle transitions
|
||||
- lobby state
|
||||
- asynchronous `authenticationRequired`
|
||||
- reconnect classification
|
||||
- generated-display republish
|
||||
- cleanup after publish failure
|
||||
- stale callbacks from an old connection
|
||||
- initialization privacy flags
|
||||
- no audio/camera track creation
|
||||
|
||||
## Step 6 — Chromium publisher supervisor
|
||||
|
||||
### Process model
|
||||
|
||||
Create one Chromium child process per published game.
|
||||
|
||||
Do not share one Chromium process across games. Per-game processes provide crash isolation, simple lifecycle ownership, and match the production-proven Jitsi Transcription design.
|
||||
|
||||
Default publisher capacity to one:
|
||||
|
||||
```text
|
||||
JITSI_MAX_PUBLISHERS=1
|
||||
```
|
||||
|
||||
Games beyond capacity enter `queued` in creation order. Make the cap configurable only after measuring CPU and memory on target Station Master hardware.
|
||||
|
||||
### Browser launch
|
||||
|
||||
Find Chromium using:
|
||||
|
||||
1. `CHROME_BIN`
|
||||
2. `/usr/bin/chromium`
|
||||
3. `/usr/bin/chromium-browser`
|
||||
4. `/usr/bin/google-chrome`
|
||||
|
||||
Use a unique temporary user-data directory per publisher and remove it after exit.
|
||||
|
||||
Launch with the StartOS-proven flags:
|
||||
|
||||
```text
|
||||
--headless=new
|
||||
--no-sandbox
|
||||
--disable-dev-shm-usage
|
||||
--autoplay-policy=no-user-gesture-required
|
||||
--use-fake-device-for-media-stream
|
||||
--use-fake-ui-for-media-stream
|
||||
--disable-background-timer-throttling
|
||||
--disable-renderer-backgrounding
|
||||
--disable-backgrounding-occluded-windows
|
||||
```
|
||||
|
||||
`--no-sandbox` is acceptable only inside the existing StartOS container boundary and because Chromium loads the Station Master-owned loopback agent page.
|
||||
|
||||
Filter noisy Chromium stderr, but retain messages matching fatal conditions, renderer crashes, out-of-memory errors, and “Aw, Snap”.
|
||||
|
||||
### Control protocol
|
||||
|
||||
Use a versioned, session-keyed JSON protocol over `/api/display/control`.
|
||||
|
||||
Registration includes:
|
||||
|
||||
- protocol version
|
||||
- role `engine`
|
||||
- session ID
|
||||
- publisher token
|
||||
|
||||
The broker must:
|
||||
|
||||
- validate every message
|
||||
- limit payloads to 64 KiB
|
||||
- disable per-message compression
|
||||
- route commands/events only to the registered session
|
||||
- allow a newer engine to supersede only the same session
|
||||
- reject client/engine role changes on an established socket
|
||||
- clear pending commands when an engine disconnects
|
||||
- reconnect the agent-side WebSocket every two seconds until stopped
|
||||
|
||||
Public frames remain on SSE and never traverse this control protocol.
|
||||
|
||||
### Lifecycle and recovery
|
||||
|
||||
Supervisor flow:
|
||||
|
||||
1. Allocate capacity.
|
||||
2. Spawn Chromium.
|
||||
3. Wait for authenticated engine registration.
|
||||
4. Send Jitsi join configuration.
|
||||
5. Wait for joined/admitted state.
|
||||
6. Command generated-display publication.
|
||||
7. Monitor process, control socket, and Jitsi state.
|
||||
8. Gracefully stop on game completion, server shutdown, or administrative stop.
|
||||
|
||||
For unexpected Chromium exit during an active game:
|
||||
|
||||
- mark `reconnecting`
|
||||
- clean the old profile
|
||||
- relaunch with delays of 1, 2, 4, 8, and 16 seconds
|
||||
- reset the consecutive-failure count after five stable minutes
|
||||
- enter `failed` after five consecutive launch/registration failures
|
||||
- keep the underlying game and browser display operational
|
||||
|
||||
### Graceful teardown
|
||||
|
||||
On stop:
|
||||
|
||||
1. Send the engine a leave command.
|
||||
2. Wait up to five seconds for confirmation.
|
||||
3. Send Chromium `SIGTERM`.
|
||||
4. Wait up to three additional seconds.
|
||||
5. Use `SIGKILL` only if it remains alive.
|
||||
6. Remove the temporary profile.
|
||||
7. Release publisher capacity.
|
||||
|
||||
Clean leave matters because Jitsi may show a stale participant for 30–120 seconds after abrupt termination. The board does not consume remote audio, so these ghosts are cosmetic, but duplicate meeting participants remain undesirable.
|
||||
|
||||
Publish the final game state for a five-minute completion grace period, then leave the meeting. Server shutdown bypasses this grace period and leaves immediately.
|
||||
|
||||
### Tests
|
||||
|
||||
Use fake child processes and fake control sockets to test:
|
||||
|
||||
- exact required Chromium flags
|
||||
- binary discovery
|
||||
- profile isolation and cleanup
|
||||
- capacity queue ordering
|
||||
- engine registration authentication
|
||||
- per-session supersession
|
||||
- command timeout and disconnection
|
||||
- crash relaunch backoff
|
||||
- retry exhaustion
|
||||
- graceful leave before termination
|
||||
- forced kill fallback
|
||||
- publisher failure not affecting the game session
|
||||
|
||||
## Step 7 — Configuration, lifecycle, packaging, and observability
|
||||
|
||||
### Configuration
|
||||
|
||||
Support:
|
||||
|
||||
```text
|
||||
JITSI_SERVER_URL
|
||||
JITSI_GUEST_DOMAIN
|
||||
JITSI_SERVICE_URL
|
||||
JITSI_XMPP_DOMAIN
|
||||
JITSI_MUC_DOMAIN
|
||||
JITSI_FORCE_JVB=false
|
||||
JITSI_MAX_PUBLISHERS=1
|
||||
JITSI_WAIT_FOR_MODERATOR_SECONDS=600
|
||||
JITSI_JOIN_TIMEOUT_SECONDS=600
|
||||
JITSI_FINISHED_GRACE_SECONDS=300
|
||||
CHROME_BIN
|
||||
```
|
||||
|
||||
Require `JITSI_SERVER_URL` to be an HTTP(S) origin without credentials, path, query, or fragment.
|
||||
|
||||
Default the XMPP WebSocket to:
|
||||
|
||||
```text
|
||||
wss://<jitsi-host>/xmpp-websocket
|
||||
```
|
||||
|
||||
Default MUC to `conference.<xmpp-domain>`. Keep explicit overrides for self-hosted deployments.
|
||||
|
||||
If `JITSI_SERVER_URL` is absent:
|
||||
|
||||
- browser common-board display remains enabled
|
||||
- Jitsi meeting URL and publisher are disabled
|
||||
- game creation and play remain unaffected
|
||||
|
||||
JWT/authenticated publisher support is out of scope for the first version. Authenticated-room deployments rely on a human moderator opening the room and the publisher’s waiting-for-moderator retry.
|
||||
|
||||
### Session integration
|
||||
|
||||
Create display metadata when the lobby starts a game.
|
||||
|
||||
Return the meeting and display links to every authenticated player. All players receive the same links.
|
||||
|
||||
On server startup:
|
||||
|
||||
- load active game saves
|
||||
- load or migrate display metadata
|
||||
- rebuild current public snapshots
|
||||
- queue publishers only for active games
|
||||
- do not automatically republish completed games
|
||||
|
||||
On SIGTERM, including StartOS backup shutdown:
|
||||
|
||||
- stop accepting new publisher work
|
||||
- command every engine to leave
|
||||
- terminate browsers
|
||||
- then close HTTP/control services
|
||||
|
||||
### Health and logs
|
||||
|
||||
Health must distinguish:
|
||||
|
||||
- game server availability
|
||||
- common display availability
|
||||
- Jitsi configuration present
|
||||
- Chromium available
|
||||
- publishers active/queued/failed
|
||||
|
||||
Do not report Jitsi publishing as healthy merely because the supervisor is running.
|
||||
|
||||
Use structured logs containing:
|
||||
|
||||
- game/session ID
|
||||
- publisher state transition
|
||||
- safe Jitsi room identifier
|
||||
- browser exit code/signal
|
||||
- retry attempt
|
||||
- sanitized error category
|
||||
|
||||
Exclude all tokens, full control frames, player private state, query strings, and browser profile paths.
|
||||
|
||||
### Dependencies and packaging
|
||||
|
||||
Add runtime dependencies:
|
||||
|
||||
- the pinned `lib-jitsi-meet` release
|
||||
- `ws`
|
||||
|
||||
Add Chromium and `tini` to the Station Master runtime image or companion StartOS packaging repository.
|
||||
|
||||
Use `tini` as PID 1 so terminated Chromium children are reaped.
|
||||
|
||||
Visual-only Station Master publishing does not require:
|
||||
|
||||
- PulseAudio
|
||||
- Xvfb
|
||||
- xauth
|
||||
- ffmpeg
|
||||
- Playwright browsers
|
||||
- CDP tooling
|
||||
|
||||
Run the service as a non-root application user. Chromium still receives `--no-sandbox` because the StartOS subcontainer does not grant the kernel capabilities required by Chromium’s internal sandbox.
|
||||
|
||||
Do not raise the package RAM requirement based solely on the Jitsi Transcription measurements. Measure the combined Station Master server plus publisher on actual target hardware first.
|
||||
|
||||
## End-to-end test plan
|
||||
|
||||
### Automated tests
|
||||
|
||||
Run:
|
||||
|
||||
- Station Master typecheck
|
||||
- all existing engine/server/web tests
|
||||
- public-projection and leak tests
|
||||
- display delta/reconstruction tests
|
||||
- HTTP/SSE authentication tests
|
||||
- renderer lifecycle tests
|
||||
- control-protocol tests
|
||||
- Jitsi adapter tests with a fake runtime
|
||||
- Chromium supervisor tests
|
||||
- persistence migration tests
|
||||
|
||||
### Local integration
|
||||
|
||||
With a local or test Jitsi deployment:
|
||||
|
||||
1. Start a two-player game with one bot.
|
||||
2. Open the manual display and both player screens.
|
||||
3. Confirm human moves update all three.
|
||||
4. Confirm bot moves appear as distinct ordered animations.
|
||||
5. Join the Jitsi meeting from another browser.
|
||||
6. Confirm the Station Master board is published as a desktop share.
|
||||
7. Force an XMPP/media disconnect.
|
||||
8. Confirm reconnect and display-track republish.
|
||||
9. Stop the game/server and confirm the publisher leaves.
|
||||
|
||||
### Authenticated deployment
|
||||
|
||||
On a Jitsi deployment where guests cannot create rooms:
|
||||
|
||||
1. Start the Station Master game before opening the meeting.
|
||||
2. Confirm publisher state becomes `waiting-for-moderator`.
|
||||
3. Open the meeting as a moderator.
|
||||
4. Confirm the publisher joins on the next retry.
|
||||
5. If lobby is enabled, confirm `waiting-for-admission` until admitted.
|
||||
6. Confirm neither state is reported as an immediate terminal failure.
|
||||
|
||||
### Privacy verification
|
||||
|
||||
Capture:
|
||||
|
||||
- raw display SSE
|
||||
- rendered canvas screenshots
|
||||
- control WebSocket messages
|
||||
- Jitsi network destinations
|
||||
- server logs
|
||||
|
||||
Verify that none contains:
|
||||
|
||||
- card identities from hands
|
||||
- objectives
|
||||
- player-only prompts or moves
|
||||
- private draw identities
|
||||
- seed
|
||||
- view/publisher tokens in logs
|
||||
- unintended third-party telemetry
|
||||
|
||||
### Soak and target hardware
|
||||
|
||||
Run at least a two-hour Station Master integration soak with:
|
||||
|
||||
- continual public-board updates
|
||||
- human and bot moves
|
||||
- two forced connection drops
|
||||
- one forced Chromium termination
|
||||
- clean service shutdown
|
||||
|
||||
Record:
|
||||
|
||||
- container RSS
|
||||
- Chromium RSS
|
||||
- CPU during idle and animation bursts
|
||||
- Jitsi reconnect time
|
||||
- display queue depth
|
||||
- dropped SSE clients
|
||||
- stale meeting-participant duration after graceful and forced exits
|
||||
|
||||
The sibling repository’s four-hour run validates the underlying headless Jitsi approach, but Station Master still needs this integration-specific measurement.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
The feature is complete when:
|
||||
|
||||
- Every player can open one shared browser display.
|
||||
- The same display is visible as a desktop share in the game’s Jitsi meeting.
|
||||
- Human and bot moves update that board through the same path.
|
||||
- Consecutive bot intents remain visibly distinct.
|
||||
- A reconnecting display reconstructs the latest state without replay.
|
||||
- Jitsi disconnection republishes the existing canvas stream.
|
||||
- A guest publisher waits for a moderator rather than failing immediately.
|
||||
- Browser/Jitsi failure never prevents normal game play.
|
||||
- Shutdown leaves the conference before Chromium termination.
|
||||
- No private game information appears in projection, transport, rendering, logs, or Jitsi.
|
||||
- No unexpected third-party telemetry connection is observed.
|
||||
- Chromium resource use is measured on target hardware before increasing concurrency.
|
||||
|
||||
## Assumptions and defaults
|
||||
|
||||
- The common board is a separate participant named `Station Master — Common Board`.
|
||||
- It represents the table, never a particular human or bot.
|
||||
- Jitsi is configurable and self-hosted; meet.jit.si-specific behavior is not assumed.
|
||||
- One publisher process is allowed by default.
|
||||
- A human moderator may need to open or admit the publisher.
|
||||
- Public display and normal multiplayer remain valuable and operational without Jitsi.
|
||||
- The sibling Jitsi Transcription repository is a reference implementation, not a shared runtime package.
|
||||
- The untracked Station Master harness remains research material and is not promoted wholesale into production.
|
||||
- Audio, transcription, speech, chat, camera capture, player screen sharing, and JWT publisher authentication are out of scope.
|
||||
@@ -0,0 +1,260 @@
|
||||
# Station Master — the cards as built
|
||||
|
||||
> **Generated from `src/engine/content.ts` by `scripts/build-card-reference.ts`. Do not edit by
|
||||
> hand** — `npm run build:cards` rewrites it, and `test/card-reference.test.ts` fails if this file
|
||||
> and the code disagree.
|
||||
|
||||
This is the one file in `docs/rules/` that describes the game **as it currently is**. Everything
|
||||
else in this directory is a historical record and marked as such: [`rules-v0.1.md`](rules-v0.1.md)
|
||||
transcribes the prototype PDFs, [`open-questions.md`](open-questions.md) tracks how the gaps in
|
||||
them were decided, and [`rules-v0.2.md`](rules-v0.2.md) and
|
||||
[`card-reference.md`](card-reference.md) both describe superseded card sets. Read those for the
|
||||
reasoning; read this for the numbers.
|
||||
|
||||
The engine instantiates from the same constants this is emitted from, so a disagreement between
|
||||
this page and the game is a bug in the generator, not a stale table.
|
||||
|
||||
**No card counts appear here, deliberately** (TODO #15a, Jesse 2026-08-22): the counts move with
|
||||
play balance, so a document that prints them is answering a question that will have a different
|
||||
answer next retune. Where a count matters it is a yes/no — whether the deck deals the card at
|
||||
all — which is a fact about the design rather than about the current tuning.
|
||||
|
||||
---
|
||||
|
||||
## Trains
|
||||
|
||||
12 timetabled and 10 Extras, 22 in all.
|
||||
Odd numbers run west, even run east; a pair shares a class and is the same card face in two
|
||||
directions. A Crew Tray holds four pieces and a caboose counts toward the four, which is why no
|
||||
train with a caboose carries more than three revenue cars.
|
||||
|
||||
### Timetabled
|
||||
|
||||
| # | Class | Speed | Runs | Consist | Printed rules |
|
||||
| ---: | --- | --- | --- | --- | --- |
|
||||
| 1 | Crack Limited | fast | west | 2 coaches (2 pieces) | terminals only; no switching; expedite; *"Stop at Terminals only."* |
|
||||
| 2 | Crack Limited | fast | east | 2 coaches (2 pieces) | terminals only; no switching; expedite; *"Stop at Terminals only."* |
|
||||
| 3 | Express | fast | west | 2 freight (2 pieces) | one freight per location; expedite; *"May drop or pick up one freight car at every location."* |
|
||||
| 4 | Express | fast | east | 2 freight (2 pieces) | one freight per location; expedite; *"May drop or pick up one freight car at every location."* |
|
||||
| 5 | The Sparrow | fast | west | 3 coaches (3 pieces) | no switching; expedite |
|
||||
| 6 | The Sparrow | fast | east | 3 coaches (3 pieces) | no switching; expedite |
|
||||
| 7 | Local | slow | west | 1 freight + 1 coach (2 pieces) | coach stays on station track; *"Maximum one freight, one coach."* |
|
||||
| 8 | Local | slow | east | 1 freight + 1 coach (2 pieces) | coach stays on station track; *"Maximum one freight, one coach."* |
|
||||
| 9 | Heavy Freight | slow | west | 3 freight + 1 caboose (4 pieces) | — |
|
||||
| 10 | Heavy Freight | slow | east | 3 freight + 1 caboose (4 pieces) | — |
|
||||
| 11 | Drag Freight | slow | west | 2 freight + 1 caboose (3 pieces) | — |
|
||||
| 12 | Drag Freight | slow | east | 2 freight + 1 caboose (3 pieces) | — |
|
||||
|
||||
### Extras
|
||||
|
||||
| # | Class | Speed | Runs | Consist | Printed rules |
|
||||
| ---: | --- | --- | --- | --- | --- |
|
||||
| X13 | Appleseed Extra | slow | player's choice | 3 freight + 1 caboose (4 pieces), empties only | drop only; *"May drop MTs but not pick up anything."* |
|
||||
| X14 | Fruit Growers Express | fast | player's choice | 2 reefers + 1 caboose (3 pieces) | expedite; *"Reefers only. May pick up one extra loaded reefer."* |
|
||||
| X15 | Yard Xfer | slow | player's choice | 2 freight + 1 caboose (3 pieces) | — |
|
||||
| X16 | Light Engine Move | fast | player's choice | engine only | no switching; *"No cars at all."* |
|
||||
| X17 | Campaign Train | fast | player's choice | 1 coach (1 piece) | no switching; stop then expedite; stop earns point; must run loaded; *"One turn at station (speeches) then expedite. Earns a point per Office Area if the candidate is aboard."* |
|
||||
| X18 | Circus Train | slow | player's choice | 2 freight + 1 coach + 1 caboose (4 pieces) | no switching; stop earns point; must run loaded; *"One turn stopped in an Office Area (circus set-up) earns 1 point, once per Area, if fully loaded."* |
|
||||
| X19 | Military Train | slow | player's choice | 1 freight + 2 coaches (3 pieces) | no switching; no passenger work; expedite; must run loaded; *"Troops and materiel: runs loaded where the yard can supply it."* |
|
||||
| X20 | Director's private car | slow | player's choice | 2 freight + 1 coach (3 pieces) | no passenger work |
|
||||
| X21 | Freight Extra | slow | player's choice | 3 freight + 1 caboose (4 pieces) | — |
|
||||
| X22 | Pee-Dee | slow | player's choice | 1 caboose (1 piece) | pick up empties only; *"Per-diem train. May only pick up MTs."* |
|
||||
|
||||
---
|
||||
|
||||
## Mainline cards
|
||||
|
||||
A card is divided into **regions**, and a train advances one region per Stage — so the regions a
|
||||
card prints are what it costs to cross. Where a train *enters* is what the rules move: a fast
|
||||
train on Hilly, a Heavy Grade with Helpers, or a card whose back region is a siding rather than
|
||||
part of the road all change the entry point rather than the card's length.
|
||||
|
||||
| Card | Regions | Default entry | Fast / slow entry | Trains may pass | Sorts cars |
|
||||
| --- | ---: | ---: | --- | :---: | :---: |
|
||||
| Plains | 1 | 0 | — | — | — |
|
||||
| Curves | 2 | 0 | — | — | — |
|
||||
| Hilly | 2 | 0 | 1 / 0 | — | — |
|
||||
| Heavy Grade | 3 | 0 | — | — | — |
|
||||
| Double Track | 1 | 0 | — | yes | — |
|
||||
| Uncontrolled Siding | 2 | 1 | — | — | — |
|
||||
| Tunnel | 2 | 0 | — | — | — |
|
||||
| Trestle | 1 | 0 | — | — | — |
|
||||
| Interchange | 2 | 1 | — | — | yes |
|
||||
|
||||
The Mainline deck is 10 cards; the two Division Points are the fixed ends of
|
||||
the Division and are not dealt. What each card does, in the words the game uses on screen:
|
||||
|
||||
- **Plains** — 1 region — one Stage each. · 1 Stage for every train — the printed speed is scenery. · One train at a time — anything following has to wait for it to clear.
|
||||
- **Curves** — 2 regions — one Stage each. · 2 Stages for every train — the printed speed is scenery. · One train at a time — anything following has to wait for it to clear.
|
||||
- **Hilly** — 2 regions — one Stage each. · This card reads the train's FAST/SLOW rating: a fast train starts further along and crosses in 1 Stage, a slow one in 2 Stages. No other card cares which it is. · One train at a time — anything following has to wait for it to clear.
|
||||
- **Heavy Grade** — 3 regions — one Stage each. · A grade, climbing eastward. 3 Stages to climb it and 3 Stages to run down, before help. Helpers start an UPHILL train a region further on; Brakeman does the same DOWNHILL and Airbrakes another again, and Airbrakes cannot be played without Brakeman. Never less than one Stage. · One train at a time — anything following has to wait for it to clear.
|
||||
- **Double Track** — 1 region — one Stage each. · 1 Stage for every train — the printed speed is scenery. · TRAINS MAY PASS — two trains may stand on this card at once, so a following train is not held behind a slower one.
|
||||
- **Uncontrolled Siding** — 2 regions — one Stage each. · A train with the card to itself starts past the back region and is across in 1 Stage. · UNCONTROLLED SIDING — arrive to find a train already here and you take the siding, a region behind it. You are not in the same place, so you do not run into it; it costs you the extra Stage instead. · One train at a time — anything following has to wait for it to clear.
|
||||
- **Tunnel** — 2 regions — one Stage each. · 2 Stages for every train — the printed speed is scenery. · One train at a time — anything following has to wait for it to clear.
|
||||
- **Trestle** — 1 region — one Stage each. · 1 Stage for every train — the printed speed is scenery. · One train at a time — anything following has to wait for it to clear.
|
||||
- **Interchange** — 2 regions — one Stage each. · A train with the card to itself starts past the back region and is across in 1 Stage. · An Extra beginning its run here starts in the back region and takes the extra Stage. · One train at a time — anything following has to wait for it to clear. · Cars may be sorted into any new order here.
|
||||
|
||||
---
|
||||
|
||||
## Office cards
|
||||
|
||||
Upgrades are strictly sequential — no skipping a tier — so a Terminal needs all three cards in
|
||||
order. Green slots are outbound passengers, red are inbound, and the design gives slots **equal**
|
||||
to Porters rather than one more.
|
||||
|
||||
| Office | Control point | Passenger facility | A/D tracks | Porters | Green | Red |
|
||||
| --- | :---: | :---: | ---: | ---: | ---: | ---: |
|
||||
| Whistle Post | — | — | 1 | 0 | 0 | 0 |
|
||||
| Depot | yes | yes | 2 | 1 | 1 | 1 |
|
||||
| Station | yes | yes | 3 | 2 | 2 | 2 |
|
||||
| Terminal | yes | yes | 4 | 3 | 3 | 3 |
|
||||
|
||||
Whistle Posts are a fixed supply of 4 outside the deck, and Limits signs a
|
||||
supply of 8.
|
||||
|
||||
---
|
||||
|
||||
## Freight facilities
|
||||
|
||||
Each lists the car types it works, which way its traffic flows, and the industries it may not sit
|
||||
beside. **Every lockout pair is a producer and the consumer of the same commodity** — you may
|
||||
build one end of a chain or the other, never both, which is what forces traffic to run between
|
||||
districts rather than in circles inside one. No two of the same industry may share an Office Area,
|
||||
and that rule is enforced for every kind rather than repeated in each row.
|
||||
|
||||
| Industry | Cars | Flow | Green | Red | Laborers | Locked out with |
|
||||
| --- | --- | --- | ---: | ---: | ---: | --- |
|
||||
| Freight House | boxcar | both | 1 | 1 | 1 | Grocer's Warehouse |
|
||||
| Mine Tipple | hopper | outbound | 1 | 0 | 1 | Power Plant |
|
||||
| Refinery | tank | outbound | 1 | 0 | 1 | Power Plant |
|
||||
| Power Plant | hopper, tank | inbound | 0 | 1 | 1 | Mine Tipple, Refinery |
|
||||
| Packing Sheds | reefer | outbound | 1 | 0 | 1 | Grocer's Warehouse |
|
||||
| Grocer's Warehouse | boxcar, reefer | inbound | 0 | 1 | 1 | Packing Sheds, Freight House |
|
||||
|
||||
---
|
||||
|
||||
## Modifier cards
|
||||
|
||||
Each sits beside a host and raises one of its capacities. `office` as a host means any Passenger
|
||||
Facility — so a modifier that adds a green slot to an Office adds nothing to a Whistle Post, which
|
||||
is not one.
|
||||
|
||||
| Modifier | Hosts | +Green | +Red | +Laborers | +Porters |
|
||||
| --- | --- | ---: | ---: | ---: | ---: |
|
||||
| Waiting area | any Passenger Facility | 1 | — | — | 1 |
|
||||
| Restaurant | any Passenger Facility | 1 | — | — | 1 |
|
||||
| Hotel | any Passenger Facility | 1 | — | — | 1 |
|
||||
| Truck dock | Freight House, Packing Sheds, Grocer's Warehouse | — | 1 | — | — |
|
||||
| Railroad Express Agency | Freight House | 1 | — | 1 | — |
|
||||
| Forklifts | Freight House, Packing Sheds | 1 | — | 1 | — |
|
||||
| Prep Plant | Mine Tipple | 1 | — | 1 | — |
|
||||
| Coal Piles | Mine Tipple | 1 | — | 1 | — |
|
||||
| Conveyor Belts | Mine Tipple | 1 | — | 1 | — |
|
||||
| Pipelines | Refinery | 1 | — | 1 | — |
|
||||
| Oil Depot | Refinery | 1 | — | 1 | — |
|
||||
| Viscosity breakers | Refinery | 1 | — | 1 | — |
|
||||
| Transmission lines | Power Plant | — | — | 1 | — |
|
||||
| Rotary Dumps | Power Plant | — | — | 1 | — |
|
||||
| Steam Turbines | Power Plant | — | — | 1 | — |
|
||||
| Ice House | Packing Sheds, Grocer's Warehouse | 1 | — | 1 | — |
|
||||
| Local small groceries | Grocer's Warehouse | — | — | 1 | — |
|
||||
|
||||
---
|
||||
|
||||
## Track cards
|
||||
|
||||
Track is **in the Home Office deck** and is drawn and played like any other card — not a separate
|
||||
per-player supply. Operational Rail is the flag that says a train may stop on the card; a turnout
|
||||
may be run through but not stopped on.
|
||||
|
||||
| Track | Geometry | Hand | Operational rail | Move cost | Dealt |
|
||||
| --- | --- | --- | :---: | ---: | :---: |
|
||||
| Straight track | straight | none | yes | 1 | yes |
|
||||
| Curved track (right) | curved | right | yes | 1 | yes |
|
||||
| Curved track (left) | curved | left | yes | 1 | yes |
|
||||
| Sharp Curved Track (right) | sharpCurved | right | yes | 2 | no |
|
||||
| Sharp Curved Track (left) | sharpCurved | left | yes | 2 | no |
|
||||
| Turnout (right) | turnout | right | — | 1 | yes |
|
||||
| Turnout (left) | turnout | left | — | 1 | yes |
|
||||
|
||||
A row marked "no" is a shape the engine understands but the deck does not currently print.
|
||||
|
||||
---
|
||||
|
||||
## Enhancements
|
||||
|
||||
The column that only the implementation can fill in: **whether the printed effect actually
|
||||
resolves yet.** `live` is read during play; `dormantSolo` is implemented at the point of attack
|
||||
but the attack is an opponent-directed card held out of every deck, so nothing reaches it in a
|
||||
solitaire game; `unbuilt` means the effect is recorded and nothing reads it. A transcription
|
||||
cannot carry this column, which is the argument for generating the page rather than writing it.
|
||||
|
||||
| Enhancement | Placement | Requires | Effect resolves |
|
||||
| --- | --- | --- | :---: |
|
||||
| Interlocking | runningTrackStraight | — | **live** |
|
||||
| Facing Point Locks | onCard | interlocking in the district | **dormantSolo** |
|
||||
| Yard office | secondaryTrackStraight | — | **live** |
|
||||
| Small yard | secondaryTrackStraight | — | **live** |
|
||||
| Water column | runningTrackStraight | — | **dormantSolo** |
|
||||
| Overpass | onCard | — | **unbuilt** |
|
||||
| Telegraph | runningTrackStraight | — | **live** |
|
||||
| Telephone | onCard | telegraph on the same card | **live** |
|
||||
| Radio | onCard | telephone on the same card | **live** |
|
||||
| ABS Signals | mainlineCard | — | **live** |
|
||||
|
||||
---
|
||||
|
||||
## Opponent-directed cards, and what answers them
|
||||
|
||||
**None of these is dealt in any deck today.** A card that can only be played at another player
|
||||
has no legal target in a solitaire game, and a defence with nothing to defend against is as dead
|
||||
a draw as the attack — so both halves are held out until the attacks are implemented. They are
|
||||
listed because they are the design, and because what a defence answers is the only record of why
|
||||
it exists.
|
||||
|
||||
### Action cards — opponent-directed
|
||||
|
||||
| Card | Played on | Effect | Answers |
|
||||
| --- | --- | --- | --- |
|
||||
| Derail | a moving train in the Local Phase | That train must stop for the remainder of the turn. | — |
|
||||
| Broken coupler | a moving train in the Mainline Phase | That train must stop and not move. | — |
|
||||
| Railroad crossing | any Secondary Track Straight | May not be used as a stop point for switching. May not become an Industry. | — |
|
||||
| Per Diem inventory | another player | Lose one point per 2 empty cars on Secondary Tracks. | — |
|
||||
| Demurrage charge | another player | Lose one point per 2 loaded freight cars on Secondary Tracks. | — |
|
||||
| Customer complaints | another player | Lose one point per 2 coaches in loading boxes. | — |
|
||||
| Vandalism | another player | A train passing a Hobo Jungle has a boxcar looted (converted to empty). | — |
|
||||
| Hotbox | another player | A train just arrived must set one car (chooser’s pick) onto Secondary Track until it departs. | — |
|
||||
| Outlawed | another player | A train just arrived may not depart for one turn — the crew’s hours have expired. | — |
|
||||
|
||||
### Space-use cards — opponent-directed
|
||||
|
||||
| Card | Played on | Effect | Answers |
|
||||
| --- | --- | --- | --- |
|
||||
| Bean house | adjacent to any straight, curve, turnout, Limit | Burns tablespace. | — |
|
||||
| Flop house | adjacent to any straight, curve, turnout | Burns tablespace. | — |
|
||||
| Watertower | adjacent to any straight, turnout on Running Track | Burns tablespace. | — |
|
||||
| Hobo Jungle | adjacent to any straight, turnout, Limit on Running Track | Burns tablespace. Vandalism can loot a boxcar passing it. | — |
|
||||
| Section House | adjacent to any straight, curve, turnout | Burns tablespace. | — |
|
||||
| City blocks | adjacent to any straight, curve, turnout, Limit | Burns tablespace. | — |
|
||||
| Engine Shops | adjacent to any straight, curve, turnout | Burns tablespace. | — |
|
||||
| Tenderloin District | adjacent to any straight, curve, turnout, Limit | Burns tablespace. | — |
|
||||
| Engineer cemetery | adjacent to any straight, curve, turnout, Limit | Burns tablespace. | — |
|
||||
|
||||
### Maneuver cards
|
||||
|
||||
| Card | Played on | Effect | Answers |
|
||||
| --- | --- | --- | --- |
|
||||
| Red Flags | any time | A stopped train is prevented from being hit; the approaching train is prevented from moving. | — |
|
||||
| Flying Switch | any time | Break a cut of cars away from behind the engine and roll them into an industry. | — |
|
||||
| Poling | any time | TBD in the source. | — |
|
||||
|
||||
Mainline modifier cards, for completeness — these ARE dealt:
|
||||
|
||||
| Card | Played on | Effect | Answers |
|
||||
| --- | --- | --- | --- |
|
||||
| Brakeman | a GRADE Mainline card | Faster passage downhill. | — |
|
||||
| Airbrakes | a GRADE Mainline card | Faster passage downhill. Brakeman must be in effect. | — |
|
||||
| Helpers | a GRADE Mainline card | Faster passage uphill. | — |
|
||||
| Realignment | a Mainline card | Convert one Mainline type to another. Not while a train is on it. | — |
|
||||
| Facing Point Locks | adjacent to Interlocking | Prevents Derail being played on you. | Derail |
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
> 2026-07-30 in `docs/Deck cards2.xlsx`, `Trains3.pdf` and `Mainline Cards.pdf`, and is transcribed
|
||||
> in `src/engine/content.ts`. See [`implications.md`](implications.md) for the full comparison.
|
||||
>
|
||||
> **For what the cards say today, read [`as-built.md`](as-built.md)** — generated from
|
||||
> `content.ts` and checked against it by the test suite, so it cannot fall behind the way this file
|
||||
> did. For several releases `content.ts` named *this* page as the current reference while the banner
|
||||
> here said otherwise, and a reader following the code landed on the v0.4.5 deck.
|
||||
>
|
||||
> Kept for the reasoning it records — the economy analysis in §7 was how we knew what questions to
|
||||
> ask the design. **Do not use its numbers.**
|
||||
|
||||
|
||||
+4
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "station-master",
|
||||
"version": "0.7.6",
|
||||
"version": "0.7.9.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Station Master — a railroad operations game",
|
||||
@@ -9,11 +9,12 @@
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"pretest": "node scripts/build-web.ts",
|
||||
"pretest": "tsc --noEmit && node scripts/build-web.ts",
|
||||
"test": "node --test test/*.test.ts test/**/*.test.ts",
|
||||
"build:web": "node scripts/build-web.ts",
|
||||
"serve:web": "node scripts/build-web.ts && npx --yes http-server dist -p 8080 -c-1",
|
||||
"deploy:web": "node scripts/deploy-web.ts"
|
||||
"deploy:web": "node scripts/deploy-web.ts",
|
||||
"build:cards": "node scripts/build-card-reference.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^26.1.2",
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
/**
|
||||
* Generate `docs/rules/as-built.md` — what the cards say, as the code actually has them.
|
||||
*
|
||||
* WHY THIS IS GENERATED RATHER THAN WRITTEN.
|
||||
*
|
||||
* Every other file in `docs/rules/` is a historical record and says so: `rules-v0.1.md` is a
|
||||
* faithful transcription of the prototype PDFs, `open-questions.md` is the gap tracker,
|
||||
* `rules-v0.2.md` and `card-reference.md` both carry SUPERSEDED banners. None of them describes the
|
||||
* game as built, and none of them should be edited to — the record is worth more intact than
|
||||
* patched.
|
||||
*
|
||||
* So there was no current reference at all, and `content.ts` spent several releases pointing at
|
||||
* `card-reference.md` as "the place that now carries what the cards say" while that file's own
|
||||
* banner said "do not use its numbers". A reader following the code's advice landed on the v0.4.5
|
||||
* deck: twelve numbered trains, "3 / 4 Mail-Express, 3 coaches", against a `content.ts` whose train
|
||||
* 3 is the Express with two freight cars and a per-location freight rule.
|
||||
*
|
||||
* A HAND-WRITTEN REPLACEMENT WOULD HAVE DRIFTED THE SAME WAY, and for the same reason: nothing
|
||||
* fails when a table falls behind a constant. So the reference is emitted from the same exported
|
||||
* catalogues the engine instantiates from, and `test/card-reference.test.ts` re-runs this generator
|
||||
* and asserts the checked-in file matches byte for byte. Change a card face and the suite goes red
|
||||
* until the doc is regenerated — which is the only mechanism this project has found that keeps a
|
||||
* document honest.
|
||||
*
|
||||
* `npm run build:cards` writes it. Nothing at runtime reads it; it is for people.
|
||||
*/
|
||||
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
ACTION_CARDS, ALL_TRAINS, ENHANCEMENT_CARDS, ENHANCEMENT_RULES, EXTRA_TRAINS, INDUSTRY_PROFILES,
|
||||
LIMITS_SUPPLY, MAINLINE_DECK, MAINLINE_MODIFIER_CARDS, MAINLINE_PROFILES, MANEUVER_CARDS,
|
||||
MODIFIER_PROFILES, OFFICE_PROFILES, SPACE_USE_CARDS, TIMETABLED_TRAINS, TRACK_CARDS,
|
||||
WHISTLE_POST_SUPPLY, consistSize, isOpponentOnly, mainlineDescription,
|
||||
} from '../src/engine/content.ts';
|
||||
import type { ConsistSpec, SimpleCard, TrainProfile, TrainRules } from '../src/engine/content.ts';
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
/** Title Case a camelCase key, so `oneFreightPerLocation` reads as a rule rather than an identifier. */
|
||||
const words = (k: string): string => k.replace(/([A-Z])/g, ' $1').toLowerCase().trim();
|
||||
|
||||
const consistOf = (c: ConsistSpec): string => {
|
||||
const parts: string[] = [];
|
||||
if (c.freight > 0) {
|
||||
const kinds = c.freightTypes ? c.freightTypes.join(' or ') : 'freight';
|
||||
parts.push(`${c.freight} ${kinds}${c.freight === 1 ? '' : c.freightTypes ? 's' : ''}`);
|
||||
}
|
||||
if (c.coach > 0) parts.push(`${c.coach} coach${c.coach === 1 ? '' : 'es'}`);
|
||||
if (c.caboose > 0) parts.push(`${c.caboose} caboose`);
|
||||
if (!parts.length) return 'engine only';
|
||||
const n = consistSize(c);
|
||||
// "Empties only" qualifies the whole consist rather than adding to it, so it reads after the count.
|
||||
return `${parts.join(' + ')} (${n} piece${n === 1 ? '' : 's'})${c.emptiesOnly ? ', empties only' : ''}`;
|
||||
};
|
||||
|
||||
const rulesOf = (r: TrainRules): string => {
|
||||
const out: string[] = [];
|
||||
for (const [k, v] of Object.entries(r)) {
|
||||
if (k === 'note' || v === false || v === undefined) continue;
|
||||
out.push(words(k));
|
||||
}
|
||||
if (typeof r.note === 'string') out.push(`*"${r.note}"*`);
|
||||
return out.length ? out.join('; ') : '—';
|
||||
};
|
||||
|
||||
const trainRow = (t: TrainProfile): string =>
|
||||
`| ${t.isExtra ? 'X' : ''}${t.number} | ${t.name} | ${t.speed} | ` +
|
||||
`${t.direction === 'playerChoice' ? "player's choice" : t.direction} | ${consistOf(t.consist)} | ${rulesOf(t.rules)} |`;
|
||||
|
||||
const lines: string[] = [];
|
||||
const w = (s = ''): void => void lines.push(s);
|
||||
|
||||
w('# Station Master — the cards as built');
|
||||
w();
|
||||
w('> **Generated from `src/engine/content.ts` by `scripts/build-card-reference.ts`. Do not edit by');
|
||||
w('> hand** — `npm run build:cards` rewrites it, and `test/card-reference.test.ts` fails if this file');
|
||||
w('> and the code disagree.');
|
||||
w();
|
||||
w('This is the one file in `docs/rules/` that describes the game **as it currently is**. Everything');
|
||||
w('else in this directory is a historical record and marked as such: [`rules-v0.1.md`](rules-v0.1.md)');
|
||||
w('transcribes the prototype PDFs, [`open-questions.md`](open-questions.md) tracks how the gaps in');
|
||||
w('them were decided, and [`rules-v0.2.md`](rules-v0.2.md) and');
|
||||
w('[`card-reference.md`](card-reference.md) both describe superseded card sets. Read those for the');
|
||||
w('reasoning; read this for the numbers.');
|
||||
w();
|
||||
w('The engine instantiates from the same constants this is emitted from, so a disagreement between');
|
||||
w('this page and the game is a bug in the generator, not a stale table.');
|
||||
w();
|
||||
w('**No card counts appear here, deliberately** (TODO #15a, Jesse 2026-08-22): the counts move with');
|
||||
w('play balance, so a document that prints them is answering a question that will have a different');
|
||||
w('answer next retune. Where a count matters it is a yes/no — whether the deck deals the card at');
|
||||
w('all — which is a fact about the design rather than about the current tuning.');
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Trains');
|
||||
w();
|
||||
w(`${TIMETABLED_TRAINS.length} timetabled and ${EXTRA_TRAINS.length} Extras, ${ALL_TRAINS.length} in all.`);
|
||||
w('Odd numbers run west, even run east; a pair shares a class and is the same card face in two');
|
||||
w('directions. A Crew Tray holds four pieces and a caboose counts toward the four, which is why no');
|
||||
w('train with a caboose carries more than three revenue cars.');
|
||||
w();
|
||||
w('### Timetabled');
|
||||
w();
|
||||
w('| # | Class | Speed | Runs | Consist | Printed rules |');
|
||||
w('| ---: | --- | --- | --- | --- | --- |');
|
||||
for (const t of TIMETABLED_TRAINS) w(trainRow(t));
|
||||
w();
|
||||
w('### Extras');
|
||||
w();
|
||||
w('| # | Class | Speed | Runs | Consist | Printed rules |');
|
||||
w('| ---: | --- | --- | --- | --- | --- |');
|
||||
for (const t of EXTRA_TRAINS) w(trainRow(t));
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Mainline cards');
|
||||
w();
|
||||
w('A card is divided into **regions**, and a train advances one region per Stage — so the regions a');
|
||||
w('card prints are what it costs to cross. Where a train *enters* is what the rules move: a fast');
|
||||
w('train on Hilly, a Heavy Grade with Helpers, or a card whose back region is a siding rather than');
|
||||
w('part of the road all change the entry point rather than the card\'s length.');
|
||||
w();
|
||||
w('| Card | Regions | Default entry | Fast / slow entry | Trains may pass | Sorts cars |');
|
||||
w('| --- | ---: | ---: | --- | :---: | :---: |');
|
||||
for (const m of MAINLINE_PROFILES) {
|
||||
const ss = m.speedStarts ? `${m.speedStarts.fast} / ${m.speedStarts.slow}` : '—';
|
||||
w(`| ${m.name} | ${m.regions} | ${m.defaultStart} | ${ss} | ${m.trainsMayPass ? 'yes' : '—'} | ${m.sortsCars ? 'yes' : '—'} |`);
|
||||
}
|
||||
w();
|
||||
w(`The Mainline deck is ${MAINLINE_DECK.length} cards; the two Division Points are the fixed ends of`);
|
||||
w('the Division and are not dealt. What each card does, in the words the game uses on screen:');
|
||||
w();
|
||||
for (const m of MAINLINE_PROFILES) w(`- **${m.name}** — ${mainlineDescription(m.kind)}`);
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Office cards');
|
||||
w();
|
||||
w('Upgrades are strictly sequential — no skipping a tier — so a Terminal needs all three cards in');
|
||||
w('order. Green slots are outbound passengers, red are inbound, and the design gives slots **equal**');
|
||||
w('to Porters rather than one more.');
|
||||
w();
|
||||
w('| Office | Control point | Passenger facility | A/D tracks | Porters | Green | Red |');
|
||||
w('| --- | :---: | :---: | ---: | ---: | ---: | ---: |');
|
||||
for (const o of OFFICE_PROFILES) {
|
||||
w(`| ${o.name} | ${o.isControlPoint ? 'yes' : '—'} | ${o.isPassengerFacility ? 'yes' : '—'} | ` +
|
||||
`${o.adTracks} | ${o.porters} | ${o.passengerOut} | ${o.passengerIn} |`);
|
||||
}
|
||||
w();
|
||||
w(`Whistle Posts are a fixed supply of ${WHISTLE_POST_SUPPLY} outside the deck, and Limits signs a`);
|
||||
w(`supply of ${LIMITS_SUPPLY}.`);
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Freight facilities');
|
||||
w();
|
||||
w('Each lists the car types it works, which way its traffic flows, and the industries it may not sit');
|
||||
w('beside. **Every lockout pair is a producer and the consumer of the same commodity** — you may');
|
||||
w('build one end of a chain or the other, never both, which is what forces traffic to run between');
|
||||
w('districts rather than in circles inside one. No two of the same industry may share an Office Area,');
|
||||
w('and that rule is enforced for every kind rather than repeated in each row.');
|
||||
w();
|
||||
w('| Industry | Cars | Flow | Green | Red | Laborers | Locked out with |');
|
||||
w('| --- | --- | --- | ---: | ---: | ---: | --- |');
|
||||
for (const f of INDUSTRY_PROFILES) {
|
||||
const lo = f.lockouts.length
|
||||
? f.lockouts.map((k) => INDUSTRY_PROFILES.find((p) => p.kind === k)?.name ?? k).join(', ')
|
||||
: '—';
|
||||
w(`| ${f.name} | ${f.carTypes.join(', ')} | ${f.flow} | ${f.baseOut} | ${f.baseIn} | ${f.baseLoaders} | ${lo} |`);
|
||||
}
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Modifier cards');
|
||||
w();
|
||||
w('Each sits beside a host and raises one of its capacities. `office` as a host means any Passenger');
|
||||
w('Facility — so a modifier that adds a green slot to an Office adds nothing to a Whistle Post, which');
|
||||
w('is not one.');
|
||||
w();
|
||||
w('| Modifier | Hosts | +Green | +Red | +Laborers | +Porters |');
|
||||
w('| --- | --- | ---: | ---: | ---: | ---: |');
|
||||
for (const m of MODIFIER_PROFILES) {
|
||||
const hosts = m.hosts
|
||||
.map((h) => (h === 'office' ? 'any Passenger Facility' : INDUSTRY_PROFILES.find((p) => p.kind === h)?.name ?? h))
|
||||
.join(', ');
|
||||
w(`| ${m.name} | ${hosts} | ${m.addOut || '—'} | ${m.addIn || '—'} | ${m.addLoaders || '—'} | ${m.addPorters || '—'} |`);
|
||||
}
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Track cards');
|
||||
w();
|
||||
w('Track is **in the Home Office deck** and is drawn and played like any other card — not a separate');
|
||||
w('per-player supply. Operational Rail is the flag that says a train may stop on the card; a turnout');
|
||||
w('may be run through but not stopped on.');
|
||||
w();
|
||||
w('| Track | Geometry | Hand | Operational rail | Move cost | Dealt |');
|
||||
w('| --- | --- | --- | :---: | ---: | :---: |');
|
||||
for (const t of TRACK_CARDS) {
|
||||
w(`| ${t.name} | ${t.geometry} | ${t.hand} | ${t.isOperationalRail ? 'yes' : '—'} | ${t.moveCost} | ${t.copiesInDeck ? 'yes' : 'no'} |`);
|
||||
}
|
||||
w();
|
||||
w('A row marked "no" is a shape the engine understands but the deck does not currently print.');
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Enhancements');
|
||||
w();
|
||||
w('The column that only the implementation can fill in: **whether the printed effect actually');
|
||||
w('resolves yet.** `live` is read during play; `dormantSolo` is implemented at the point of attack');
|
||||
w('but the attack is an opponent-directed card held out of every deck, so nothing reaches it in a');
|
||||
w('solitaire game; `unbuilt` means the effect is recorded and nothing reads it. A transcription');
|
||||
w('cannot carry this column, which is the argument for generating the page rather than writing it.');
|
||||
w();
|
||||
w('| Enhancement | Placement | Requires | Effect resolves |');
|
||||
w('| --- | --- | --- | :---: |');
|
||||
for (const r of ENHANCEMENT_RULES) {
|
||||
const card = ENHANCEMENT_CARDS.find((c) => c.key === r.key);
|
||||
const needs = r.requiresOnSameCard
|
||||
? `${r.requiresOnSameCard} on the same card`
|
||||
: r.requiresInDistrict
|
||||
? `${r.requiresInDistrict} in the district`
|
||||
: '—';
|
||||
w(`| ${card?.name ?? r.key} | ${r.placement} | ${needs} | **${r.effect}** |`);
|
||||
}
|
||||
w();
|
||||
w('---');
|
||||
w();
|
||||
|
||||
w('## Opponent-directed cards, and what answers them');
|
||||
w();
|
||||
w('**None of these is dealt in any deck today.** A card that can only be played at another player');
|
||||
w('has no legal target in a solitaire game, and a defence with nothing to defend against is as dead');
|
||||
w('a draw as the attack — so both halves are held out until the attacks are implemented. They are');
|
||||
w('listed because they are the design, and because what a defence answers is the only record of why');
|
||||
w('it exists.');
|
||||
w();
|
||||
const pvp = (title: string, cards: readonly SimpleCard[], category: string): void => {
|
||||
w(`### ${title}${isOpponentOnly(category) ? ' — opponent-directed' : ''}`);
|
||||
w();
|
||||
w('| Card | Played on | Effect | Answers |');
|
||||
w('| --- | --- | --- | --- |');
|
||||
for (const c of cards) w(`| ${c.name} | ${c.placement} | ${c.effect} | ${c.answers ?? '—'} |`);
|
||||
w();
|
||||
};
|
||||
pvp('Action cards', ACTION_CARDS, 'action');
|
||||
pvp('Space-use cards', SPACE_USE_CARDS, 'spaceUse');
|
||||
pvp('Maneuver cards', MANEUVER_CARDS, 'maneuver');
|
||||
w('Mainline modifier cards, for completeness — these ARE dealt:');
|
||||
w();
|
||||
w('| Card | Played on | Effect | Answers |');
|
||||
w('| --- | --- | --- | --- |');
|
||||
for (const c of MAINLINE_MODIFIER_CARDS) w(`| ${c.name} | ${c.placement} | ${c.effect} | ${c.answers ?? '—'} |`);
|
||||
w();
|
||||
|
||||
writeFileSync(join(root, 'docs/rules/as-built.md'), `${lines.join('\n')}\n`);
|
||||
console.log(`built -> docs/rules/as-built.md (${lines.length} lines)`);
|
||||
+15
-1
@@ -60,7 +60,21 @@ execFileSync(
|
||||
*/
|
||||
function buildStamp(): string {
|
||||
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version: string };
|
||||
let git = 'nogit';
|
||||
/**
|
||||
* THE FALLBACK HAS TO BE UNIQUE PER BUILD, because this string is also the cache-bust key.
|
||||
*
|
||||
* It used to be the literal `nogit`, which is exactly what the `.s9pk` build produces — the
|
||||
* Dockerfile copies the working tree in without `.git`, so `git rev-parse` fails there every time.
|
||||
* Every packaged release therefore published `?v=nogit`, byte-identical to the release before it,
|
||||
* and a returning player's browser had no reason to refetch a single module. v0.7.5's setup screen
|
||||
* and v0.7.6's fix to it both shipped correctly to `phoenix.local` and neither reached the browser
|
||||
* that asked for them (Jesse, twice, 2026-08-29 — "setup did not work").
|
||||
*
|
||||
* The version plus the build's own timestamp is always distinct, needs nothing from the
|
||||
* environment, and stays honest: two builds of the same commit ARE two deploys, and a cache key
|
||||
* that says so costs one refetch, while one that lies costs a release nobody receives.
|
||||
*/
|
||||
let git = `${pkg.version}-${Date.now().toString(36)}`;
|
||||
try {
|
||||
const sha = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: root })
|
||||
.toString()
|
||||
|
||||
+34
-8
@@ -688,8 +688,16 @@ function spendDispatchBonus(
|
||||
const mine = tray.trainNumber ?? 99;
|
||||
const theirs = other.trainNumber ?? 99;
|
||||
|
||||
// The Fedora is held by a PLAYER, and the dispatch devices are installed in an Office Area, which
|
||||
// is keyed by SEAT. Indexing one with the other is right only while seating is the identity map.
|
||||
/**
|
||||
* The Fedora is held by a PLAYER; the devices are installed in an Office Area, which is keyed by
|
||||
* SEAT. `areaOf` is what reconciles the two — it resolves through `seatOf` — so this is correct
|
||||
* under Employee Rotation and not only while seating happens to be the identity map.
|
||||
*
|
||||
* This comment used to say the opposite, warning that indexing one with the other was safe only
|
||||
* while seating was identity. It read as a live bug and was not one: `areaOf(s, player)` IS
|
||||
* `areaAtSeat(s, seatOf(s, player))`. Pinned by test rather than asserted here — see #101's
|
||||
* "spends the Superintendent's own devices under non-identity seating".
|
||||
*/
|
||||
const area = areaOf(s, s.clock.superintendent);
|
||||
|
||||
// Best device first — Radio (+12) beats Telephone (+8) beats Telegraph (+4).
|
||||
@@ -727,7 +735,11 @@ function spendDispatchBonus(
|
||||
* the speeches are made, and every arrival after that is expedited. `speechMade` is set on that first
|
||||
* stop, so the train is exempt once and subject to the fault thereafter.
|
||||
*/
|
||||
function isExpedited(tray: CrewTray): boolean {
|
||||
export function isExpedited(tray: {
|
||||
trainNumber: number | null;
|
||||
trainIsExtra: boolean;
|
||||
speechMade?: boolean;
|
||||
}): boolean {
|
||||
const rules = trainProfile(tray.trainNumber ?? 0, tray.trainIsExtra)?.rules;
|
||||
if (!rules) return false;
|
||||
if (rules.expedite) return true;
|
||||
@@ -1636,11 +1648,25 @@ function shiftChange(s: GameState, events: GameEvent[]): AdvanceResult {
|
||||
events.push({ type: 'stageBegan', day: s.clock.day, stage: s.clock.stage });
|
||||
}
|
||||
|
||||
// §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') {
|
||||
/**
|
||||
* §3.4 — EVERY MODE, SOLITAIRE INCLUDED: 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.
|
||||
*
|
||||
* SOLITAIRE WAS EXCLUDED UNTIL 2026-08-30 and nothing said so. The gate here read `mode ===
|
||||
* 'competitive' || mode === 'coop'`, while `SOLO_CONFIG` carried both limits and the New Game
|
||||
* dialog offered them as live settings — so a solitaire player could set a collision limit, read
|
||||
* "the game ends in a loss" beside it, and crash as often as they liked. Found reviewing that
|
||||
* screen's wording (Jesse, 2026-08-30); his ruling is that the settings should do what they say,
|
||||
* so the gate is gone rather than the controls.
|
||||
*
|
||||
* A SOLITAIRE GAME CAN THEREFORE NOW END EARLY, which no measurement in `TODO.md` was taken
|
||||
* under. At the shipped defaults (3 a Day, 5 total) it is a rare ending rather than a common one —
|
||||
* the bot averages 0.06 collisions a game — but any figure quoted from a full-length run predates
|
||||
* it.
|
||||
*/
|
||||
{
|
||||
const perDayBreach =
|
||||
s.config.maxCollisionsPerDay > 0 && s.collisionsToday >= s.config.maxCollisionsPerDay;
|
||||
const totalBreach =
|
||||
|
||||
+20
-6
@@ -16,7 +16,6 @@
|
||||
|
||||
import {
|
||||
FREIGHT_PROFILES,
|
||||
HAND_LIMIT,
|
||||
LABORER_ACTIONS_PER_LOAD,
|
||||
MAX_CONSIST,
|
||||
REALIGNMENTS,
|
||||
@@ -61,6 +60,7 @@ import {
|
||||
decisionActor,
|
||||
officeNodeFor,
|
||||
isOperationalRail,
|
||||
overHandLimit,
|
||||
playerAtSeat,
|
||||
pooled,
|
||||
railFacingOf,
|
||||
@@ -607,7 +607,8 @@ function freightWorkedKey(trayId: TrayId, at: GridCoord): string {
|
||||
return `${trayId}@${coordKey(at)}`;
|
||||
}
|
||||
|
||||
const isFreight = (c: RollingStock): boolean => c.type !== 'coach' && c.type !== 'caboose';
|
||||
/** Exported so the Blocked panel counts a freight car the same way the reducers do (Gitea#21). */
|
||||
export const isFreight = (c: RollingStock): boolean => c.type !== 'coach' && c.type !== 'caboose';
|
||||
|
||||
/**
|
||||
* IS THIS CAR CARRYING A LOAD? A CABOOSE NEVER IS, whatever its `loaded` flag says.
|
||||
@@ -657,6 +658,20 @@ function switchingRefusal(tray: CrewTray): RejectionCode | null {
|
||||
return rulesOf(tray).noSwitching ? 'NO_SWITCHING' : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* WHETHER TRAINS 3/4's PRINTED RULE IS WHAT IS STOPPING THIS CREW WHERE IT STANDS (Gitea#21).
|
||||
*
|
||||
* Exported for the Blocked panel, which needs to say so — and asks `freightBudgetLeft`, the same
|
||||
* predicate the reducer refuses on, rather than rebuilding the key for itself. `narrate.ts` cannot
|
||||
* then drift from the rule it is describing, which is the whole premise of that panel.
|
||||
*/
|
||||
export function freightRuleSpentHere(s: GameState, player: PlayerIndex, trayId: TrayId): boolean {
|
||||
const tray = s.trays.get(trayId);
|
||||
if (!tray || !rulesOf(tray).oneFreightPerLocation) return false;
|
||||
if (tray.position.at !== 'grid') return false;
|
||||
return !freightBudgetLeft(s, player, tray, tray.position.coord, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge freight cars against this train's per-location budget (trains 3/4).
|
||||
*
|
||||
@@ -1084,10 +1099,9 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
|
||||
case 'draw.end': {
|
||||
if (!inPhase(s, 'localOps')) return 'WRONG_PHASE';
|
||||
if (turnOf(s, player).option !== 'draw') return 'OPTION_NOT_CHOSEN';
|
||||
// §6.2 — "the player must reduce his hand to no more than three cards".
|
||||
const hand = s.decks.hands.get(player) ?? [];
|
||||
const limit = s.decks.redFlags.get(player) ? HAND_LIMIT + 1 : HAND_LIMIT;
|
||||
return hand.length > limit ? 'HAND_LIMIT' : null;
|
||||
// §6.2 — "the player must reduce his hand to no more than three cards". `overHandLimit`
|
||||
// (state.ts) is the one copy of that test; the Frame and the page ask the same function.
|
||||
return overHandLimit(s, player) ? 'HAND_LIMIT' : null;
|
||||
}
|
||||
|
||||
// -- Freight Agent --------------------------------------------------------
|
||||
|
||||
@@ -481,8 +481,11 @@ export const TIMETABLED_TRAINS: readonly TrainProfile[] = [
|
||||
* COACH COUNTS ON 1/2 AND 5/6 WERE SWAPPED BY JESSE (Gitea#7, v0.4.9e playtest): the Crack Limited
|
||||
* drops from three coaches to two, and The Sparrow rises from two to three. A change to the card
|
||||
* faces themselves, not a transcription fix — `Trains3.pdf` and the tables that transcribe it
|
||||
* still print the old numbers, so `docs/rules/card-reference.md` is the place that now carries
|
||||
* what the cards say.
|
||||
* still print the old numbers, so `docs/rules/as-built.md` is the place that now carries what
|
||||
* the cards say — GENERATED from the constants below by `scripts/build-card-reference.ts`, with
|
||||
* `test/card-reference.test.ts` failing if the two disagree. This comment used to name
|
||||
* `card-reference.md`, which describes the v0.4.5 deck and carries a banner saying not to use its
|
||||
* numbers; the code sent readers to a table it had itself superseded.
|
||||
*/
|
||||
...pair(1, 'Crack Limited', 'fast', { freight: 0, coach: 2, caboose: 0 },
|
||||
{ terminalsOnly: true, noSwitching: true, expedite: true, note: 'Stop at Terminals only.' }),
|
||||
|
||||
+14
-1
@@ -17,7 +17,7 @@ import type {
|
||||
OfficeTier,
|
||||
TrackGeometry,
|
||||
} from './content.ts';
|
||||
import { MAX_CONSIST, officeProfile } from './content.ts';
|
||||
import { HAND_LIMIT, MAX_CONSIST, officeProfile } from './content.ts';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Identifiers
|
||||
@@ -1040,6 +1040,19 @@ export function turnOf(s: GameState, player: PlayerIndex): TurnState {
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* §6.2 — IS THIS PLAYER HOLDING MORE THAN THEY MAY? Three cards, or four while a Red Flag is held.
|
||||
*
|
||||
* ONE answer, because there were three of them: `check('draw.end')` refused on it, `snapshot()`
|
||||
* recomputed it inline for the Frame, and `web/game.ts` kept a third for the page. All three agreed
|
||||
* — which is the state a disagreement starts from, and #96 is what that costs when the two halves
|
||||
* are a screen and the server that refuses what the screen offered.
|
||||
*/
|
||||
export function overHandLimit(s: GameState, player: PlayerIndex): boolean {
|
||||
const hand = s.decks.hands.get(player) ?? [];
|
||||
return hand.length > (s.decks.redFlags.get(player) ? HAND_LIMIT + 1 : HAND_LIMIT);
|
||||
}
|
||||
|
||||
export function freshTurn(moves: number): TurnState {
|
||||
return {
|
||||
option: null,
|
||||
|
||||
+30
-4
@@ -101,7 +101,13 @@ function sendJson(res: ServerResponse, status: number, body: unknown): void {
|
||||
res.end(text);
|
||||
}
|
||||
|
||||
async function serveStatic(distDir: string, urlPath: string, res: ServerResponse): Promise<void> {
|
||||
async function serveStatic(
|
||||
distDir: string,
|
||||
urlPath: string,
|
||||
res: ServerResponse,
|
||||
/** The request's `?v=` build tag, when it has one — see the `Cache-Control` note below. */
|
||||
buildTagged = false,
|
||||
): 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.
|
||||
@@ -113,7 +119,27 @@ async function serveStatic(distDir: string, urlPath: string, res: ServerResponse
|
||||
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 });
|
||||
/**
|
||||
* ONLY A URL CARRYING A BUILD TAG MAY BE CACHED, AND NOTHING ELSE MAY BE.
|
||||
*
|
||||
* Nothing here sent a `Cache-Control` at all before, so a browser applied its own heuristic to
|
||||
* the pages as much as the modules. The pages are the one thing that CANNOT be versioned in
|
||||
* their own URL — a player types the address or follows a bookmark — so a cached `play.html`
|
||||
* pins that player to the entire build it names, including every `?v=` tag inside it. That is
|
||||
* half of why v0.7.5 and v0.7.6 did not reach the browser that asked for them; `build-web.ts`
|
||||
* publishing `?v=nogit` on every packaged release was the other half, and neither is enough on
|
||||
* its own.
|
||||
*
|
||||
* `?v=` is the exact condition rather than "not HTML": `build-web.ts` tags the modules and the
|
||||
* script tags that load them, and tags NOTHING else. An untagged URL — an image, the replay
|
||||
* manifest — has no way to announce a change, so a year of `immutable` on one would outlive
|
||||
* several releases of whatever it holds.
|
||||
*/
|
||||
res.writeHead(200, {
|
||||
'Content-Type': MIME[extname(full)] ?? 'application/octet-stream',
|
||||
'Content-Length': info.size,
|
||||
'Cache-Control': buildTagged ? 'public, max-age=31536000, immutable' : 'no-cache',
|
||||
});
|
||||
createReadStream(full).pipe(res);
|
||||
} catch {
|
||||
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
||||
@@ -281,7 +307,7 @@ export function startServer(opts: ServerOptions): void {
|
||||
// Unset means the routes are not here — indistinguishable from any other unknown path, so
|
||||
// nothing advertises an administrative surface to someone probing for one.
|
||||
if (!opts.adminSecret) {
|
||||
await serveStatic(opts.distDir, url.pathname, res);
|
||||
await serveStatic(opts.distDir, url.pathname, res, url.searchParams.has('v'));
|
||||
return;
|
||||
}
|
||||
if (req.headers['x-admin-secret'] !== opts.adminSecret) {
|
||||
@@ -700,7 +726,7 @@ export function startServer(opts: ServerOptions): void {
|
||||
return;
|
||||
}
|
||||
|
||||
await serveStatic(opts.distDir, url.pathname, res);
|
||||
await serveStatic(opts.distDir, url.pathname, res, url.searchParams.has('v'));
|
||||
})().catch((err: unknown) => {
|
||||
sendJson(res, 500, { error: err instanceof Error ? err.message : 'internal error' });
|
||||
});
|
||||
|
||||
+15
-1
@@ -174,8 +174,17 @@ function buildSession(
|
||||
};
|
||||
let open: OpenSpan | null = openSpanFor(Date.now());
|
||||
|
||||
/**
|
||||
* A seat's full Frame, with `lines` deliberately EMPTY (#97).
|
||||
*
|
||||
* Narration reaches a client by ONE path — `Push.lines` — because `RemoteSession`
|
||||
* (`web/session.ts`) accumulates from that field alone and its `lines()` returns the accumulator.
|
||||
* Passing `game.log` here serialised the entire log into every frame for every seat, where it grew
|
||||
* all game and was thrown away on arrival, while `linesSince` correctly sent the same text beside
|
||||
* it. The duplicate was not merely waste: it masked the reconnect bug `connect` fixes below.
|
||||
*/
|
||||
function frameFor(seat: PlayerIndex): Frame {
|
||||
return snapshot(game.state, game.log, null, null, null, false, seat);
|
||||
return snapshot(game.state, [], null, null, null, false, seat);
|
||||
}
|
||||
|
||||
function linesSince(seat: PlayerIndex): { text: string; tone: string }[] {
|
||||
@@ -341,6 +350,11 @@ function buildSession(
|
||||
// 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);
|
||||
// ...and the NARRATION watermark with it (#97). The browser this answers has just reloaded
|
||||
// from an empty accumulator, so a seat told "nothing new since your last push" came back to a
|
||||
// blank history panel mid-game, with the server holding the whole log. `Push.lines` on a
|
||||
// connect IS the history, which is what lets the Frame stop carrying a second copy.
|
||||
sentLines.delete(seat);
|
||||
return pushFor(seat, null);
|
||||
},
|
||||
|
||||
|
||||
+148
-8
@@ -55,11 +55,12 @@ export function divisionSvg(nodes: DivisionView[], roster?: DivisionRoster | nul
|
||||
*
|
||||
* West DP · Mainline · [Limits … Office … Limits] · Mainline · [ … ] · Mainline · East DP
|
||||
*
|
||||
* SEATING. Players sit around a table, so the route is laid out the way they do: one row alone,
|
||||
* two rows facing, a horseshoe of three, a square of four. The Division is a LINE and not a loop
|
||||
* — trains enter at one Division Point and leave at the other — so the shape is deliberately left
|
||||
* open, with the two ends drawn as buffer stops facing each other across a marked gap. Closing it
|
||||
* into a ring would promise a connection the rules do not have.
|
||||
* ONE ROW AT EVERY SEAT COUNT (Gitea#18). It used to be laid out the way players sit — two rows
|
||||
* facing, a horseshoe of three, a square of four — and the reasoning for dropping that is at the
|
||||
* layout itself below. The Division is a LINE and not a loop — trains enter at one Division Point
|
||||
* and leave at the other — so the row is deliberately left open, with the two ends drawn as
|
||||
* buffer stops facing outward. Closing it into a ring would promise a connection the rules do
|
||||
* not have.
|
||||
*
|
||||
* Self-contained on purpose: the replay embeds this by `toString()`, so it may not reach for
|
||||
* anything outside its own body.
|
||||
@@ -108,7 +109,6 @@ export function divisionSvg(nodes: DivisionView[], roster?: DivisionRoster | nul
|
||||
* this is back to what a buffer stop actually needs.
|
||||
*/
|
||||
const PAD = 22;
|
||||
const SIDE_GAP = 34;
|
||||
|
||||
const esc = (t: string): string =>
|
||||
String(t).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] ?? c);
|
||||
@@ -144,8 +144,20 @@ export function divisionSvg(nodes: DivisionView[], roster?: DivisionRoster | nul
|
||||
* register under the rail (Gitea#18).
|
||||
*/
|
||||
below?: Cell['trains'];
|
||||
/**
|
||||
* Office cells only: a Red Flag standing at this Office's Limits, and which approach it guards
|
||||
* (#94). A token set out ON the board that holds the next train arriving from that side, so it
|
||||
* is drawn like the other things standing on the map rather than left to the log.
|
||||
*/
|
||||
redFlag?: string | null;
|
||||
/** Mainline cards only: §2.1 divides one into two regions. 0 elsewhere — no bars are drawn. */
|
||||
regions: number;
|
||||
/**
|
||||
* Which way a Heavy Grade climbs, or null on every other card. Drawn as a wedge, because the
|
||||
* tooltip said "climbs east" and the card itself showed nothing — so the one card whose
|
||||
* orientation the PLAYER chooses was the one card you had to hover to read (Jesse, 2026-08-30).
|
||||
*/
|
||||
gradeUp?: string | null;
|
||||
w: number;
|
||||
x: number;
|
||||
y: number;
|
||||
@@ -217,10 +229,17 @@ export function divisionSvg(nodes: DivisionView[], roster?: DivisionRoster | nul
|
||||
(owner?.isYou ? ' — this is your railroad' : '') +
|
||||
// "their move" is wrong when the reader is the one being waited on.
|
||||
(owner?.isTurn ? (owner.isYou ? ' — it is your move' : ' — it is their move') : '') +
|
||||
// #94 — first, and in full, because it is the one thing here that CHANGES what a train
|
||||
// may do. Everything below it describes the cell; this describes a rule in force.
|
||||
(n.redFlag === 'east' || n.redFlag === 'west'
|
||||
? `\n\nRED FLAG set out at the ${n.redFlag === 'east' ? 'East' : 'West'} Limits — the ` +
|
||||
`next train arriving from the ${n.redFlag} is held short, and the flag is spent doing it.`
|
||||
: '') +
|
||||
`\n\nThe district itself is drawn on the Office map — this cell is the whole of it, with the ` +
|
||||
`trains standing in it: those holding an A/D track on the rail, and any crew switching in ` +
|
||||
`the district below it.`,
|
||||
seat: n.seat ?? null,
|
||||
redFlag: n.redFlag ?? null,
|
||||
// No regions in a district: a crew moves by Moves there, not by Stages, so it occupies a
|
||||
// card outright rather than a part of one.
|
||||
regions: 0,
|
||||
@@ -259,6 +278,7 @@ export function divisionSvg(nodes: DivisionView[], roster?: DivisionRoster | nul
|
||||
seat: null,
|
||||
// A Division Point is one region — the queue trains enter and leave the Division through.
|
||||
regions: dp ? 1 : (n.regions ?? 0),
|
||||
gradeUp: dp ? null : (n.gradeUp ?? null),
|
||||
w: dp ? CW.dp : CW.ml,
|
||||
});
|
||||
}
|
||||
@@ -357,6 +377,97 @@ export function divisionSvg(nodes: DivisionView[], roster?: DivisionRoster | nul
|
||||
out += `<line class="bs-region" x1="${c.x + 6 + RW * r}" y1="${c.y + RAIL_Y - 14}" x2="${c.x + 6 + RW * r}" y2="${c.y + RAIL_Y + 10}"/>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A RED FLAG STANDING AT THE LIMITS (#94).
|
||||
*
|
||||
* Drawn at the END IT GUARDS — west on the left, east on the right, since east is right on this
|
||||
* map — because which approach it covers is the whole of the information. A flag in the middle
|
||||
* of the cell would say a flag is out and leave the reader to hover for the half that decides
|
||||
* whether to run a train.
|
||||
*
|
||||
* A staff with a pennant, at rail height, standing clear of the chips: it is beside the rail,
|
||||
* which is where a flag is. Red is otherwise unused on this map (`bs-full` tints a cell, it does
|
||||
* not draw), so the mark does not compete with anything for meaning.
|
||||
*/
|
||||
if (c.redFlag === 'east' || c.redFlag === 'west') {
|
||||
const west = c.redFlag === 'west';
|
||||
const fx = west ? c.x + 9 : c.x + c.w - 9;
|
||||
const top = c.y + RAIL_Y - 22;
|
||||
const dir = west ? 1 : -1;
|
||||
out += `<g class="bs-flag">`;
|
||||
out += `<line x1="${fx}" y1="${top}" x2="${fx}" y2="${c.y + RAIL_Y + 4}"/>`;
|
||||
// The pennant flies INTO the cell, so it can never overhang the card edge at either end.
|
||||
out += `<polygon points="${fx},${top} ${fx + dir * 13},${top + 5} ${fx},${top + 10}"/>`;
|
||||
out += `</g>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* WHICH WAY A HEAVY GRADE CLIMBS, drawn rather than only said.
|
||||
*
|
||||
* The tooltip has said "climbs east" since the Frame carried `gradeUp`, and the card showed
|
||||
* nothing — so the one Mainline card whose orientation the PLAYER sets, and the one where a
|
||||
* Helpers or Brakeman modifier means opposite things at opposite ends, was the one you had to
|
||||
* hover to read (Jesse, 2026-08-30).
|
||||
*
|
||||
* A wedge rising toward the climb, with an arrow up its slope. Two cues rather than one: the
|
||||
* wedge alone asks the reader to judge which end is taller, which at eleven pixels of rise is a
|
||||
* comparison rather than a glance. Bottom-right, clear of the left-aligned capacity line and
|
||||
* below the region bars, so it never lands under a train chip.
|
||||
*
|
||||
* `east` is RIGHT on this map and always has been (Gitea#18) — that is what makes a wedge
|
||||
* readable without a compass, and it is why the row layout is worth its width.
|
||||
*/
|
||||
if (c.gradeUp === 'east' || c.gradeUp === 'west') {
|
||||
const s = c.gradeUp === 'east' ? 1 : -1;
|
||||
const GW = 58;
|
||||
const RISE = 24;
|
||||
const gx1 = c.x + c.w - 9 - GW;
|
||||
const gx2 = c.x + c.w - 9;
|
||||
const yb = c.y + CH - 6;
|
||||
const peakX = s === 1 ? gx2 : gx1;
|
||||
out += `<polygon class="bs-grade" points="${gx1},${yb} ${gx2},${yb} ${peakX},${yb - RISE}"/>`;
|
||||
|
||||
/**
|
||||
* THE ARROW LIES ALONG THE WEDGE'S OWN SLOPE, CENTRED IN IT (Jesse, 2026-08-30).
|
||||
*
|
||||
* Parallel to the hypotenuse is the shape that fits: the perpendicular gap to the slope is
|
||||
* then CONSTANT along the whole arrow, instead of closing at one end the way a steeper line
|
||||
* does. The earlier 30° pass had to be tucked into the fat half to survive, because 30° is
|
||||
* steeper than this wedge climbs — at 58×24 the slope is 22.5°, and the arrow simply lies on
|
||||
* it.
|
||||
*
|
||||
* Centred on the TRIANGLE'S CENTROID (2/3 along the base, 1/3 up), which is the balance point
|
||||
* of the form rather than of its bounding box — centring on the box would push the arrow into
|
||||
* the thin corner where there is no height for it.
|
||||
*
|
||||
* The wedge grew 50×22 → 58×24 to pay for that: the centroid sits only ~7px from the
|
||||
* hypotenuse, so a centred arrow has less room than an off-centre one and needs a bigger form
|
||||
* to keep it. Sizes are the best fit found by search, clearing every edge by 2.88px;
|
||||
* `web.test.ts` re-derives it and fails under 2px.
|
||||
*
|
||||
* Worked in the wedge's own frame — `u` along the base from the thin corner, `h` up from it —
|
||||
* so a westward climb is one sign on `u` rather than a second set of coordinates.
|
||||
*/
|
||||
const L = 20;
|
||||
const HL = 6;
|
||||
const HW = 3.5;
|
||||
const T = 1.4;
|
||||
const A = Math.atan2(RISE, GW);
|
||||
const cos = Math.cos(A);
|
||||
const sin = Math.sin(A);
|
||||
const cu = (2 * GW) / 3;
|
||||
const ch = RISE / 3;
|
||||
const pt = (lx: number, ly: number): string => {
|
||||
const u = cu + lx * cos - ly * sin;
|
||||
const h = ch + lx * sin + ly * cos;
|
||||
return `${s === 1 ? gx1 + u : gx2 - u},${yb - h}`;
|
||||
};
|
||||
const H = L / 2;
|
||||
out +=
|
||||
`<polygon class="bs-gradeup" points="${pt(-H, -T)} ${pt(H - HL, -T)} ${pt(H - HL, -HW)} ` +
|
||||
`${pt(H, 0)} ${pt(H - HL, HW)} ${pt(H - HL, T)} ${pt(-H, T)}"/>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* ON THE DIVISION MAP, A TRAIN IS A CHIP — name, which way it points, how many cars.
|
||||
*
|
||||
@@ -378,6 +489,14 @@ export function divisionSvg(nodes: DivisionView[], roster?: DivisionRoster | nul
|
||||
* things the Division map is for — where a train is and which way it is going — and leaves the
|
||||
* cars to the tooltip and to the district.
|
||||
*/
|
||||
/**
|
||||
* THE REGION NUMBER IS A PLACE ON THE MAP, NOT A DISTANCE RUN (Gitea#22).
|
||||
*
|
||||
* `view.ts` mirrors a westbound train before it gets here, so this counts boxes west to east
|
||||
* for every train regardless of which way it is going — and the tooltip says so, because
|
||||
* "region 2 of 2" beside "2 Stages still to run" reads as a contradiction otherwise. It is the
|
||||
* second box from the west end; a westbound train in it has its whole crossing ahead of it.
|
||||
*/
|
||||
const chip = (t: NonNullable<Cell['trains']>[number], tx: number, ty: number, w: number): void => {
|
||||
const cars = t.cars ?? [];
|
||||
const arrow = t.facing === 'w' ? '\u25c0' : '\u25b6';
|
||||
@@ -391,7 +510,7 @@ export function divisionSvg(nodes: DivisionView[], roster?: DivisionRoster | nul
|
||||
: '';
|
||||
out += `<g class="bs-train" data-tip="${esc(t.label)} \u2014 carrying ${esc(cars.join(', ') || 'no cars')}${
|
||||
cars.length ? ` (${loaded} loaded)` : ''
|
||||
}${inRegion ? ` \u00b7 region ${(t.region ?? 0) + 1} of ${c.regions}${dir}` : ''}${esc(stages)}${
|
||||
}${inRegion ? ` \u00b7 region ${(t.region ?? 0) + 1} of ${c.regions}, counted west to east${dir}` : ''}${esc(stages)}${
|
||||
// What the card prints. A train on the Mainline is exactly where "why did that leave without
|
||||
// me?" gets asked, and EXPEDITED is the answer more often than not.
|
||||
t.what ? `\n\n${esc(t.what)}` : ''
|
||||
@@ -979,9 +1098,18 @@ export function officeSvg(
|
||||
// card, the old y = H-46 baseline printed the label straight along the rail itself.
|
||||
// Hover text per enhancement, from the card catalogue — an Interlocking used to be a bare word
|
||||
// on the card with nothing to say what it did, or that it does not do it yet.
|
||||
// A SPENT dispatch device is struck through (#101). Telegraph/Telephone/Radio are "once a
|
||||
// day", and the label said the same thing before and after the Superintendent spent one — so
|
||||
// the card advertised a +12 that was not there. Per-`tspan` rather than per-`text` so the
|
||||
// names still read as one row, and `?? []` because `piecePreview` builds a cell literal by
|
||||
// hand and has no flags.
|
||||
const spentFlags = cell.enhancementsSpent ?? [];
|
||||
const names = cell.enhancements
|
||||
.map((n, i) => (spentFlags[i] ? `<tspan class="bs-enh-spent">${esc(n)}</tspan>` : esc(n)))
|
||||
.join(' · ');
|
||||
out += `<text class="bs-enh" x="6" y="26" data-tip="${esc(
|
||||
(cell.enhancementsWhat ?? []).join(' · '),
|
||||
)}">${esc(cell.enhancements.join(' · '))}</text>`;
|
||||
)}">${names}</text>`;
|
||||
}
|
||||
if (selectedTrain) {
|
||||
/**
|
||||
@@ -1123,6 +1251,17 @@ export const BOARD_CSS = `
|
||||
/* The vertical bars a Mainline card is divided into (§2.1). Drawn faint: they are the ruler the
|
||||
train is measured against, not something to look at instead of the train. */
|
||||
.bs-region{stroke:#4a5361;stroke-width:1.2;stroke-dasharray:3 3}
|
||||
/* #94 — the one red mark on the Division map, so it reads as a stop rather than as decoration. */
|
||||
.bs-flag line{stroke:#9aa3b0;stroke-width:1.6}
|
||||
.bs-flag polygon{fill:#d2453f;stroke:#7d211d;stroke-width:0.8}
|
||||
/* THE HEAVY GRADE WEDGE. Terrain, so it is coloured as terrain rather than as a warning.
|
||||
SOLID BROWN, fill and border the same (Jesse, 2026-08-30) — the first pass paired a desaturated
|
||||
fill with an amber arrow and the pair read reddish, which on a map that spends amber on "it is
|
||||
happening here" made a fixed piece of landscape look like a live alert. One flat brown recedes
|
||||
into scenery; the arrow is bone so the DIRECTION, which is the fact being reported, is the part
|
||||
that carries. */
|
||||
.bs-grade{fill:#6b5334;stroke:#6b5334;stroke-width:1}
|
||||
.bs-gradeup{fill:#f2e8d5}
|
||||
.bs-slot{fill:none;stroke:#5f6b7a;stroke-width:1.1;stroke-dasharray:3 2}
|
||||
.bs-slot.bs-occ{stroke-dasharray:none;stroke-width:1.6}
|
||||
/* CAR TYPE BY COLOUR, LOAD STATE BY FILL — the SAME distinction the train tray draws, because they
|
||||
@@ -1206,6 +1345,7 @@ export const BOARD_CSS = `
|
||||
.bs-mod{font:10px ui-monospace,monospace}
|
||||
text.bs-mod{fill:#c8a04a}
|
||||
.bs-enh{fill:#7fb0e6;font:9px ui-monospace,monospace}
|
||||
.bs-enh-spent{fill:#5b6b7d;text-decoration:line-through}
|
||||
.bs-rowlab{fill:#5f6b7a;font:600 9px ui-monospace,monospace;letter-spacing:.1em}
|
||||
/* THE EDGE OF THE DISTRICT. Deliberately quiet — it is a boundary, not an action — and dashed, so it
|
||||
reads as a line on the table rather than as rail. Nothing is laid outside it (§2.1). */
|
||||
|
||||
+100
-8
@@ -15,10 +15,10 @@
|
||||
* panel cannot drift from the rules.
|
||||
*/
|
||||
|
||||
import { MAX_CONSIST } from '../engine/content.ts';
|
||||
import { MAX_CONSIST, crewTrayCount } from '../engine/content.ts';
|
||||
import { adTrackCount, coordKey, seatOf, turnOf } from '../engine/state.ts';
|
||||
import type { GameState, GridCoord, PlayerIndex, RollingStock, SeatIndex, TrayId } from '../engine/state.ts';
|
||||
import { areaOf, canAdvanceLoad, canBoard, canDetrain, canStartLoad, facilityCarType, facilityCarTypes, laborersLeft, movesFor, passengerRefusal, portersLeft } from '../engine/apply.ts';
|
||||
import { areaOf, canAdvanceLoad, canBoard, canDetrain, canStartLoad, facilityCarType, facilityCarTypes, freightRuleSpentHere, isFreight, laborersLeft, movesFor, passengerRefusal, portersLeft } from '../engine/apply.ts';
|
||||
import type { GameEvent } from '../engine/events.ts';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -746,6 +746,42 @@ export function impediments(s: GameState, player: PlayerIndex = 0): Impediment[]
|
||||
* Only while switching, and only the cards actually in the crew's way: `movesFor` reports the
|
||||
* squares the movement walk reached and refused, not every square on the board.
|
||||
*/
|
||||
/**
|
||||
* WHY A CAR WILL NOT COME OFF (Gitea#21).
|
||||
*
|
||||
* "I dropped the first tank car, but that was all I was allowed to do" — and this panel, asked
|
||||
* why, talked about the refinery's green box. The rule that actually refused is printed on the
|
||||
* train: trains 3/4, the Express, "may drop or pick up one freight car at every location". The
|
||||
* refusal was correct. Nothing said it.
|
||||
*
|
||||
* That is a worse failure than a missing button, because the panel did not stay silent — it
|
||||
* offered a true statement about the FACILITY, which sent the player to spend a Freight Agent
|
||||
* action that could not have helped. The rule was on the train card's tooltip, which is not
|
||||
* where anyone looks when a button they expected is simply absent.
|
||||
*
|
||||
* Only when the crew has a freight car it could otherwise set out. A budget spent by a train
|
||||
* with nothing left to drop is not blocking anything, and this panel earns its keep by being
|
||||
* short enough to read.
|
||||
*/
|
||||
const turnNow = turnOf(s, player);
|
||||
if (s.clock.phase === 'localOps' && turnNow.option === 'switch') {
|
||||
for (const [id, tray] of s.trays) {
|
||||
if (tray.position.at !== 'grid' || tray.position.seat !== seatOf(s, player)) continue;
|
||||
if (!tray.consist.some(isFreight)) continue;
|
||||
if (!freightRuleSpentHere(s, player, id)) continue;
|
||||
const { row, col } = tray.position.coord;
|
||||
out.push({
|
||||
where: `Train ${tray.trainNumber} at (${col},${row})`,
|
||||
why:
|
||||
'ONE FREIGHT CAR PER LOCATION — this train has already worked a freight car on this ' +
|
||||
'square, so no more come off or on here until next turn. It may still work one at the ' +
|
||||
'next square it reaches.',
|
||||
// The printed rule doing its job, and it lifts by itself. Amber, not red.
|
||||
severity: 'waiting',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const turn = turnOf(s, player);
|
||||
if (s.clock.phase === 'localOps' && turn.option === 'switch' && turn.movesRemaining > 0) {
|
||||
for (const [id, tray] of s.trays) {
|
||||
@@ -832,13 +868,69 @@ export function impediments(s: GameState, player: PlayerIndex = 0): Impediment[]
|
||||
}
|
||||
}
|
||||
|
||||
// Trains held for want of a Crew Tray (§7) — the scarcity mechanic, made visible.
|
||||
const due = s.timetable[s.clock.stage - 1];
|
||||
if (due !== null && due !== undefined && s.freeTrays.length === 0) {
|
||||
/**
|
||||
* TRAINS HELD FOR WANT OF A CREW TRAY (§7) — the scarcity mechanic, made visible (#98).
|
||||
*
|
||||
* This covered the TIMETABLED train due out this Stage and nothing else, which meant the two
|
||||
* other things that queue for the same pool reported nothing at all. A player who spent a card on
|
||||
* an Extra, or ordered a second section, got an EMPTY panel while their train sat behind an
|
||||
* exhausted pool — and each had been announced once in the log in a line that promised a future
|
||||
* event ("as soon as a Crew Tray frees up") which nothing then confirmed.
|
||||
*
|
||||
* All three are one condition, so they are written as one block: no free tray, and something
|
||||
* waiting for one. The count rides along because "no free Crew Tray" reads like a permanent fact
|
||||
* about the game rather than a state that will pass.
|
||||
*/
|
||||
// `crewTrayCount` is the pool's size, asked rather than re-derived. `trays.size + freeTrays.length`
|
||||
// gives the same number in play — `retireTrain` moves a tray back — but it is a second way to know
|
||||
// one fact, which is the shape of every bug this release fixed.
|
||||
const trays = `${s.freeTrays.length} of ${crewTrayCount(s.players.length)} Crew Trays free`;
|
||||
if (s.freeTrays.length === 0) {
|
||||
const due = s.timetable[s.clock.stage - 1];
|
||||
if (due !== null && due !== undefined) {
|
||||
out.push({
|
||||
where: `Train ${due}`,
|
||||
why: `due to depart but HELD — no free Crew Tray (${trays})`,
|
||||
severity: 'stuck',
|
||||
});
|
||||
}
|
||||
|
||||
// An Extra belongs to the player who played the card (§7), so it is their errand and it is
|
||||
// reported to them. A second section is the table's, like any Timetabled train.
|
||||
for (const x of s.pendingExtras) {
|
||||
if (x.player !== player) continue;
|
||||
out.push({
|
||||
where: `Extra X${x.trainNumber}`,
|
||||
why: `played and waiting to be made up — no free Crew Tray (${trays})`,
|
||||
severity: 'stuck',
|
||||
});
|
||||
}
|
||||
|
||||
for (const n of s.pendingSecondSections) {
|
||||
out.push({
|
||||
where: `Train ${n}`,
|
||||
why: `second section ordered and waiting to be made up — no free Crew Tray (${trays})`,
|
||||
severity: 'stuck',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A TRAIN HELD AT THE LIMITS BY AN INTERLOCKING (#99).
|
||||
*
|
||||
* It is inside the player's Limits, not on an A/D track, and it takes the first track that frees
|
||||
* ahead of any newcomer. The map now draws it on the Limits square; this says what it is waiting
|
||||
* for, which is the Office emptying rather than anything the held train itself can do.
|
||||
*/
|
||||
for (const id of area.heldAtLimits) {
|
||||
const t = s.trays.get(id);
|
||||
if (!t) continue;
|
||||
out.push({
|
||||
where: `Train ${due}`,
|
||||
why: 'due to depart but HELD — no free Crew Tray',
|
||||
severity: 'stuck',
|
||||
where: `Train ${t.trainIsExtra ? 'X' : ''}${t.trainNumber ?? '—'}`,
|
||||
why:
|
||||
'held at your Limits by the Interlocking instead of colliding — it takes the first A/D ' +
|
||||
'track that frees, ahead of any train arriving after it',
|
||||
severity: 'waiting',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+22
-3
@@ -35,6 +35,7 @@ import { legalActions } from '../engine/legal.ts';
|
||||
import { createGame } from '../engine/setup.ts';
|
||||
import type { Facility, GameConfig, GameState } from '../engine/state.ts';
|
||||
import { actingPlayer } from '../engine/state.ts';
|
||||
import { reasonSentence } from '../web/panels.ts';
|
||||
import { developerBot, lastChoiceReason } from './bot.ts';
|
||||
import { carLabel, cuesFor, idleNote, isVisible, narrate } from './narrate.ts';
|
||||
// The view-model lives in its own module so the browser build can import it without dragging in
|
||||
@@ -148,12 +149,26 @@ export function record(seed: number, length: GameLength, maxSteps = 100_000): Re
|
||||
push(applied.events);
|
||||
}
|
||||
|
||||
/**
|
||||
* IN WORDS, NOT AS AN ENUM (`TODO.md` #34). This heading read `loss — revenueFloor`, which is
|
||||
* exactly the defect Gitea#16 was filed about on the playable page — it just outlived the fix
|
||||
* here, because nothing player-facing pointed at it. `reasonSentence` is shared rather than
|
||||
* reimplemented, so the replay and the results screen cannot end up explaining the same ending
|
||||
* two different ways.
|
||||
*
|
||||
* Fed the LAST frame, which is the state the outcome was decided in and is already recorded.
|
||||
* Tags are stripped: this lands in an `<h1>` and in a console line, neither of which wants markup.
|
||||
*/
|
||||
const o = s.outcome;
|
||||
const last = frames[frames.length - 1];
|
||||
const why = o && last ? reasonSentence(last, o, last.day).replace(/<[^>]+>/g, '') : '';
|
||||
return {
|
||||
seed,
|
||||
length,
|
||||
frames,
|
||||
outcome: o ? `${o.result} — ${o.reason} · final Revenue ${s.players[0]?.revenue ?? 0}` : 'unfinished',
|
||||
outcome: o
|
||||
? `${o.result === 'win' ? 'won' : 'lost'} — ${why} Final Revenue ${s.players[0]?.revenue ?? 0}.`
|
||||
: 'unfinished',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -215,7 +230,7 @@ export function compress(frames: Frame[]): Packed {
|
||||
const fi = c.facility ? f.facilities.indexOf(c.facility) : -1;
|
||||
// `trains` rides whole rather than being interned: it changes almost every frame, so a table
|
||||
// of them would be as long as the frames are and buy nothing.
|
||||
return [ci, wi, c.enhancements, c.cars, fi, c.trains, c.adTracks, c.enhancementsWhat, c.standingWest];
|
||||
return [ci, wi, c.enhancements, c.cars, fi, c.trains, c.adTracks, c.enhancementsWhat, c.standingWest, c.enhancementsSpent];
|
||||
});
|
||||
return { ...f, cells } as unknown as Frame;
|
||||
});
|
||||
@@ -249,7 +264,7 @@ export function rehydrateCells(
|
||||
facs: unknown[],
|
||||
): unknown[] {
|
||||
return packed.map((row) => {
|
||||
const p = row as [number, number, string[], string[], number, unknown, unknown, string[], number];
|
||||
const p = row as [number, number, string[], string[], number, unknown, unknown, string[], number, boolean[]];
|
||||
const c = cards[p[0]] as [number, number, string, string, boolean, string[]];
|
||||
// Tolerant the same way `standingWest` below is: an array rides through as-is, a lone object
|
||||
// (an older recording's singular `train`) is wrapped into a one-train roster, and null or
|
||||
@@ -269,6 +284,10 @@ export function rehydrateCells(
|
||||
// cut ahead of or behind the engine exactly as the live board does. Absent in older recordings,
|
||||
// which read as 0 — the whole cut east of the engine, which is what they used to draw anyway.
|
||||
standingWest: p[8] ?? 0,
|
||||
// Which dispatch devices were spent (#101), so a replay strikes a used Radio through exactly
|
||||
// as the live board does. Absent in recordings made before it existed, which read as no
|
||||
// device spent — the same thing they drew at the time, so an old replay is unchanged.
|
||||
enhancementsSpent: p[9] ?? [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
+29
-5
@@ -19,6 +19,8 @@ export type TurnChartFrame = {
|
||||
phase: string;
|
||||
phaseKey: string;
|
||||
actor: number | null;
|
||||
/** What the game has stopped to ask, when it has. Null while a phase is simply running. */
|
||||
awaiting?: { asks: string; train: string } | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -93,8 +95,21 @@ export function turnChartHtml(f: TurnChartFrame, actorName: string | null, super
|
||||
);
|
||||
}).join('');
|
||||
|
||||
// An automatic phase is waiting on nobody, and saying so is more use than a blank.
|
||||
/**
|
||||
* WAITING ON WHOM, AND FOR WHAT.
|
||||
*
|
||||
* "nobody — the Division is running itself" is true of an automatic phase and was being printed
|
||||
* over the top of three interruptions that are emphatically waiting on a person: §8.1's clearance
|
||||
* ruling, the Yard Office offer and the Red Flag prompt. The Frame carried the phase's actor,
|
||||
* which is null throughout the Mainline Phase, so a game stopped on a named player's decision
|
||||
* reported that nobody was holding it up (Jesse, 2026-08-30). `Frame.actor` is `actingPlayer` now
|
||||
* and answers who; `awaiting` says what, because "waiting on Bob" with no more than that is a
|
||||
* game that looks stuck to everyone except Bob.
|
||||
*/
|
||||
const who = actorName ?? 'nobody — the Division is running itself';
|
||||
const asked = f.awaiting
|
||||
? ` <span class="tc-asks">${esc(f.awaiting.asks)} · ${esc(f.awaiting.train)}</span>`
|
||||
: '';
|
||||
const fedora =
|
||||
superName === null
|
||||
? ''
|
||||
@@ -105,9 +120,12 @@ export function turnChartHtml(f: TurnChartFrame, actorName: string | null, super
|
||||
`<div class="tc-when"><b>Day ${f.day}</b><span>Stage ${f.stage} of 12</span>` +
|
||||
`<span class="dim">${esc(f.clock)}</span></div>` +
|
||||
`<div class="tc-now">phase <b>${esc(f.phase)}</b></div>` +
|
||||
`<div class="tc-who">waiting on <b>${esc(who)}</b></div>` +
|
||||
fedora +
|
||||
`<ol class="tc-phases">${chips}</ol>`
|
||||
`<div class="tc-who">waiting on <b>${esc(who)}</b>${asked}</div>` +
|
||||
// THE FEDORA RIDES AT THE END OF THE PHASE ROW (`TODO.md` #29, Jesse). It sat on its own line
|
||||
// between the phases and everything above them, which put a thing that changes every third
|
||||
// Stage in the middle of the things that change every Stage. The row it belongs beside is the
|
||||
// one whose last chip is Supervisor Shift — the phase that passes it.
|
||||
`<div class="tc-row"><ol class="tc-phases">${chips}</ol>${fedora}</div>`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -130,12 +148,18 @@ export const TURNCHART_CSS = `
|
||||
says "Player Solitaire", so the chart should agree. In multiplayer this is the thing a table
|
||||
glances at most often, so it gets its own chip rather than hiding in the phase text. */
|
||||
.tc-who{display:flex;align-items:center;gap:6px;font-size:12px;color:#8b94a3}
|
||||
.tc-asks{color:#a99ac4;font-style:italic}
|
||||
.tc-who b{color:#b98cf0;background:rgba(150,110,230,.16);border:1px solid #8b6ad0;
|
||||
border-radius:11px;padding:1px 9px;font-size:12px}
|
||||
/* WHO HOLDS THE FEDORA. Violet like the rest of the chart — this is "where you are" news, not
|
||||
something to press — but unfilled, so the eye still lands on "waiting on" first: that is the one
|
||||
that changes every turn, while this changes four times a Day. */
|
||||
.tc-super{display:flex;align-items:center;gap:6px;font-size:12px;color:#8b94a3;cursor:help}
|
||||
/* The phase row and the Fedora on one line, the hat pushed to the far end (TODO.md #29): the row
|
||||
is the Stage, and the Superintendent is who holds it. Wraps under the phases on a narrow screen
|
||||
rather than squeezing the chips. */
|
||||
.tc-row{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
|
||||
.tc-row ol.tc-phases{flex:1 1 auto}
|
||||
.tc-super{margin-left:auto;display:flex;align-items:center;gap:6px;font-size:12px;color:#8b94a3;cursor:help}
|
||||
.tc-super b{color:#cbb6f2;border:1px solid #6b5a94;border-radius:11px;padding:1px 9px;font-size:12px}
|
||||
ol.tc-phases{display:flex;gap:6px;list-style:none;margin:0;padding:0;flex-wrap:wrap}
|
||||
.tc-phase{display:flex;align-items:center;gap:6px;border:1px solid #2c333d;border-radius:14px;
|
||||
|
||||
+435
-69
@@ -10,7 +10,7 @@
|
||||
* drift into two different pictures of the same board.
|
||||
*/
|
||||
|
||||
import { regionOfTransit } from '../engine/advance.ts';
|
||||
import { isExpedited, regionOfTransit } from '../engine/advance.ts';
|
||||
import {
|
||||
areaAtSeat,
|
||||
areaOf,
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
import {
|
||||
ACTION_CARDS,
|
||||
ENHANCEMENT_CARDS,
|
||||
HAND_LIMIT,
|
||||
MAINLINE_MODIFIER_CARDS,
|
||||
MAINLINE_PROFILES,
|
||||
MANEUVER_CARDS,
|
||||
@@ -35,6 +34,8 @@ import {
|
||||
REALIGNMENTS,
|
||||
OFFICE_ORDER,
|
||||
SPACE_USE_CARDS,
|
||||
STAGES_PER_SHIFT,
|
||||
crewTrayCount,
|
||||
enhancementRule,
|
||||
enhancementText,
|
||||
industryProfile,
|
||||
@@ -46,9 +47,9 @@ import {
|
||||
mainlineDescription,
|
||||
} from '../engine/content.ts';
|
||||
import type { Intent } from '../engine/intents.ts';
|
||||
import type { Facility, GameConfig, GameState, PlayerIndex, SeatIndex, TrackCard, TurnoutOrientation } from '../engine/state.ts';
|
||||
import { carsOn, playerAtSeat, railFacingOf, seatOf, turnOf } from '../engine/state.ts';
|
||||
import type { Hand, HouseRules, TrackGeometry } from '../engine/content.ts';
|
||||
import type { Facility, GameConfig, GameState, OfficeArea, PlayerIndex, SeatIndex, TrackCard, TurnoutOrientation } from '../engine/state.ts';
|
||||
import { actingPlayer, carsOn, overHandLimit, playerAtSeat, railFacingOf, seatOf, turnOf } from '../engine/state.ts';
|
||||
import type { Direction, Hand, HouseRules, TrackGeometry } from '../engine/content.ts';
|
||||
import type { Port } from '../engine/track.ts';
|
||||
import { connectionsFor, slopeOfPair, variantsFor } from '../engine/track.ts';
|
||||
import type { Impediment } from './narrate.ts';
|
||||
@@ -73,6 +74,14 @@ export type CellView = {
|
||||
* `toString()`), so it cannot reach the card catalogue itself.
|
||||
*/
|
||||
enhancementsWhat: string[];
|
||||
/**
|
||||
* Which of those enhancements is SPENT for today, in the same order (#101).
|
||||
*
|
||||
* Only ever true of a dispatch device — Telegraph, Telephone, Radio — which is "once a day". The
|
||||
* reason and the Fedora caveat are already written into `enhancementsWhat`; this is the flag the
|
||||
* board styles from, because `board-svg.ts` imports nothing and cannot work it out for itself.
|
||||
*/
|
||||
enhancementsSpent: boolean[];
|
||||
/**
|
||||
* EVERY TRAIN STANDING HERE, in order, each with the engine in it and which way it points.
|
||||
*
|
||||
@@ -104,6 +113,15 @@ export type CellView = {
|
||||
* standing in front of them — the card is face down in a box somewhere by then.
|
||||
*/
|
||||
what: string;
|
||||
/**
|
||||
* HELD AT THE LIMITS BY AN INTERLOCKING, rather than standing on this square (#99).
|
||||
*
|
||||
* The engine keeps these in `OfficeArea.heldAtLimits` and deliberately does NOT move
|
||||
* `tray.position` onto the grid — a held train is not on a square anything may switch it from.
|
||||
* So the map has to draw it from the held list, and mark it, or it reads as an ordinary arrival
|
||||
* the player could work.
|
||||
*/
|
||||
heldAtLimits?: true;
|
||||
}[];
|
||||
/**
|
||||
* Office card only: how many A/D tracks the tier has — null everywhere else.
|
||||
@@ -320,6 +338,16 @@ export type DivisionView = {
|
||||
what?: string;
|
||||
/** Mainline cards only: how many regions the card is divided into (§2.1 — two). */
|
||||
regions?: number;
|
||||
/**
|
||||
* Office nodes only: a Red Flag standing at this Office's Limits, and which approach it guards
|
||||
* (#94). `null` when none is out.
|
||||
*
|
||||
* PUBLIC STATE, and the reason it has to be here: the flag is a token set out ON the board that
|
||||
* holds the next train arriving from that side until it is spent. It was announced once in the
|
||||
* log and then drawn nowhere, so a train would stop short with its only explanation scrolled out
|
||||
* of the panel.
|
||||
*/
|
||||
redFlag?: string | null;
|
||||
/** Office nodes only: the Running Track, Limits to Limits, west to east. */
|
||||
running?: RunningCardView[];
|
||||
/** Office nodes only: whose district this is. */
|
||||
@@ -354,7 +382,21 @@ export type Frame = {
|
||||
* replay recorder, which sees the events; the live game keeps its own on the Game object.
|
||||
*/
|
||||
cues?: string[];
|
||||
/**
|
||||
* WHO THE GAME IS WAITING ON — the phase's actor, or the owner of a pending interruption when
|
||||
* there is one. It carried `clock.currentActor` alone until 2026-08-30, which is null during the
|
||||
* Mainline Phase, so a game stopped dead on a Superintendent's clearance ruling reported "waiting
|
||||
* on nobody — the Division is running itself" while it waited on a named person to click
|
||||
* (reported by Jesse). The engine had the answer the whole time in `actingPlayer`.
|
||||
*/
|
||||
actor: number | null;
|
||||
/**
|
||||
* WHAT that player is being asked, when the game is stopped on a question rather than a turn.
|
||||
* Null whenever the phase is simply running. Naming the person is not enough on its own: three
|
||||
* different interruptions can be waiting, and "waiting on Bob" with no more than that is a game
|
||||
* that looks stuck to everyone except Bob.
|
||||
*/
|
||||
awaiting: { asks: string; train: string } | null;
|
||||
superintendent: number;
|
||||
revenue: number;
|
||||
/**
|
||||
@@ -433,7 +475,17 @@ export type Frame = {
|
||||
* there is only one; the first thing you want to know at a four-player table.
|
||||
*/
|
||||
viewer: number;
|
||||
/** The viewer's position in the west-to-east chain, which is not their player index (§4.4). */
|
||||
/**
|
||||
* The viewer's position in the west-to-east chain, which is not their player index (§4.4).
|
||||
*
|
||||
* CARRIED AHEAD OF ITS CALLER, DELIBERATELY (#45). Nothing renders this today — the 2026-08-30
|
||||
* dead-field audit found it read only by one test, and Jesse deferred the delete-or-document
|
||||
* call. Documenting rather than deleting, because Gitea#20's common board keys every district by
|
||||
* SEAT and resolves the player through `playerAtSeat` (§Employee Rotation moves players between
|
||||
* districts), so a client that must pick its own district out of a seat-keyed board needs exactly
|
||||
* this and cannot derive it from `viewer`. If step 2 ships without using it, delete it then —
|
||||
* this note is the reason it survived one audit, not a permanent exemption from the next.
|
||||
*/
|
||||
viewerSeat: number;
|
||||
/**
|
||||
* §4.4's opening D12 per player, and the roll that chose the Superintendent — kept so a client
|
||||
@@ -726,6 +778,39 @@ function baseOf(
|
||||
*/
|
||||
function trainsOnCard(s: GameState, viewerSeat: SeatIndex, key: string): CellView['trains'] {
|
||||
const out: CellView['trains'] = [];
|
||||
|
||||
/**
|
||||
* TRAINS HELD AT THE LIMITS — drawn here or drawn nowhere (#99).
|
||||
*
|
||||
* `arriveAtOffice` takes the tray out of the Mainline node's `transits` and, when an Interlocking
|
||||
* saves it from Gap 2d's collision, pushes it onto `heldAtLimits` without giving it a grid
|
||||
* position. The map draws mainline nodes from `transits` and squares from `position.at === 'grid'`
|
||||
* — so between the two the train was drawn in NEITHER, and simply vanished off the board until an
|
||||
* A/D track freed some Stages later.
|
||||
*
|
||||
* At WHICH Limits: the end it came in by. An eastbound train entered from the west, so it is held
|
||||
* at `limitsWest`; a westbound one at `limitsEast`.
|
||||
*/
|
||||
const area = areaAtSeat(s, viewerSeat);
|
||||
for (const id of area.heldAtLimits) {
|
||||
const t = s.trays.get(id);
|
||||
if (!t) continue;
|
||||
const at = t.direction === 'east' ? area.limitsWest : area.limitsEast;
|
||||
if (`${at.row},${at.col}` !== key) continue;
|
||||
out.push({
|
||||
trayId: id,
|
||||
label: t.trainNumber === null ? 'crew' : `T${t.trainIsExtra ? 'X' : ''}${t.trainNumber}`,
|
||||
cars: t.consist.map((c) => carLabel(c, viewerSeat)),
|
||||
engineAt: Math.max(0, Math.min(t.consist.length, t.engineAt)),
|
||||
facing: railFacingOf(t),
|
||||
what:
|
||||
'HELD AT THE LIMITS — the Interlocking stopped it on the Limit Track instead of letting it ' +
|
||||
'collide with a full Office. It takes the first A/D track that frees, ahead of any train ' +
|
||||
`arriving after it. ${trainRules(t)}`,
|
||||
heldAtLimits: true,
|
||||
});
|
||||
}
|
||||
|
||||
for (const [id, t] of s.trays) {
|
||||
if (t.position.at !== 'grid' || t.position.seat !== viewerSeat) continue;
|
||||
if (`${t.position.coord.row},${t.position.coord.col}` !== key) continue;
|
||||
@@ -1157,28 +1242,76 @@ export function describeIntent(s: GameState, i: Intent): string {
|
||||
* replay cannot drift into two different pictures of the same board.
|
||||
*/
|
||||
/**
|
||||
* The board as ONE SEAT sees it.
|
||||
* ONE DISTRICT'S BOARD, BY SEAT — the cards on the table and the cars standing on them (Gitea#20
|
||||
* step 1).
|
||||
*
|
||||
* `viewer` decides whose district, whose hand and whose facilities the Frame carries — everything
|
||||
* else (the Division, the timetable, the clock) is common to the table. It defaults to seat 0, which
|
||||
* is what solitaire and every replay want, so existing callers are unaffected.
|
||||
* A district's BOARD is public. Everyone at the table can see the cards somebody has laid, the cars
|
||||
* standing on them and the trains in the Office Area; what is private is a player's HAND, their
|
||||
* objective and their Revenue detail, none of which is here. That split is why this can be handed to
|
||||
* a seatless spectator unchanged.
|
||||
*
|
||||
* This was hardcoded to 0 throughout. That was correct while there was one player and would have
|
||||
* been a quiet disaster with more: every seat would have been shown player 0's railroad, including
|
||||
* player 0's hand, which is the one thing the state model calls secret.
|
||||
* **KEYED BY SEAT, NOT BY PLAYER, and that is not a detail.** Employee Rotation moves players
|
||||
* between districts, so district ownership cannot be assumed to match player index — the board
|
||||
* belongs to the POSITION on the Division and the player is whoever is currently sitting there
|
||||
* (`playerAtSeat`). Taking a player here would silently draw the wrong district the first time
|
||||
* anybody rotated.
|
||||
*
|
||||
* `seat` is also the "home seat" for `carLabel`, which marks a load THIS district made — the printed
|
||||
* game turns the chip upside down in the tray, and a load may not be broken in the Office Area that
|
||||
* made it. For a player's own view that seat is theirs; for a spectator's view of district N it is
|
||||
* N, which is the same fact asked from outside.
|
||||
*/
|
||||
export function snapshot(
|
||||
/**
|
||||
* WHAT AN ENHANCEMENT DOES — AND WHETHER IT CAN DO IT RIGHT NOW (#101).
|
||||
*
|
||||
* `enhancementText(key)` takes only the key, so it says the same thing for ever. That is right for
|
||||
* every enhancement except the three dispatch devices, which are "once a day": a spent Radio read
|
||||
* "Once a day, add +12…" all Day after it was gone, which is `trainRules` before #100 in a different
|
||||
* corner of the same view.
|
||||
*
|
||||
* AND THE FEDORA, which is the half that actually surprises. `spendDispatchBonus` (advance.ts) reads
|
||||
* the SUPERINTENDENT's own devices, not the train owner's, and the Fedora moves every
|
||||
* `STAGES_PER_SHIFT` Stages — so a device does nothing at all while somebody else is dispatching,
|
||||
* and is spent automatically, without its owner being asked, while they are.
|
||||
*
|
||||
* `dispatchBonus` decides what counts as a device, rather than a list of three keys written out
|
||||
* here: the ladder lives in `ENHANCEMENT_RULES` and a fourth rung would otherwise be silently
|
||||
* exempt.
|
||||
*/
|
||||
function enhancementState(
|
||||
s: GameState,
|
||||
lines: { text: string; tone: string }[],
|
||||
where: { row: number; col: number } | null,
|
||||
whereFrom: { row: number; col: number } | null = null,
|
||||
decision: Decision | null = null,
|
||||
wasted = false,
|
||||
viewer: PlayerIndex = 0,
|
||||
): Frame {
|
||||
const area = areaOf(s, viewer);
|
||||
const viewerSeat = seatOf(s, viewer);
|
||||
area: OfficeArea,
|
||||
seat: SeatIndex,
|
||||
key: string,
|
||||
): { what: string; spent: boolean } {
|
||||
const base = enhancementText(key) ?? prettyKey(key);
|
||||
if (enhancementRule(key)?.dispatchBonus === undefined) return { what: base, spent: false };
|
||||
|
||||
const spent = area.dispatchUsedToday.includes(key);
|
||||
if (spent) {
|
||||
return {
|
||||
what: `${base} SPENT for today — it comes back at the start of the next Day.`,
|
||||
spent: true,
|
||||
};
|
||||
}
|
||||
// Available, but only to whoever is dispatching. Naming the shift length is the difference
|
||||
// between "not now" and knowing how long "not now" lasts.
|
||||
if (seatOf(s, s.clock.superintendent) !== seat) {
|
||||
return {
|
||||
what:
|
||||
`${base} Unspent, but IDLE: a device is only used by the district holding the Fedora, ` +
|
||||
`which moves every ${STAGES_PER_SHIFT} Stages.`,
|
||||
spent: false,
|
||||
};
|
||||
}
|
||||
return { what: `${base} Available today, and this district is dispatching.`, spent: false };
|
||||
}
|
||||
|
||||
export function projectDistrict(
|
||||
s: GameState,
|
||||
seat: SeatIndex,
|
||||
): { cells: CellView[]; facilities: FacilityView[]; runningRow: number; limits: { west: number; east: number } } {
|
||||
const area = areaAtSeat(s, seat);
|
||||
const cells: CellView[] = [];
|
||||
const facilities: FacilityView[] = [];
|
||||
for (const [key, card] of area.grid) {
|
||||
@@ -1196,7 +1329,7 @@ export function snapshot(
|
||||
else if (g.kind === 'spaceUse') label = prettyKey(g.key);
|
||||
else label = geometryLabel(g.geometry);
|
||||
|
||||
const fv = facilityView(card as never, officeProfile(area.tier).name, viewerSeat);
|
||||
const fv = facilityView(card as never, officeProfile(area.tier).name, seat);
|
||||
if (fv) facilities.push(fv);
|
||||
|
||||
cells.push({
|
||||
@@ -1208,16 +1341,34 @@ export function snapshot(
|
||||
what: cellDescription(card, officeProfile(area.tier).name, row === area.runningRow),
|
||||
links: connectionsFor(card).map(([a, b]) => `${a}${b}`),
|
||||
enhancements: card.enhancements.map(prettyKey),
|
||||
enhancementsWhat: card.enhancements.map((k) => enhancementText(k) ?? prettyKey(k)),
|
||||
trains: trainsOnCard(s, viewerSeat, key),
|
||||
enhancementsWhat: card.enhancements.map((k) => enhancementState(s, area, seat, k).what),
|
||||
enhancementsSpent: card.enhancements.map((k) => enhancementState(s, area, seat, k).spent),
|
||||
trains: trainsOnCard(s, seat, key),
|
||||
adTracks: card.geometry.kind === 'office' ? officeProfile(area.tier).adTracks : null,
|
||||
cars: carsOn(card).map((c) => carLabel(c, viewerSeat)),
|
||||
cars: carsOn(card).map((c) => carLabel(c, seat)),
|
||||
standingWest: card.standingWest,
|
||||
facility: fv,
|
||||
});
|
||||
}
|
||||
|
||||
const division: DivisionView[] = s.division.nodes.map((n) => {
|
||||
return {
|
||||
cells,
|
||||
facilities,
|
||||
runningRow: area.runningRow,
|
||||
limits: { west: area.limitsWest.col, east: area.limitsEast.col },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* THE DIVISION — every district's cell, the Mainline between them, and both Division Points.
|
||||
*
|
||||
* Wholly public and always was: it reads no hand, no objective and no per-viewer state, so a
|
||||
* spectator's Division map and a player's are the same picture. It is extracted rather than
|
||||
* rewritten for exactly that reason — the public view must not be a second implementation that can
|
||||
* drift from the one players look at.
|
||||
*/
|
||||
export function projectDivision(s: GameState): DivisionView[] {
|
||||
return s.division.nodes.map((n) => {
|
||||
if (n.kind === 'divisionPoint') {
|
||||
return {
|
||||
kind: 'dp',
|
||||
@@ -1245,10 +1396,31 @@ export function snapshot(
|
||||
* one per Stage — and the entry point is what the rules actually move. There is nothing left
|
||||
* to reconstruct.
|
||||
*/
|
||||
// One region per Stage, straight off the card's own count: what a train has LEFT to run says
|
||||
// where it is standing. `regionOfTransit` is the engine's own answer, so the picture and the
|
||||
// collision rule cannot disagree about who is where.
|
||||
const place = (t: { stagesRemaining: number }): number => regionOfTransit(n.card, t.stagesRemaining);
|
||||
/**
|
||||
* AND WHICH WAY IT CAME IN (Gitea#22). `regionOfTransit` counts from the end the train
|
||||
* ENTERED — everything still to run is region 0 — and both directions share that one index
|
||||
* space, which is what the collision rules want and why the engine asks it directly.
|
||||
*
|
||||
* The map is asking a different question: which printed box, LEFT TO RIGHT. East is right
|
||||
* here and always has been, so for an eastbound train the two questions have the same answer
|
||||
* by luck — it enters at the west end, so "just entered" and "leftmost box" coincide. A
|
||||
* westbound train enters at the EAST end, so its region 0 is the right-hand box, and using
|
||||
* the travel index directly drew the whole card mirrored.
|
||||
*
|
||||
* That cost a collision (seed 550943578, undo 187): a westbound TX17 that had just entered
|
||||
* was drawn WEST of a westbound T5 that was nearly across, so the train physically behind
|
||||
* appeared to be the one in front. Train 3 was cleared to follow T5 and ran into TX17 —
|
||||
* where the rules had always had it.
|
||||
*
|
||||
* So the engine's index is turned into a place on the map here, once, at the boundary the
|
||||
* map is drawn from. `regionOfTransit` keeps its meaning and the collision rules are
|
||||
* untouched; only the picture changes.
|
||||
*/
|
||||
const place = (t: { stagesRemaining: number; direction: Direction }): number => {
|
||||
const travelled = regionOfTransit(n.card, t.stagesRemaining);
|
||||
const regions = mainlineProfile(n.card).regions;
|
||||
return t.direction === 'west' ? regions - 1 - travelled : travelled;
|
||||
};
|
||||
return {
|
||||
kind: 'ml',
|
||||
label: name,
|
||||
@@ -1331,39 +1503,65 @@ export function snapshot(
|
||||
modifiers: [],
|
||||
gradeUp: null,
|
||||
seat: n.seat,
|
||||
// Straight off the node the engine sets (#94). Public to every seat — a flag on the table is
|
||||
// seen by everyone at it — so this is not redacted by viewer and must not become so.
|
||||
redFlag: n.redFlag ?? null,
|
||||
running,
|
||||
switching: below,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* WHO THE GAME IS WAITING ON — the one answer, asked one way (Gitea#20 step 1).
|
||||
*
|
||||
* TWO THINGS HAVE TO BE TRUE AT ONCE, and each was somewhere else before #96 put them together.
|
||||
*
|
||||
* `clock.currentActor` alone is not it: the engine sets that null while an interruption is standing
|
||||
* — a §8.1 clearance goes to the Superintendent, a Yard Office offer to the district's owner — so a
|
||||
* view reading the raw field reports "nobody" during exactly the moments a player is being waited
|
||||
* on. `actingPlayer` knows that rule and is the engine's own answer to it.
|
||||
*
|
||||
* `actingPlayer` alone is not it either, and THIS is what #96 was: it has no status guard, so when
|
||||
* the game is not running it hands back whatever `clock.currentActor` was left holding — the last
|
||||
* seat to move before the timetable ran out. The §3.3 vote is the state that exposed it. That vote
|
||||
* is PARALLEL, open to every un-voted seat at once, and `apply.ts` says in as many words that there
|
||||
* is no actor to be; the screen named the last mover anyway, beside a tally correctly showing three
|
||||
* seats outstanding.
|
||||
*
|
||||
* So: nobody is acting unless the game is `active`, and when it is, `actingPlayer` decides who.
|
||||
*
|
||||
* `currentActor(game)` in `web/game.ts` is this function taking a `Game`, and delegates to it —
|
||||
* ONE answer, not two that agree until they don't. That matters more than it looks: `currentActor`
|
||||
* is what refuses an intent, so a screen answering differently tells the table to wait on a player
|
||||
* the server would turn away.
|
||||
*/
|
||||
export function currentActorOfState(s: GameState): PlayerIndex | null {
|
||||
if (s.status !== 'active') return null;
|
||||
return actingPlayer(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* THE TABLE, AS EVERY SEAT SEES IT IDENTICALLY (Gitea#20 step 1).
|
||||
*
|
||||
* The clock, the phase, whose turn it is, the timetable, the yards, the deck COUNTS, the score and
|
||||
* the house rules. Nothing here is redacted, and nothing here may become redacted: the whole point
|
||||
* is that a spectator and a player read the same table state, so a field that has to differ by seat
|
||||
* belongs in the player's own frame instead.
|
||||
*
|
||||
* Deck contents are counts and top-of-pile names only. A Department pile is FACE UP — a discard goes
|
||||
* onto one precisely so a rival can take it — so naming its top card gives nothing away; the Home
|
||||
* Office deck is face down and appears here as a length and nothing else.
|
||||
*/
|
||||
export function projectSharedTable(s: GameState) {
|
||||
return {
|
||||
day: s.clock.day,
|
||||
stage: s.clock.stage,
|
||||
clock: clockTime(s.clock.stage),
|
||||
phase: phaseLabel(s.clock.phase),
|
||||
phaseKey: s.clock.phase,
|
||||
actor: s.clock.currentActor,
|
||||
actor: currentActorOfState(s),
|
||||
superintendent: s.clock.superintendent,
|
||||
revenue: s.players[viewer]?.revenue ?? 0,
|
||||
lines,
|
||||
where,
|
||||
whereFrom,
|
||||
division,
|
||||
cells,
|
||||
facilities,
|
||||
/**
|
||||
* NEWEST FIRST, matching the play page (`actionMenu`).
|
||||
*
|
||||
* The engine pushes a drawn card onto the END of the hand, which put the card just turned over
|
||||
* at the far end of a wrapping row. Reversed here rather than in the engine so the bot's hand
|
||||
* iteration — and every revenue measurement taken with it — is left alone.
|
||||
*
|
||||
* Both lines must reverse together or the descriptions come apart from the names.
|
||||
*/
|
||||
hand: [...(s.decks.hands.get(viewer) ?? [])].reverse().map((id) => cardName(s, id)),
|
||||
handWhat: [...(s.decks.hands.get(viewer) ?? [])].reverse().map((id) => cardDescription(s, id)),
|
||||
handDiscardable: [...(s.decks.hands.get(viewer) ?? [])].reverse().map((id) => keepReason(s, id) === null),
|
||||
handKeepWhy: [...(s.decks.hands.get(viewer) ?? [])].reverse().map((id) => keepReason(s, id)),
|
||||
deck: s.decks.homeOffice.length,
|
||||
departments: s.decks.departments.map((pile) => {
|
||||
const top = pile[pile.length - 1];
|
||||
@@ -1388,9 +1586,6 @@ export function snapshot(
|
||||
},
|
||||
timetable: [...s.timetable],
|
||||
timetableWhat: s.timetable.map((n) => (n === null ? null : trainRules({ trainNumber: n, trainIsExtra: false }))),
|
||||
decision,
|
||||
wasted,
|
||||
option: turnOf(s, viewer).option,
|
||||
houseRules: houseRules(s.config),
|
||||
mode: s.config.mode,
|
||||
optionalRules: s.config.optionalRules,
|
||||
@@ -1411,23 +1606,14 @@ export function snapshot(
|
||||
seat: seatOf(s, p.index),
|
||||
name: p.name,
|
||||
revenue: p.revenue,
|
||||
// A COUNT, never the cards. Hand SIZE is public — you can see how many cards somebody holds
|
||||
// across a table — and this is the only thing about another player's hand that may be here.
|
||||
hand: (s.decks.hands.get(p.index) ?? []).length,
|
||||
})),
|
||||
viewer,
|
||||
viewerSeat,
|
||||
openingRolls: {
|
||||
division: [...s.openingRolls.division],
|
||||
superintendent: [...s.openingRolls.superintendent],
|
||||
},
|
||||
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 },
|
||||
movesLeft: s.clock.phase === 'localOps' && turnOf(s, viewer).option === 'switch' ? turnOf(s, viewer).movesRemaining : null,
|
||||
moves: switchingMoves(s, viewer),
|
||||
blocked: impediments(s, viewer),
|
||||
trains: [...s.trays.values()].map((t) => ({
|
||||
label: t.trainNumber === null ? 'local crew' : `Train ${t.trainIsExtra ? 'X' : ''}${t.trainNumber}`,
|
||||
where:
|
||||
@@ -1437,6 +1623,166 @@ export function snapshot(
|
||||
? `Mainline card ${t.position.index}`
|
||||
: `Office Area (${t.position.coord.col},${t.position.coord.row})`,
|
||||
})),
|
||||
/**
|
||||
* THE CREW TRAY POOL, WHICH IS §7's SCARCITY MECHANIC (#98).
|
||||
*
|
||||
* `state.ts` calls it explicit, and it was explicit only in the engine: there are fewer trays
|
||||
* than there are trains wanting one, and nothing said how many were left. Public without
|
||||
* question — the trays are physical objects in the middle of the table, and this is a count
|
||||
* beside the deck and yard counts already here.
|
||||
*/
|
||||
crewTrays: { free: s.freeTrays.length, total: crewTrayCount(s.players.length) },
|
||||
/**
|
||||
* THE TRAINS QUEUED FOR ONE — the other half, and the half that had been promised in words.
|
||||
*
|
||||
* Playing an Extra says "it runs once as soon as a Crew Tray frees up"; ordering a second
|
||||
* section says "an identical train will run right behind it". Both were announced once in the
|
||||
* log and then existed only in the engine, so neither promise was ever visibly kept. Who played
|
||||
* an Extra is public: §7 gives the train to the player who played the card, in the open.
|
||||
*/
|
||||
queued: {
|
||||
extras: s.pendingExtras.map((x) => ({ trainNumber: x.trainNumber, player: x.player })),
|
||||
secondSections: [...s.pendingSecondSections],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** One district as a spectator sees it: whose seat it is, who is sitting there, and its board. */
|
||||
export type PublicDistrict = {
|
||||
seat: SeatIndex;
|
||||
player: PlayerIndex;
|
||||
name: string;
|
||||
cells: CellView[];
|
||||
facilities: FacilityView[];
|
||||
runningRow: number;
|
||||
limits: { west: number; east: number };
|
||||
};
|
||||
|
||||
/** What a seatless viewer may be shown: the table, the Division, and every district's board. */
|
||||
export type PublicFrame = ReturnType<typeof projectSharedTable> & {
|
||||
division: DivisionView[];
|
||||
districts: PublicDistrict[];
|
||||
};
|
||||
|
||||
/**
|
||||
* THE WHOLE GAME AS A SPECTATOR MAY SEE IT — no seat, no hand, no secrets (Gitea#20 step 1).
|
||||
*
|
||||
* **Built from the same lower-level projections a player's frame is, and deliberately NOT by calling
|
||||
* `snapshot()` once per seat.** That shortcut is the trap: `snapshot` exists to assemble one
|
||||
* player's view and carries their hand, their objective, their Revenue detail and their legal moves,
|
||||
* so a public view made of player views starts by constructing everything it then has to remember to
|
||||
* strip. It also defaults its viewer to player zero, which means a careless spectator call today
|
||||
* serves seat 0's hand. Composing upward instead means a private field cannot arrive here by
|
||||
* accident: it would have to be added to a projection that has no business holding one.
|
||||
*
|
||||
* **Districts are keyed by SEAT and the player is resolved through `playerAtSeat`.** Employee
|
||||
* Rotation moves players between districts, so seat and player index are not interchangeable, and
|
||||
* a public board that assumed they were would relabel every district the first time anybody rotated.
|
||||
*
|
||||
* What is NOT here, and why each: `hand`/`handWhat`/`handDiscardable`/`handKeepWhy` and `handCount`
|
||||
* (the cards a seat holds), `objective` (a private goal), `option`/`movesLeft`/`moves` (one player's
|
||||
* legal actions, which describe what they are ABOUT to do), `blocked` (computed per viewer and
|
||||
* partly about their own crews), `decision`, `viewer`/`viewerSeat`, and the narration log — which
|
||||
* `session.ts` sends incrementally and which is checked separately, because two of the leaks found
|
||||
* in v0.7.9.2 lived there rather than in any frame.
|
||||
*/
|
||||
export function publicSnapshot(s: GameState): PublicFrame {
|
||||
return {
|
||||
...projectSharedTable(s),
|
||||
division: projectDivision(s),
|
||||
districts: [...s.officeAreas.keys()].sort((a, b) => a - b).map((seat) => {
|
||||
const player = playerAtSeat(s, seat);
|
||||
return {
|
||||
seat,
|
||||
player,
|
||||
// Through `seatLabel`, like every other seat a person reads: the internal index is
|
||||
// zero-based and the spoken number is not (`session.test.ts` guards the conversion).
|
||||
name: s.players[player]?.name ?? `Seat ${seatLabel(seat)}`,
|
||||
...projectDistrict(s, seat),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The board as ONE SEAT sees it.
|
||||
*
|
||||
* `viewer` decides whose district, whose hand and whose facilities the Frame carries — everything
|
||||
* else (the Division, the timetable, the clock) is common to the table. It defaults to seat 0, which
|
||||
* is what solitaire and every replay want, so existing callers are unaffected.
|
||||
*
|
||||
* This was hardcoded to 0 throughout. That was correct while there was one player and would have
|
||||
* been a quiet disaster with more: every seat would have been shown player 0's railroad, including
|
||||
* player 0's hand, which is the one thing the state model calls secret.
|
||||
*/
|
||||
export function snapshot(
|
||||
s: GameState,
|
||||
lines: { text: string; tone: string }[],
|
||||
where: { row: number; col: number } | null,
|
||||
whereFrom: { row: number; col: number } | null = null,
|
||||
decision: Decision | null = null,
|
||||
wasted = false,
|
||||
viewer: PlayerIndex = 0,
|
||||
): Frame {
|
||||
const viewerSeat = seatOf(s, viewer);
|
||||
|
||||
const { cells, facilities, runningRow, limits } = projectDistrict(s, viewerSeat);
|
||||
const division = projectDivision(s);
|
||||
return {
|
||||
/**
|
||||
* THE SHARED TABLE COMES FROM THE SAME PROJECTION THE COMMON BOARD USES (Gitea#20 step 1).
|
||||
*
|
||||
* Spread rather than restated, so a player's frame and a spectator's cannot come to disagree
|
||||
* about the clock, the phase, whose turn it is or the score. Everything after this point is
|
||||
* either private to `viewer` or a viewer-specific slice; none of it shadows a shared field, and
|
||||
* one that did would be exactly the bug this arrangement exists to make visible.
|
||||
*/
|
||||
...projectSharedTable(s),
|
||||
/**
|
||||
* The three interruptions §8.1 and Gitea#5/#19 can raise, said in the words the prompt itself
|
||||
* uses. `decisionActor` above decides WHO; this is only what they are looking at.
|
||||
*/
|
||||
awaiting: (() => {
|
||||
const d = s.clock.pendingDecision;
|
||||
if (!d) return null;
|
||||
const train = trainName(s, d.train);
|
||||
if (d.kind === 'clearance') return { asks: 'a clearance ruling', train };
|
||||
if (d.kind === 'yardOffice') return { asks: 'the Yard Office offer', train };
|
||||
return { asks: 'a Red Flag', train };
|
||||
})(),
|
||||
revenue: s.players[viewer]?.revenue ?? 0,
|
||||
lines,
|
||||
where,
|
||||
whereFrom,
|
||||
division,
|
||||
cells,
|
||||
facilities,
|
||||
/**
|
||||
* NEWEST FIRST, matching the play page (`actionMenu`).
|
||||
*
|
||||
* The engine pushes a drawn card onto the END of the hand, which put the card just turned over
|
||||
* at the far end of a wrapping row. Reversed here rather than in the engine so the bot's hand
|
||||
* iteration — and every revenue measurement taken with it — is left alone.
|
||||
*
|
||||
* Both lines must reverse together or the descriptions come apart from the names.
|
||||
*/
|
||||
hand: [...(s.decks.hands.get(viewer) ?? [])].reverse().map((id) => cardName(s, id)),
|
||||
handWhat: [...(s.decks.hands.get(viewer) ?? [])].reverse().map((id) => cardDescription(s, id)),
|
||||
handDiscardable: [...(s.decks.hands.get(viewer) ?? [])].reverse().map((id) => keepReason(s, id) === null),
|
||||
handKeepWhy: [...(s.decks.hands.get(viewer) ?? [])].reverse().map((id) => keepReason(s, id)),
|
||||
decision,
|
||||
wasted,
|
||||
option: turnOf(s, viewer).option,
|
||||
viewer,
|
||||
viewerSeat,
|
||||
handCount: (s.decks.hands.get(viewer) ?? []).length,
|
||||
overHandLimit: overHandLimit(s, viewer),
|
||||
objective: objectiveOf(s, viewer),
|
||||
runningRow,
|
||||
limits,
|
||||
movesLeft: s.clock.phase === 'localOps' && turnOf(s, viewer).option === 'switch' ? turnOf(s, viewer).movesRemaining : null,
|
||||
moves: switchingMoves(s, viewer),
|
||||
blocked: impediments(s, viewer),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1607,6 +1953,12 @@ export function cardDescription(s: GameState, id: string): string {
|
||||
export function trainRules(t: {
|
||||
trainNumber: number | null;
|
||||
trainIsExtra: boolean;
|
||||
/**
|
||||
* X17 only — whether the speeches are made, which is what decides which HALF of its printed rule
|
||||
* the train is currently living under (#100). Optional because the timetable renders a train
|
||||
* number with no tray behind it; absent means "not yet", which is the state a train starts in.
|
||||
*/
|
||||
speechMade?: boolean;
|
||||
}): string {
|
||||
const p = trainProfile(t.trainNumber ?? 0, t.trainIsExtra);
|
||||
if (!p) return '';
|
||||
@@ -1651,11 +2003,25 @@ export function trainRules(t: {
|
||||
if (p.rules.pickUpEmptiesOnly) {
|
||||
parts.push('EMPTIES ONLY — it may not couple a loaded car. A caboose is not a load.');
|
||||
}
|
||||
/**
|
||||
* WHICH HALF OF ITS RULE THE CAMPAIGN TRAIN IS IN (#100).
|
||||
*
|
||||
* "One turn at station (speeches) then expedite" is two states, not one sentence. This used to
|
||||
* print the sentence and stop, so the chip read identically before and after the speeches — while
|
||||
* the fault the second half creates was warned about only under `expedite`, i.e. to every train
|
||||
* EXCEPT the one that had just become subject to it.
|
||||
*/
|
||||
if (p.rules.stopThenExpedite) {
|
||||
parts.push('STOPS ONCE FOR SPEECHES, then runs expedited from its next Office onward');
|
||||
parts.push(
|
||||
t.speechMade
|
||||
? 'SPEECHES MADE — it runs EXPEDITED from here on'
|
||||
: 'STOPS ONCE FOR SPEECHES at its first Office, then runs expedited from the next one onward',
|
||||
);
|
||||
}
|
||||
|
||||
if (p.rules.expedite) {
|
||||
// `isExpedited` (advance.ts) is the engine's own test, borrowed rather than restated: a card that
|
||||
// described a rule the engine did not apply — or the reverse — is the whole failure this is in.
|
||||
if (isExpedited(t)) {
|
||||
// It is released and switched exactly like any other train — the restriction is on where it may
|
||||
// be LEFT, not on when it leaves.
|
||||
parts.push(
|
||||
|
||||
+106
-26
@@ -30,7 +30,7 @@ import type { Intent } from '../engine/intents.ts';
|
||||
import { legalActions } from '../engine/legal.ts';
|
||||
import { createGame } from '../engine/setup.ts';
|
||||
import type { CardId, GameConfig, GameState, PlayerIndex } from '../engine/state.ts';
|
||||
import { actingPlayer } from '../engine/state.ts';
|
||||
import { overHandLimit as overHandLimitOf } from '../engine/state.ts';
|
||||
import { playerAtSeat } from '../engine/state.ts';
|
||||
import { cuesFor, narrate } from '../sim/narrate.ts';
|
||||
// Import from the view module, NOT replay.ts — replay.ts writes files and reads process.argv,
|
||||
@@ -38,6 +38,7 @@ import { cuesFor, narrate } from '../sim/narrate.ts';
|
||||
import {
|
||||
cardDescription,
|
||||
cardName,
|
||||
currentActorOfState,
|
||||
describeIntent,
|
||||
geometryLabel,
|
||||
snapshot,
|
||||
@@ -49,7 +50,6 @@ import {
|
||||
DEFAULT_HOUSE_RULES,
|
||||
DEFAULT_MAX_COLLISIONS_PER_DAY,
|
||||
DEFAULT_MAX_COLLISIONS_TOTAL,
|
||||
HAND_LIMIT,
|
||||
LEGACY_HOUSE_RULES,
|
||||
collectiveRevenueFloor,
|
||||
houseRules,
|
||||
@@ -134,10 +134,25 @@ export type NewGameOptions = {
|
||||
|
||||
/** The same config with the New Game dialog's answers in it. */
|
||||
export function configWith(opts: NewGameOptions): GameConfig {
|
||||
const days = opts.days ?? SOLO_CONFIG.days;
|
||||
return {
|
||||
...SOLO_CONFIG,
|
||||
days: opts.days ?? SOLO_CONFIG.days,
|
||||
minCombinedRevenue: opts.minCombinedRevenue ?? SOLO_CONFIG.minCombinedRevenue,
|
||||
days,
|
||||
/**
|
||||
* DERIVED FROM THE DAYS ACTUALLY IN PLAY, not from `SOLO_CONFIG`'s five-Day constant.
|
||||
*
|
||||
* It fell back to the constant until 2026-08-30, so `configWith({ days: 1 })` asked a one-Day
|
||||
* game to clear **15** — a floor a five-Day game averages barely half of — and
|
||||
* `configWith({ days: 10 })` asked for the same 15 a five-Day game does. The two fields silently
|
||||
* disagreed, which is the one thing a "build me a config" helper must not let happen.
|
||||
*
|
||||
* Not a live fault when it was found: `createLocalSession` is the only caller, and the page
|
||||
* always writes `minCombinedRevenue` itself (`solitaireDefaults` re-derives it from the preset).
|
||||
* Found by a throwaway probe that passed only `days` — which is exactly how the next caller
|
||||
* would use this. At the default day count the answer is unchanged, since `SOLO_CONFIG`'s own
|
||||
* floor is this same formula at `DEFAULT_DAYS`.
|
||||
*/
|
||||
minCombinedRevenue: opts.minCombinedRevenue ?? collectiveRevenueFloor(1, days),
|
||||
maxCollisionsPerDay: opts.maxCollisionsPerDay ?? SOLO_CONFIG.maxCollisionsPerDay,
|
||||
maxCollisionsTotal: opts.maxCollisionsTotal ?? SOLO_CONFIG.maxCollisionsTotal,
|
||||
optionalRules: { ...SOLO_CONFIG.optionalRules, ...(opts.optionalRules ?? {}) },
|
||||
@@ -230,7 +245,6 @@ export type Game = {
|
||||
* had already been played and the hand held three or fewer. Derived from the hand each render, so
|
||||
* it cannot drift out of step with what is actually held.
|
||||
*/
|
||||
mustPlayCard: boolean;
|
||||
/**
|
||||
* Sounds the last batch of events earned, for the page to play and clear.
|
||||
*
|
||||
@@ -297,7 +311,7 @@ export const SOLO_PLAYER = 'Solitaire';
|
||||
|
||||
export function newGame(seed: number, config: GameConfig = SOLO_CONFIG): Game {
|
||||
const state = createGame({ id: `web-${seed}`, seed, config, playerNames: [SOLO_PLAYER] });
|
||||
const game: Game = { state, seed, history: [], log: [], mustPlayCard: false, cues: [], scheduled: null, justDrawn: null, announced: null };
|
||||
const game: Game = { state, seed, history: [], log: [], cues: [], scheduled: null, justDrawn: null, announced: null };
|
||||
// A history that opens mid-Stage reads as though something was missed. Say what the game IS
|
||||
// first, then let the clock take over.
|
||||
game.log.push({ text: 'Game Begins', tone: 'start' });
|
||||
@@ -316,9 +330,23 @@ export function newGame(seed: number, config: GameConfig = SOLO_CONFIG): Game {
|
||||
*/
|
||||
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 };
|
||||
const game: Game = { state, seed, history: [], log: [], 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' });
|
||||
/**
|
||||
* NO SEED AT A TABLE WITH MORE THAN ONE SEAT (Gitea#20 step 1).
|
||||
*
|
||||
* `game.log` is one shared list and `linesSince(seat)` (`server/session.ts`) slices it with no
|
||||
* per-seat filter, so every line here reaches every player. Announcing the seed therefore handed
|
||||
* each of them the whole future of the deal — every card order, every die — in the opening line
|
||||
* of the game. Found while planning the public common board; it is a multiplayer leak with or
|
||||
* without that display, which is why it is fixed here rather than waiting for it.
|
||||
*
|
||||
* `newGame` still records it, deliberately: a solitaire table has nobody to leak to, and the seed
|
||||
* in the log is what a bug report quotes. The rule is "do not tell the OTHER seats", not "write
|
||||
* less down". The seed remains in `game.seed`, in every save (`session.ts` persistence) and in the
|
||||
* lobby record, so nothing administrative or replayable loses it.
|
||||
*/
|
||||
game.log.push({ text: `${config.mode} · ${playerNames.length} players`, tone: 'quiet' });
|
||||
drain(game);
|
||||
return game;
|
||||
}
|
||||
@@ -333,12 +361,18 @@ export function drain(game: Game): void {
|
||||
record(game, pump(game.state));
|
||||
}
|
||||
|
||||
/** Whose turn it is, or null if the game is over or waiting on nothing. */
|
||||
/**
|
||||
* Whose turn it is, or null if the game is over or waiting on nothing.
|
||||
*
|
||||
* `currentActorOfState` (sim/view.ts) IS this, taking the state rather than the `Game` — so this is
|
||||
* the adapter and not a second copy. It used to be the second copy: it carried the status guard and
|
||||
* the view's version did not, which is #96 — the turn chart named the last seat to move all the way
|
||||
* through the §3.3 vote, while this function correctly refused every intent that seat could send.
|
||||
* Two functions that agree until they don't are worse than one, because the disagreement surfaces
|
||||
* as a screen nobody can square with the server.
|
||||
*/
|
||||
export function currentActor(game: Game): PlayerIndex | null {
|
||||
if (game.state.status !== 'active') return null;
|
||||
// `actingPlayer` (state.ts) knows which player each kind of interruption goes to — the
|
||||
// Superintendent for a §8.1 clearance, the district's owner for a Yard Office offer.
|
||||
return actingPlayer(game.state);
|
||||
return currentActorOfState(game.state);
|
||||
}
|
||||
|
||||
/** Every legal action right now, grouped for display. Empty when there is nothing to decide. */
|
||||
@@ -1024,9 +1058,7 @@ function makeUpAdvice(
|
||||
* button with a reason instead of hiding a move that has simply become illegal.
|
||||
*/
|
||||
export function overHandLimit(game: Game, seat: PlayerIndex = 0): boolean {
|
||||
const hand = game.state.decks.hands.get(seat) ?? [];
|
||||
const limit = game.state.decks.redFlags.get(seat) ? HAND_LIMIT + 1 : HAND_LIMIT;
|
||||
return hand.length > limit;
|
||||
return overHandLimitOf(game.state, seat);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1074,7 +1106,6 @@ export function submit(game: Game, intent: Intent, as: PlayerIndex | null = null
|
||||
}
|
||||
game.history.push(intent);
|
||||
record(game, result.events, actor);
|
||||
game.mustPlayCard = overHandLimit(game);
|
||||
drain(game);
|
||||
return true;
|
||||
}
|
||||
@@ -1107,6 +1138,24 @@ export function view(game: Game, seat: PlayerIndex = 0): Frame {
|
||||
return snapshot(game.state, [], null, null, null, false, seat);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold a narration's opening word into the middle of a sentence — "Chose to draw" after a name has
|
||||
* to read "Player Bob chose to draw".
|
||||
*
|
||||
* ONLY A SENTENCE-CASED WORD, which is the whole point. It used to be a flat
|
||||
* `text.charAt(0).toLowerCase()`, so every line opening with an all-caps keyword came out mangled:
|
||||
* `EXTRA X18 started…` rendered as `Player Solitaire eXTRA X18 started…`, and the same happened to
|
||||
* `TRAIN 1 MADE UP` and `COLLISION`. Those words are shouted deliberately.
|
||||
*
|
||||
* `^[A-Z][a-z]` is the test — a capital followed by a lower-case letter is an ordinary word that was
|
||||
* capitalised because it began a sentence, and nothing else is. It leaves all-caps keywords alone,
|
||||
* and it also leaves alone a word whose second character is a digit or a hyphen (`X22 Pee-Dee`),
|
||||
* which a naive "is it uppercase?" check would get wrong because `'2'.toUpperCase() === '2'`.
|
||||
*/
|
||||
function uncapitalise(text: string): string {
|
||||
return /^[A-Z][a-z]/.test(text) ? text.charAt(0).toLowerCase() + text.slice(1) : text;
|
||||
}
|
||||
|
||||
function record(game: Game, events: GameEvent[], actor: PlayerIndex | null = null): void {
|
||||
const who = actor === null ? null : (game.state.players[actor]?.name ?? null);
|
||||
for (const e of events) {
|
||||
@@ -1116,10 +1165,28 @@ function record(game: Game, events: GameEvent[], actor: PlayerIndex | null = nul
|
||||
cardName: (id) => cardName(game.state, id),
|
||||
trainName: (id) => trainName(game.state, id),
|
||||
});
|
||||
/**
|
||||
* A BLIND DRAW IS PUBLIC; WHICH CARD CAME UP IS NOT (Gitea#20 step 1).
|
||||
*
|
||||
* Everybody at the table sees a hand go to the Home Office deck, so the draw itself belongs in
|
||||
* the shared log. The card's NAME does not: the deck is face down, and this log goes to every
|
||||
* seat unfiltered, so naming it told three opponents exactly what the fourth was holding.
|
||||
*
|
||||
* A DEPARTMENT SLOT IS NOT THE SAME and stays named. Those piles are face up — a discard goes
|
||||
* onto one precisely so a rival can take it — so the card was public before it was drawn, and
|
||||
* hiding it would lose real information for no gain.
|
||||
*
|
||||
* The drawing seat still learns what it got. `justDrawn` below is the owner-only channel and
|
||||
* `session.ts` sends it to that seat alone, so this costs the drawer nothing. Solitaire keeps
|
||||
* the name for the same reason it keeps the seed: a one-seat table has nobody to leak to, and
|
||||
* a solo player's history naming their own draw is the record rather than a leak.
|
||||
*/
|
||||
const blindDraw = e.type === 'cardDrawn' && e.source === 'homeOffice' && game.state.players.length > 1;
|
||||
const said = blindDraw ? 'Drew a card from the Home Office deck' : n.text;
|
||||
// "Chose to DRAW a card" does not say WHO, which is unreadable the moment there is more than
|
||||
// one seat. Only events the player caused are attributed; the Division running itself is not.
|
||||
const mine = who !== null && 'player' in e;
|
||||
const text = mine ? `Player ${who} ${n.text.charAt(0).toLowerCase()}${n.text.slice(1)}` : n.text;
|
||||
const text = mine ? `Player ${who} ${uncapitalise(said)}` : said;
|
||||
game.log.push({ text, tone: mine ? 'act' : n.tone });
|
||||
|
||||
}
|
||||
@@ -1220,7 +1287,18 @@ export function fromSave(save: Save, config: GameConfig = SOLO_CONFIG): Game {
|
||||
const result = applyIntent(game.state, actor, intent);
|
||||
if (!result.ok) break;
|
||||
game.history.push(intent);
|
||||
record(game, result.events);
|
||||
/**
|
||||
* `actor` IS PASSED HERE, so a replayed game narrates exactly as the live one did.
|
||||
*
|
||||
* It was omitted, and the omission was invisible in solitaire for a reason worth keeping: the
|
||||
* only test that compares logs ("leaves nothing in the log describing a move that was taken
|
||||
* back") compares one `fromSave`-built log against ANOTHER, so the missing attribution cancelled
|
||||
* out on both sides. Live play attributes (`submit` passes `actor`) and so does multiplayer's
|
||||
* replay (`fromMultiplayerSave`) — this was the one path of the three that did not, which meant
|
||||
* a restored save, an undone game (undo rebuilds through here) and the replay viewer all
|
||||
* described the same moves in different words from the game that produced them.
|
||||
*/
|
||||
record(game, result.events, actor);
|
||||
drain(game);
|
||||
}
|
||||
return game;
|
||||
@@ -1234,16 +1312,18 @@ export function fromSave(save: Save, config: GameConfig = SOLO_CONFIG): Game {
|
||||
* 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,
|
||||
* LIKE `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.
|
||||
* resumed game hits every time.
|
||||
*
|
||||
* `fromSave` HAD THE SAME GAP AND NO LONGER DOES (fixed 2026-08-30). It predated multiplayer, and
|
||||
* nothing ever compared its output against a LIVE-played log: `undo`'s rebuilt game is itself
|
||||
* `fromSave`-built, so `test/web.test.ts`'s replay-fidelity test only ever compared one unattributed
|
||||
* replay against another and the gap cancelled out on both sides. The test that now pins it plays a
|
||||
* game live, restores it from its own save, and asserts the two logs are identical — which is the
|
||||
* comparison that had been missing rather than a new requirement.
|
||||
*/
|
||||
/**
|
||||
* Why the intent a replay stopped at is reported rather than swallowed.
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@ footer{margin-top:26px;color:var(--dim);font-size:11px;display:flex;gap:18px;fle
|
||||
|
||||
<footer>
|
||||
<span>build <span id="build">__BUILD__</span></span>
|
||||
<span>solitaire runs entirely in your browser — no server code required</span>
|
||||
<span>Multiplayer runs on StartOS server. Solitaire runs entirely in your browser.</span>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
|
||||
+18
-25
@@ -256,25 +256,21 @@ export function runLobby(handlers: LobbyHandlers, resume?: { token: string; game
|
||||
else if (type === 'custom') type = base;
|
||||
for (const r of typeRadios()) r.checked = r.value === type;
|
||||
|
||||
const scoring = preset(base).scoring;
|
||||
const note = $('lb-type-note');
|
||||
if (type === 'custom') {
|
||||
note.textContent =
|
||||
`${gameTypeLabel('custom', scoring)} · ${differing.length} ` +
|
||||
`${differing.length === 1 ? 'setting differs' : 'settings differ'} from ${preset(base).label}.`;
|
||||
note.className = 'ng-note changed-note';
|
||||
// A Custom game is nobody's default: open the block that says how it differs.
|
||||
$<HTMLDetailsElement>('lb-settings').open = true;
|
||||
} else {
|
||||
note.textContent = preset(type as PresetName).blurb;
|
||||
note.className = 'ng-note';
|
||||
}
|
||||
/**
|
||||
* NO SENTENCE UNDER THE RADIOS since 2026-08-30 — it restated the type just chosen to the person
|
||||
* who had just chosen it, and the row is already labelled and already carries its own
|
||||
* description (Jesse: "There's no need to repeat it below"). `form.mark` still puts a hint on
|
||||
* each row that actually differs, which is where a Custom game's differences can be acted on.
|
||||
*/
|
||||
// A Custom game is nobody's default: open the block that says how it differs.
|
||||
if (type === 'custom') $<HTMLDetailsElement>('lb-settings').open = true;
|
||||
}
|
||||
|
||||
for (const r of typeRadios()) {
|
||||
// Solitaire is on this screen so the two screens read as one list, but there is nothing here to
|
||||
// deal it with — the New Game dialog is where a solitaire game comes from.
|
||||
if (r.value === 'solitaire') markUnavailable(r, 'dealt with the New game button, not here');
|
||||
// deal it with. Dimmed and left to speak for itself: the heading says "Game type
|
||||
// (multi-player)", which is the explanation (Jesse, 2026-08-30).
|
||||
if (r.value === 'solitaire') markUnavailable(r);
|
||||
r.onchange = () => {
|
||||
if (!r.checked) return;
|
||||
if (r.value === 'custom') {
|
||||
@@ -615,18 +611,15 @@ export function prefillCode(code: string): void {
|
||||
*
|
||||
* Reported by Jesse 2026-08-23: "solitaire is disabled, but really hard to tell." A bare `disabled`
|
||||
* on a radio leaves the whole row at full strength — the dot simply refuses the click, which reads
|
||||
* as a broken control rather than an unavailable one. Dims the row and says why, once.
|
||||
* as a broken control rather than an unavailable one.
|
||||
*
|
||||
* The dimming is the whole signal now. It used to append a reason to the row as well, and dropped
|
||||
* that in 2026-08-30 along with the same text on the solitaire screen: one heading naming which
|
||||
* game the screen deals says it once, where three dimmed rows each said it again.
|
||||
*/
|
||||
function markUnavailable(radio: HTMLInputElement, why: string): void {
|
||||
function markUnavailable(radio: HTMLInputElement): void {
|
||||
radio.disabled = true;
|
||||
const row = radio.closest('label');
|
||||
if (!row) return;
|
||||
row.classList.add('disabled');
|
||||
if (row.querySelector('.lb-why')) return;
|
||||
const note = document.createElement('span');
|
||||
note.className = 'lb-why';
|
||||
note.textContent = ` — ${why}`;
|
||||
row.querySelector('span')?.appendChild(note);
|
||||
radio.closest('label')?.classList.add('disabled');
|
||||
}
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
|
||||
+346
-137
@@ -36,7 +36,7 @@ import {
|
||||
settingsOf,
|
||||
} from './presets.ts';
|
||||
import type { GameType, PresetName } from './presets.ts';
|
||||
import { settingsForm } from './settings-form.ts';
|
||||
import { rulesListHtml, settingsForm } from './settings-form.ts';
|
||||
import type { SettingsForm } from './settings-form.ts';
|
||||
|
||||
const SAVE_KEY = 'station-master.save.v1';
|
||||
@@ -62,9 +62,14 @@ type Settings = {
|
||||
districtMode: 'auto' | 'open' | 'closed';
|
||||
soundOn: boolean;
|
||||
zoom: number;
|
||||
/**
|
||||
* Is the This Game card open? (TODO #28.) Folded by default: it answers "what did we set that
|
||||
* to?", which Jesse's own framing says is "not something they're likely to need all the time".
|
||||
*/
|
||||
gameCardOpen: boolean;
|
||||
};
|
||||
|
||||
const DEFAULT_SETTINGS: Settings = { districtMode: 'auto', soundOn: false, zoom: 1 };
|
||||
const DEFAULT_SETTINGS: Settings = { districtMode: 'auto', soundOn: false, zoom: 1, gameCardOpen: false };
|
||||
|
||||
function loadSettings(): Settings {
|
||||
try {
|
||||
@@ -80,6 +85,8 @@ function loadSettings(): Settings {
|
||||
typeof parsed.zoom === 'number' && (ZOOM_LEVELS as readonly number[]).includes(parsed.zoom)
|
||||
? parsed.zoom
|
||||
: DEFAULT_SETTINGS.zoom,
|
||||
gameCardOpen:
|
||||
typeof parsed.gameCardOpen === 'boolean' ? parsed.gameCardOpen : DEFAULT_SETTINGS.gameCardOpen,
|
||||
};
|
||||
} catch {
|
||||
// A full or disabled localStorage must not take the game down with it — same guard as the save.
|
||||
@@ -141,6 +148,7 @@ let pendingAt: string | null = null;
|
||||
* save, for exactly that reason.
|
||||
*/
|
||||
let districtMode: 'auto' | 'open' | 'closed' = settings.districtMode;
|
||||
let gameCardOpen = settings.gameCardOpen;
|
||||
/**
|
||||
* Sound, OFF by default until a player asks for it once — then remembered via `settings`.
|
||||
*
|
||||
@@ -257,17 +265,88 @@ function renderTurnChart(f: Frame): void {
|
||||
* tooltip. Written down at all because a playtest note is worthless without it: "scored 4" means one
|
||||
* thing at 1 Revenue per transit and another at 5.
|
||||
*/
|
||||
function renderHouseRules(rules: HouseRules): void {
|
||||
const { passengerPerCoach: pax, freightPerLoad: frt, trainPerTransit: trn } = rules.revenue;
|
||||
function gameCardSummary(f: Frame): string {
|
||||
const { passengerPerCoach: pax, freightPerLoad: frt, trainPerTransit: trn } = f.houseRules.revenue;
|
||||
const short = { threeRandom: '3 cards', sixRandom: '6 cards', threeTrackThreeOther: '3+3 cards' };
|
||||
const el = $('houserules');
|
||||
el.textContent = `· ${short[rules.startingHand]} · ${pax}/${frt}/${trn}`;
|
||||
const handWords = STARTING_HAND_LABELS.find((o) => o.value === rules.startingHand)?.label ?? '';
|
||||
const config = configFromFrame(f);
|
||||
const type = gameTypeLabel(presetOf(config, f.players.length, f.days), f.mode);
|
||||
const floor = f.minCombinedRevenue === 0 ? 'no floor' : `floor ${f.minCombinedRevenue}`;
|
||||
return `${type} · ${f.days} Days · ${floor} · ${short[f.houseRules.startingHand]} · ${pax}/${frt}/${trn}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS GAME — every setting it was dealt under, in a card rather than along the top line (TODO #28).
|
||||
*
|
||||
* Jesse, 2026-08-23: "the game-specific information in the very top line should probably be a card
|
||||
* like Facilities, timetable or blocked. Off on the side, we can give complete information about all
|
||||
* the game options and not take up valuable real estate at the top of the screen." And on when it is
|
||||
* read: "To go, 'Oh wait, what did we set that to?' They should be able to look that up, but it does
|
||||
* not need to be at the top every moment."
|
||||
*
|
||||
* NOTHING NEW TRAVELS FOR THIS. `configFromFrame` already turns the Frame's copy of the config back
|
||||
* into a `GameConfig`, and `rulesListHtml` is the renderer the lobby's join preview and seating
|
||||
* screen already draw — so what a player agreed to before the deal and what they can read mid-game
|
||||
* come from ONE implementation and cannot drift. The identity block above it is the half
|
||||
* `rulesListHtml` has no notion of: which seed or seat this is, and what the game is called.
|
||||
*
|
||||
* THE SEED IS SOLITAIRE-ONLY, and that is a redaction rule rather than a layout one: it is never
|
||||
* sent to a remote client at all, because it would leak every future shuffle and roll
|
||||
* (`multiplayer.md` §7). `RemoteSession` has no `.seed()` to call. A seated player gets their seat
|
||||
* instead, which is the thing they actually need to know.
|
||||
*/
|
||||
function renderGameCard(f: Frame): void {
|
||||
const sec = $('gamecard');
|
||||
sec.classList.toggle('folded', !gameCardOpen);
|
||||
$('gamecardsummary').textContent = gameCardSummary(f);
|
||||
|
||||
const btn = $('gamecardtoggle');
|
||||
btn.textContent = gameCardOpen ? 'hide' : 'show';
|
||||
btn.onclick = () => {
|
||||
gameCardOpen = !gameCardOpen;
|
||||
saveSettings({ gameCardOpen });
|
||||
render();
|
||||
};
|
||||
if (!gameCardOpen) {
|
||||
// Folded: the body is display:none anyway, and rebuilding it every frame is work nobody sees.
|
||||
$('gamecardbody').innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const config = configFromFrame(f);
|
||||
const players = f.players.length;
|
||||
const type = presetOf(config, players, f.days);
|
||||
const who = isLocal(session)
|
||||
? `<dt>Seed</dt><dd>${esc(String(session.seed()))}</dd>`
|
||||
: `<dt>Seat</dt><dd>${esc(String(seatLabel(session.seat())))}</dd>`;
|
||||
const code = gameCode === '' ? '' : `<dt>Game code</dt><dd>${esc(gameCode)}</dd>`;
|
||||
$('gamecardbody').innerHTML =
|
||||
`<dl>${who}${code}<dt>Type</dt><dd>${esc(gameTypeLabel(type, f.mode))}</dd></dl>` +
|
||||
rulesListHtml(config, players, f.days);
|
||||
}
|
||||
|
||||
/**
|
||||
* THE COLLISION COUNTS, WHICH ARE A LIVE SCORE (TODO #28, Jesse's call 2026-08-30).
|
||||
*
|
||||
* They stay on the top line while the limits themselves move into the card, because the two are
|
||||
* different kinds of thing: `maxCollisionsPerDay` is a setting you agreed to once, and "2 of 3
|
||||
* today" is a number that changes how you play the next Stage. The Frame has carried both counts
|
||||
* since v0.7.0 and nothing drew them, so the one victory condition that ends a game EARLY ran
|
||||
* invisibly — v0.7.9 made it reachable in solitaire too, which is what made this worth having.
|
||||
*
|
||||
* `0` means the limit is off (the engine's convention), and a half that is off is left out rather
|
||||
* than shown as "1 of 0". With both off the chip is empty, and an empty span collapses.
|
||||
*/
|
||||
function renderCollisions(f: Frame): void {
|
||||
const parts: string[] = [];
|
||||
if (f.maxCollisionsPerDay > 0) parts.push(`${f.collisionsToday} of ${f.maxCollisionsPerDay} today`);
|
||||
if (f.maxCollisionsTotal > 0) parts.push(`${f.collisionsTotal} of ${f.maxCollisionsTotal} total`);
|
||||
const el = $('collisions');
|
||||
el.textContent = parts.length === 0 ? '' : `collisions ${parts.join(' · ')}`;
|
||||
el.title =
|
||||
`Opening hand: ${handWords.toLowerCase()}.\n` +
|
||||
`Passenger revenue per coach: ${pax} (paid on boarding and again on detraining).\n` +
|
||||
`Freight revenue per load: ${frt} (paid on loading and again on unloading).\n` +
|
||||
`Train revenue per transit: ${trn} (paid to every player when a train leaves the Division).`;
|
||||
parts.length === 0
|
||||
? ''
|
||||
: 'Reaching either limit ends the game immediately and results in a loss. Both limits are in ' +
|
||||
'the This Game card; these are the running counts.';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -506,7 +585,7 @@ const lobbyHandlers = {
|
||||
const record = readStore().games[gameId];
|
||||
if (!record) return;
|
||||
if (record.stage === 'game' && record.seat !== undefined) {
|
||||
beginRemote({ ...record, seat: record.seat });
|
||||
beginRemote({ ...record, seat: record.seat }, true);
|
||||
return;
|
||||
}
|
||||
// Still seated in a lobby that had not started: the stream puts us back on the seating screen,
|
||||
@@ -533,6 +612,8 @@ const HANDOFF_STALL_MS = 8000;
|
||||
let handoffOpenedAt = 0;
|
||||
let handoffStall: number | null = null;
|
||||
let firstFrameSeen = false;
|
||||
/** Set when this page entered a game it was already seated in, so the first frame says so. */
|
||||
let rejoiningRemote = false;
|
||||
|
||||
function setText(id: string, text: string): void {
|
||||
const el = document.getElementById(id);
|
||||
@@ -612,7 +693,7 @@ function noteDayEnd(f: Frame): void {
|
||||
* nothing saying this was the game just set up. `#phasenote` cannot help: it announces a CHANGE of
|
||||
* phase, and there is no previous phase to have changed from.
|
||||
*/
|
||||
function noteFirstFrame(f: Frame): void {
|
||||
function noteFirstFrame(f: Frame, rejoining = false): void {
|
||||
if (firstFrameSeen || isLocal(session)) return;
|
||||
firstFrameSeen = true;
|
||||
const held = Date.now() - handoffOpenedAt;
|
||||
@@ -621,14 +702,34 @@ function noteFirstFrame(f: Frame): void {
|
||||
window.setTimeout(
|
||||
() => {
|
||||
closeHandoff();
|
||||
/**
|
||||
* "BEGUN" IS ONLY TRUE ONCE. `firstFrameSeen` is per page-load, so re-entering a game this
|
||||
* browser already holds a seat in — a reload mid-game, or picking it out of the lobby's list
|
||||
* — announced that the game had begun, to a player who had been playing it for an hour.
|
||||
* Reported for the solitaire side by Jesse, 2026-08-30; the same line was wrong here.
|
||||
*/
|
||||
flashAnnounce(
|
||||
`The game has begun — ${type} · ${f.players.length} players · Day ${f.day}, Stage ${f.stage}`,
|
||||
`The game has ${rejoining ? 'resumed' : 'begun'} — ${type} · ${f.players.length} players · ` +
|
||||
`Day ${f.day}, Stage ${f.stage}`,
|
||||
);
|
||||
},
|
||||
Math.max(0, HANDOFF_BEAT_MS - held),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* COMING BACK TO A GAME, said out loud — the solitaire counterpart to `noteFirstFrame`.
|
||||
*
|
||||
* A restored game draws exactly like a dealt one: mid-Day, mid-phase, with a log already several
|
||||
* turns deep. Nothing distinguished "this is the game you left" from "this is a game that has just
|
||||
* started", and the multiplayer path had the opposite problem — it announced that the game had
|
||||
* BEGUN to a player rejoining one (Jesse, 2026-08-30: "do not post a message that says 'The game
|
||||
* has begun.' … it needs to say 'The game has resumed.'").
|
||||
*/
|
||||
function announceResumed(f: Frame): void {
|
||||
flashAnnounce(`The game has resumed — Day ${f.day}, Stage ${f.stage}`);
|
||||
}
|
||||
|
||||
/** Toggles the three mutually-exclusive top-level screens `play.html` defines — `#lobby` (Phase 4),
|
||||
* `#gameui` (the board, whether local or remote), and `#solitairesetup` (asked before the first
|
||||
* solitaire deal, the same way `#lobby` is asked before the first multiplayer one — Jesse,
|
||||
@@ -646,7 +747,7 @@ function showScreen(which: 'lobby' | 'gameui' | 'solitairesetup'): void {
|
||||
* earlier visit. Either way the token is what makes reconnection work (`lobby-and-sessions.md` §1),
|
||||
* so it is always written back here before anything else happens.
|
||||
*/
|
||||
function beginRemote(ready: LobbyReady): void {
|
||||
function beginRemote(ready: LobbyReady, rejoining = false): void {
|
||||
saveRemote({ token: ready.token, gameId: ready.gameId, gameCode: ready.gameCode, seat: ready.seat, stage: 'game' });
|
||||
gameCode = ready.gameCode;
|
||||
showScreen('gameui');
|
||||
@@ -656,6 +757,7 @@ function beginRemote(ready: LobbyReady): void {
|
||||
// banner (`#presence`), and it holds a beat so the game visibly begins.
|
||||
openHandoff();
|
||||
session = createRemoteSession(ready.token, ready.seat, abandonRemote);
|
||||
rejoiningRemote = rejoining;
|
||||
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
|
||||
@@ -742,7 +844,7 @@ function start(): void {
|
||||
// session reports a dead game through `abandonRemote`, which lands in the lobby.
|
||||
const remembered = wantsSolitaire ? null : loadRemote();
|
||||
if (remembered && remembered.stage === 'game' && remembered.seat !== undefined) {
|
||||
beginRemote({ ...remembered, seat: remembered.seat });
|
||||
beginRemote({ ...remembered, seat: remembered.seat }, true);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
@@ -773,16 +875,24 @@ function start(): void {
|
||||
* (Jesse, 2026-08-29 — "let the user choose their options like the start of a multiplayer game";
|
||||
* "asking first is the only path").
|
||||
*
|
||||
* A saved game or an explicit `seed=` both mean this visit is not "no plan yet" — a saved game is
|
||||
* a game to resume, and a seed names a specific deal someone already chose to share or bookmark,
|
||||
* the same reasoning `?lobby` already uses to skip past the doors on an invite link. `hand` is the
|
||||
* one field every `commitNewGame` write always sets (`rulesToUrl`), so its presence means this
|
||||
* navigation IS the setup screen's own Deal button, landing back here to actually deal — checking
|
||||
* it is what stops the screen asking itself the question a second time.
|
||||
* Three things answer the question and so skip the screen, in this order of precedence:
|
||||
* `hand` (every `commitNewGame` write sets it, so this navigation IS the Deal button landing back
|
||||
* here to deal), `seed` (a specific deal someone chose to share or bookmark), and — only when the
|
||||
* player did not explicitly ask to set one up — an existing save, which is a game to resume.
|
||||
*
|
||||
* THE DOOR OUTRANKS A SAVED GAME, and getting that wrong is what made this feature unreachable
|
||||
* for three releases. v0.7.5 skipped the screen whenever `load()` found ANYTHING, reasoned as "a
|
||||
* saved game is a game to resume" — but a browser that has ever played solitaire always has one,
|
||||
* so the door could never reach the screen again. Reported three times (Jesse, 2026-08-29 twice
|
||||
* and 2026-08-30); a private window appeared to absolve it only because it had never played and
|
||||
* so had no save. Clicking "Play solitaire" is a request to set a game up, not to resume one — a
|
||||
* BARE reload is the resume case, and still is. `#ss-resume` is what keeps the save reachable, so
|
||||
* this costs nobody the game they were playing.
|
||||
*/
|
||||
if (!saved && requested === null && !params.has('hand')) {
|
||||
const askedToSetUp = params.get('solitaire') !== null;
|
||||
if (requested === null && !params.has('hand') && (askedToSetUp || !saved)) {
|
||||
showScreen('solitairesetup');
|
||||
runSolitaireSetup(params);
|
||||
runSolitaireSetup(params, saved !== null);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -791,13 +901,17 @@ function start(): void {
|
||||
const seed = requested !== null ? Number(requested) || 1 : Math.floor(Math.random() * 1e9);
|
||||
const local = createLocalSession(seed, solitaireDefaults(gameOptionsFromUrl(params)));
|
||||
session = local;
|
||||
if (saved && requested === null) local.restore(saved);
|
||||
const restored = Boolean(saved) && requested === null;
|
||||
if (saved && restored) local.restore(saved);
|
||||
|
||||
applyCapabilities();
|
||||
// Every render goes through the session, so the page redraws whenever the game says it changed —
|
||||
// which is what a remote session will use to push. Locally it fires on each accepted intent.
|
||||
session.subscribe(render);
|
||||
render();
|
||||
// Coming back to a game is not the same event as being dealt one, and the board looks identical
|
||||
// either way — mid-Day, mid-phase, with a log already deep (Jesse, 2026-08-30).
|
||||
if (restored) announceResumed(session.view());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -895,21 +1009,32 @@ function renderPresence(f: Frame): void {
|
||||
*/
|
||||
function renderGameIdentity(f: Frame): void {
|
||||
const codeEl = document.getElementById('gamecode');
|
||||
if (codeEl) codeEl.textContent = gameCode === '' ? '' : `game ${gameCode}`;
|
||||
|
||||
const el = document.getElementById('gametype');
|
||||
if (!el) return;
|
||||
if (!codeEl) return;
|
||||
codeEl.textContent = gameCode === '' ? '' : `game ${gameCode}`;
|
||||
/**
|
||||
* THE CODE KEEPS ITS TOOLTIP, AND THE TOOLTIP KEEPS THE RULES. The game type and the house rules
|
||||
* moved into the This Game card (TODO #28), but the code is the thing a player reads out to say
|
||||
* WHICH game they are in — so it is worth being able to hover it and get the whole answer without
|
||||
* opening the card.
|
||||
*
|
||||
* IN SOLITAIRE THERE IS NO CODE, so the span is empty and this tooltip is unreachable. That is not
|
||||
* a hole: the card's summary line is always on screen whether the card is folded or not, and it
|
||||
* opens with the type — "Solitaire · 5 Days · floor 15 · 3 cards · 4/2/1". A lone player has no
|
||||
* game to name to anybody, and the one thing this tooltip adds over that line is the blurb.
|
||||
*/
|
||||
const config = configFromFrame(f);
|
||||
const players = f.players.length;
|
||||
const type = presetOf(config, players, f.days);
|
||||
const near = closestPreset(config, players, f.days);
|
||||
el.textContent = gameTypeLabel(type, f.mode);
|
||||
el.title =
|
||||
const blurb =
|
||||
type === 'custom'
|
||||
? `A custom game, scored as ${preset(near.name).scoring === 'coop' ? 'Co-op' : 'Competitive'}. ` +
|
||||
`${near.differing.length} ${near.differing.length === 1 ? 'setting differs' : 'settings differ'} ` +
|
||||
`from ${preset(near.name).label}.\n\n${rulesSummary(f)}`
|
||||
: `${preset(type).blurb}\n\n${rulesSummary(f)}`;
|
||||
`from ${preset(near.name).label}.`
|
||||
: preset(type).blurb;
|
||||
codeEl.title =
|
||||
`${gameTypeLabel(type, f.mode)}. ${blurb}\n\n${rulesSummary(f)}\n\n` +
|
||||
'The full settings are in the This Game card, at the foot of the right-hand column.';
|
||||
}
|
||||
|
||||
/** The victory conditions in force, spelled out for the header's tooltip. */
|
||||
@@ -926,7 +1051,7 @@ function rulesSummary(f: Frame): string {
|
||||
function render(): void {
|
||||
const f = session.view();
|
||||
const menu = session.menu();
|
||||
noteFirstFrame(f);
|
||||
noteFirstFrame(f, rejoiningRemote);
|
||||
|
||||
// Which squares the selected card or track piece may go on. Highlighting them is what turns the
|
||||
// coordinate list into a board: you pick the thing, then click where it goes.
|
||||
@@ -969,11 +1094,9 @@ function render(): void {
|
||||
? `${f.revenue} · Day ${f.day} — ${f.extraDays} beyond the timetable`
|
||||
: `${f.revenue} of ${f.objective.target} · ${left}`;
|
||||
obj.className = 'pace';
|
||||
// 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 ${seatLabel(session.seat())}`;
|
||||
renderCollisions(f);
|
||||
renderGameIdentity(f);
|
||||
renderHouseRules(f.houseRules);
|
||||
renderGameCard(f);
|
||||
|
||||
// -- division
|
||||
$('division').innerHTML = divisionSvg(f.division, {
|
||||
@@ -1253,15 +1376,40 @@ function render(): void {
|
||||
* WHERE THE GAME BEGAN. In a multiplayer game the bots move the instant the host presses Start, so
|
||||
* by the time the board paints the log already has several turns in it and nothing says which of
|
||||
* them are yours to have missed. Only drawn while the whole log is on screen: past sixty lines the
|
||||
* top of the panel is no longer the start of the game, and a marker claiming otherwise would lie.
|
||||
* end of the panel is no longer the start of the game, and a marker claiming otherwise would lie.
|
||||
*/
|
||||
const startMarker =
|
||||
!isLocal(session) && allLines.length === shownLines.length
|
||||
? '<div class="line t-phase">— the game began —</div>'
|
||||
: '';
|
||||
/**
|
||||
* NEWEST FIRST (TODO #23). Jesse, 2026-08-30: "it should be reversed so the top line is the most
|
||||
* recent and the further down you go, the older the entry."
|
||||
*
|
||||
* The panel used to run oldest-first and scroll itself to the bottom, so the thing that had just
|
||||
* happened was the one line you had to go and find. A glance at the top is now always the most
|
||||
* recent thing, and `scrollTop = 0` keeps it there as lines arrive rather than chasing the end.
|
||||
*
|
||||
* THE PHASE HEADINGS NOW TRAIL THEIR LINES, and that is accepted rather than overlooked. A
|
||||
* `t-phase` line reads forwards — it introduces what follows it — so reversing puts each one
|
||||
* BELOW the events it announced. Jesse ruled on it directly: "stage changes will be beneath
|
||||
* (prior to / older than) the following events. That is OK." Reading down the panel is reading
|
||||
* backwards in time, and a heading sitting under its own lines is what backwards looks like.
|
||||
* Grouping by phase and reversing the groups was the alternative, and it was declined as more
|
||||
* machinery than the complaint needs.
|
||||
*
|
||||
* The start marker moves with the same logic: it is the OLDEST thing on screen, so it goes last.
|
||||
*
|
||||
* `replays.ts` keeps its own oldest-first log deliberately — it is paired with a frame stepper,
|
||||
* where "what just happened" is the step you have this moment clicked, so newest-first would
|
||||
* fight the stepping rather than help it.
|
||||
*/
|
||||
log.innerHTML =
|
||||
startMarker + shownLines.map((l) => `<div class="line t-${l.tone}">${esc(l.text)}</div>`).join('');
|
||||
log.scrollTop = log.scrollHeight;
|
||||
shownLines
|
||||
.map((l) => `<div class="line t-${l.tone}">${esc(l.text)}</div>`)
|
||||
.reverse()
|
||||
.join('') + startMarker;
|
||||
log.scrollTop = 0;
|
||||
|
||||
/**
|
||||
* SAY WHEN THE PHASE TURNS OVER.
|
||||
@@ -1373,21 +1521,35 @@ function renderDistrict(f: Frame): void {
|
||||
`${f.cells.length} cards · ${f.facilities.length} facilities · ${cars} cars standing` +
|
||||
(crew > 0 ? ` · ${crew} crew on the board` : '');
|
||||
|
||||
// Say what pressing it DOES, not what the panel is currently doing. "auto · folded" reads as a
|
||||
// status line and was missed entirely; "always show" is an instruction.
|
||||
const btn = $('districttoggle');
|
||||
btn.textContent =
|
||||
districtMode === 'auto'
|
||||
? (open ? 'auto-hide: on — click to keep open' : 'auto-hide: on — click to show')
|
||||
: districtMode === 'open'
|
||||
? 'always showing — click for auto-hide'
|
||||
: 'always hidden — click for auto-hide';
|
||||
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();
|
||||
};
|
||||
/**
|
||||
* THREE CONTROLS, ONE PER MODE (TODO #16) — not one control that cycles.
|
||||
*
|
||||
* The cycle was `auto -> (open ? 'closed' : 'open') -> auto`, where `open` is what auto is doing
|
||||
* AT THAT MOMENT — `FOCUS_PHASES.has(f.phaseKey)`. So which pin a press reached depended on the
|
||||
* phase: during Local Operations or Cargo it offered "always hidden", and in every other phase
|
||||
* "always showing". Getting from one pin to the other meant clicking back to auto, waiting for
|
||||
* the phase to turn over, and clicking again — which is why it never read as a setting.
|
||||
*
|
||||
* The labels still say what pressing DOES rather than what the panel is doing. That was a
|
||||
* deliberate earlier fix ("auto · folded" read as a status line and was missed entirely) and it
|
||||
* survives the change; what the CYCLE could not do was be honest about the state it was in, which
|
||||
* is now carried by `aria-pressed` and the lit button instead of by the label.
|
||||
*/
|
||||
/**
|
||||
* Addressed by id, one lookup each, rather than by querying the container's children. Everything
|
||||
* else on this page is reached with `$('...')`, and it is what makes the control testable at all:
|
||||
* the page never writes this markup, so a child query finds nothing in a stubbed DOM and the
|
||||
* whole control would ship green and unexercised.
|
||||
*/
|
||||
for (const mode of ['auto', 'open', 'closed'] as const) {
|
||||
const b = $(`dm-${mode}`);
|
||||
b.setAttribute('aria-pressed', String(mode === districtMode));
|
||||
b.onclick = () => {
|
||||
districtMode = mode;
|
||||
saveSettings({ districtMode });
|
||||
render();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1546,6 +1708,33 @@ function showResults(f: Frame): void {
|
||||
const body = document.getElementById('resultsbody');
|
||||
if (!dlg || !body) return;
|
||||
body.innerHTML = resultsHtml(f);
|
||||
|
||||
/**
|
||||
* ASK THE EXTENSION QUESTION ON THE THING THAT IS ACTUALLY IN FRONT OF THE PLAYER.
|
||||
*
|
||||
* This dialog opens itself at every ending and it is MODAL, so `renderEnding`'s own "play one more
|
||||
* Day" buttons — written into `#actions` — are behind it. The player read a results screen offering
|
||||
* nothing but Close and concluded the game was over, which is exactly what it looked like (Jesse,
|
||||
* 2026-08-30). Gitea#11 was verified over the HTTP API, where there is no dialog to be behind.
|
||||
*
|
||||
* The buttons in `#actions` stay, and are still correct: they are what remains after this is
|
||||
* closed, and what a player who reopened the results with "see the full results" comes back to.
|
||||
* Voting from either place submits the same intent.
|
||||
*/
|
||||
const yes = document.getElementById('rs-extend-yes') as HTMLButtonElement | null;
|
||||
const no = document.getElementById('rs-extend-no') as HTMLButtonElement | null;
|
||||
const asking = f.status === 'awaitingExtension' && f.extensionVotes[f.viewer] === null;
|
||||
if (yes && no) {
|
||||
yes.hidden = !asking;
|
||||
no.hidden = !asking;
|
||||
if (asking) {
|
||||
// `method="dialog"` closes it on click; the vote rides along. Assigned every time rather than
|
||||
// once, because `f` is a fresh Frame on each ending.
|
||||
yes.onclick = () => void session.submit({ type: 'game.extend', player: f.viewer, agree: true });
|
||||
no.onclick = () => void session.submit({ type: 'game.extend', player: f.viewer, agree: false });
|
||||
}
|
||||
}
|
||||
|
||||
// A redraw can arrive while it is open — `showModal` throws on an already-open dialog rather
|
||||
// than doing nothing (the same trap `noteDayEnd` documents).
|
||||
if (!dlg.open) dlg.showModal();
|
||||
@@ -1768,12 +1957,23 @@ function renderActions(
|
||||
}
|
||||
html += `</div>`;
|
||||
}
|
||||
if (
|
||||
f.phaseKey === 'localOps' &&
|
||||
f.option === 'draw' &&
|
||||
!menu.options.some((i) => i.type === 'draw.end')
|
||||
) {
|
||||
// The hand being counted is the ACTOR's — they are the one who cannot end the turn.
|
||||
/**
|
||||
* WHY "END LOCAL OPERATIONS" IS NOT THERE (#45).
|
||||
*
|
||||
* This asked the question backwards: "the engine is offering no `draw.end`, so it must be the
|
||||
* hand limit." That was true only because `check('draw.end')` happens to refuse for exactly three
|
||||
* reasons and the two guards above rule out the other two — a fourth reason would have made this
|
||||
* block explain a refusal by describing something else entirely, which is #90 verbatim.
|
||||
*
|
||||
* `f.overHandLimit` IS the fact, and the Frame has carried it all along for precisely this: "the
|
||||
* same test the engine applies to `draw.end`, asked here so the page can disable the button with a
|
||||
* reason instead of hiding a move that has simply become illegal" (`web/game.ts`). It was computed,
|
||||
* serialised and sent to nobody. Behaviour is unchanged today; what changes is that the screen now
|
||||
* states the reason it is giving rather than inferring it from an absence.
|
||||
*/
|
||||
if (f.phaseKey === 'localOps' && f.option === 'draw' && f.overHandLimit) {
|
||||
// The hand being counted is the VIEWER's, like `f.option` and `f.handCount` beside it — and the
|
||||
// viewer is the actor whenever this menu is on screen at all.
|
||||
const hand = f.handCount;
|
||||
/**
|
||||
* WHEN NOTHING IN HAND MAY BE DISCARDED, SAY SO AND SAY WHAT TO DO INSTEAD.
|
||||
@@ -1984,12 +2184,16 @@ function wireGameTypeBlock(prefix: string, root: ParentNode): WiredGameType {
|
||||
if (differing.length > 0) type = 'custom';
|
||||
else if (type === 'custom') type = base;
|
||||
for (const r of typeRadios()) r.checked = r.value === type;
|
||||
const note = field<HTMLElement>('type-note');
|
||||
note.textContent =
|
||||
type === 'custom'
|
||||
? `${gameTypeLabel('custom', preset(base).scoring)} · ${differing.length} ` +
|
||||
`${differing.length === 1 ? 'setting differs' : 'settings differ'} from ${preset(base).label}.`
|
||||
: preset(type as PresetName).blurb;
|
||||
/**
|
||||
* NO SENTENCE UNDER THE RADIOS. It restated the type just chosen — the row is already labelled
|
||||
* and already carries its own one-line description — so it was the choice read back to the
|
||||
* person who had just made it (Jesse, 2026-08-30: "It's obvious from what they selected above
|
||||
* what they're playing. There's no need to repeat it below.").
|
||||
*
|
||||
* The Custom case said something the radios do NOT — how many settings differ, and from which
|
||||
* type — and that is not lost: `form.mark` puts a hint on each row that actually differs, which
|
||||
* is where a reader can act on it rather than a count they would then have to go and find.
|
||||
*/
|
||||
}
|
||||
|
||||
function selectPreset(name: PresetName): void {
|
||||
@@ -2008,19 +2212,21 @@ function wireGameTypeBlock(prefix: string, root: ParentNode): WiredGameType {
|
||||
}
|
||||
|
||||
for (const r of typeRadios()) {
|
||||
// Nothing here can deal a multiplayer game: a `LocalSession` runs the engine in this browser and
|
||||
// a table needs a server. The lobby is the door, and the row says so rather than just refusing
|
||||
// the click (Jesse, 2026-08-23 — a disabled radio that looks enabled reads as a broken one).
|
||||
/**
|
||||
* Nothing here can deal a multiplayer game: a `LocalSession` runs the engine in this browser and
|
||||
* a table needs a server. Dimmed rather than hidden, so what this screen offers and what the
|
||||
* lobby offers read as one list (Jesse, 2026-08-23 — a disabled radio that looks enabled reads
|
||||
* as a broken one).
|
||||
*
|
||||
* NO REASON PRINTED BESIDE THEM since 2026-08-30. Each row used to gain "— use the Multiplayer
|
||||
* button; a table needs a server", which is three unreachable types each explaining the same
|
||||
* thing on a screen whose heading already says "Game type (solitaire)". Jesse: "grayed out with
|
||||
* no additional explanation. The explanation above… is sufficient." The lobby dims Solitaire the
|
||||
* same way and says nothing either, which is what lets one list serve both screens.
|
||||
*/
|
||||
if (r.value !== 'solitaire' && r.value !== 'custom') {
|
||||
r.disabled = true;
|
||||
const row = r.closest('label');
|
||||
if (row && !row.querySelector('.lb-why')) {
|
||||
row.classList.add('disabled');
|
||||
const note = document.createElement('span');
|
||||
note.className = 'lb-why';
|
||||
note.textContent = ' — use the Multiplayer button; a table needs a server';
|
||||
row.querySelector('span')?.appendChild(note);
|
||||
}
|
||||
r.closest('label')?.classList.add('disabled');
|
||||
}
|
||||
r.onchange = () => {
|
||||
if (!r.checked) return;
|
||||
@@ -2102,65 +2308,26 @@ function commitNewGame(wired: WiredGameType, seedFieldValue: string): void {
|
||||
else location.search = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* THE IN-GAME "NEW GAME" BUTTON GOES TO THE SETUP SCREEN (Jesse, 2026-08-30 — "it should not go to
|
||||
* a separate screen. We should reuse the Solitaire New Game Screen").
|
||||
*
|
||||
* `#newgamedlg` used to be a third copy of the same questions and the one that drifted: it carried
|
||||
* multiplayer wording on a screen only a solitaire player ever sees. It is deleted; this navigates
|
||||
* to the screen that already asks these questions properly.
|
||||
*
|
||||
* Nothing is lost on the way: `render()` calls `save()` every frame, so the game in progress is
|
||||
* always on disk, and the setup screen offers "Continue saved game" to come back to it.
|
||||
*/
|
||||
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;
|
||||
|
||||
/**
|
||||
* THE SAME FIVE GAME TYPES THE LOBBY OFFERS, and the same shared rules block under them.
|
||||
*
|
||||
* The dialog used to carry its own copy of the questions and its own idea of the defaults, which
|
||||
* is how it ended up with "where an Extra may start" that the lobby did not have and none of the
|
||||
* three optional rules that it did. Every screen now reads `presets.ts` and drives its block
|
||||
* through `settings-form.ts`; only Solitaire can actually be DEALT here, so the three multiplayer
|
||||
* types are shown disabled rather than hidden — what this screen offers and what the lobby offers
|
||||
* should read as one list, not two.
|
||||
*/
|
||||
const ng = wireGameTypeBlock('ng-', dlg);
|
||||
|
||||
/**
|
||||
* 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 settings each time is how a
|
||||
* comparison silently stops comparing. Which TYPE that is comes out of the comparison — a game
|
||||
* dealt at the Solitaire defaults reopens on Solitaire, and one that was tuned reopens on Custom
|
||||
* with every changed field marked.
|
||||
*/
|
||||
if (newBtn) {
|
||||
newBtn.onclick = () => {
|
||||
// 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 ${local.seed()}, Day ${day}) and deal a new one?`)) return;
|
||||
|
||||
field<HTMLInputElement>('ng-seed').value = '';
|
||||
field<HTMLInputElement>('ng-days').value = String(f.days);
|
||||
ng.setBase('solitaire', 'solitaire');
|
||||
// The rules actually in play, then the comparison decides what to call them.
|
||||
ng.form.write(settingsOf(configFromFrame(f)), presetSettings('solitaire', 1, f.days));
|
||||
ng.refresh();
|
||||
dlg.showModal();
|
||||
showScreen('solitairesetup');
|
||||
// IN PLACE, not a navigation: the live session stays in memory, so the fields can open on the
|
||||
// rules actually being played and "Continue saved game" is just showing the board
|
||||
// again rather than a reload and a replay.
|
||||
runSolitaireSetup(new URLSearchParams(), true, session.view());
|
||||
};
|
||||
|
||||
/**
|
||||
* One handler for every way the dialog can close — the Deal button, the Cancel button, and Esc,
|
||||
* which `<dialog>` answers with an empty `returnValue` and no submit event at all.
|
||||
*/
|
||||
dlg.addEventListener('close', () => {
|
||||
if (dlg.returnValue !== 'deal') return;
|
||||
commitNewGame(ng, field<HTMLInputElement>('ng-seed').value);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2173,7 +2340,7 @@ if (newBtn && dlg) {
|
||||
* Solitaire defaults, since there is no live game to compare against yet, and reuses the identical
|
||||
* `wireGameTypeBlock`/`commitNewGame` pair the in-game dialog uses — the two are one design, not two.
|
||||
*/
|
||||
function runSolitaireSetup(params: URLSearchParams): void {
|
||||
function runSolitaireSetup(params: URLSearchParams, hasSave = false, live: Frame | null = null): void {
|
||||
const screen = document.getElementById('solitairesetup');
|
||||
const dealBtn = document.getElementById('ss-deal');
|
||||
if (!screen || !dealBtn) return;
|
||||
@@ -2185,7 +2352,49 @@ function runSolitaireSetup(params: URLSearchParams): void {
|
||||
const seedField = document.getElementById('ss-seed') as HTMLInputElement | null;
|
||||
if (seedField) seedField.value = params.get('seed') ?? '';
|
||||
|
||||
ss.selectPreset('solitaire');
|
||||
/**
|
||||
* WHAT THE FIELDS OPEN ON, and it is not the same question in both directions.
|
||||
*
|
||||
* Reached mid-game from "New game", this opens on the rules CURRENTLY IN PLAY — that is what the
|
||||
* deleted dialog was good for, and losing it would make "change one dial and redeal to compare"
|
||||
* impossible. Reached from the splash, there is no game to read, so it opens on the plain
|
||||
* Solitaire defaults.
|
||||
*/
|
||||
if (live) {
|
||||
const daysField = document.getElementById('ss-days') as HTMLInputElement | null;
|
||||
if (daysField) daysField.value = String(live.days);
|
||||
ss.setBase('solitaire', 'solitaire');
|
||||
ss.form.write(settingsOf(configFromFrame(live)), presetSettings('solitaire', 1, live.days));
|
||||
ss.refresh();
|
||||
} else {
|
||||
ss.selectPreset('solitaire');
|
||||
}
|
||||
|
||||
/**
|
||||
* THE WAY BACK TO A GAME IN PROGRESS, and the reason the door is allowed to outrank a save at all.
|
||||
* Dealing from here calls `clearSave()`, so a player who reached this screen from the splash — by
|
||||
* clicking "Play solitaire", which nobody reads as "throw away what I was playing" — needs their
|
||||
* game one button away and needs to be told what Deal costs.
|
||||
*
|
||||
* Mid-game the game is still in memory, so going back is just showing it again. From the splash
|
||||
* there is nothing loaded yet, so it is a navigation to the bare URL and `start()` restores the
|
||||
* save — one place that turns a URL into a game, either way.
|
||||
*/
|
||||
const resumeBtn = document.getElementById('ss-resume');
|
||||
const savedNote = document.getElementById('ss-saved-note');
|
||||
const canResume = hasSave || live !== null;
|
||||
if (resumeBtn) {
|
||||
resumeBtn.hidden = !canResume;
|
||||
resumeBtn.onclick = live
|
||||
? () => {
|
||||
showScreen('gameui');
|
||||
render();
|
||||
announceResumed(session.view());
|
||||
}
|
||||
: () => void (location.search = '');
|
||||
}
|
||||
if (savedNote) savedNote.hidden = !canResume;
|
||||
|
||||
dealBtn.onclick = () => commitNewGame(ss, seedField?.value ?? '');
|
||||
}
|
||||
|
||||
|
||||
+20
-1
@@ -254,8 +254,13 @@ function collisionsHtml(f: Frame): string {
|
||||
* game read the words `GAME OVER — revenueFloor`: an internal enum value, printed at the one moment
|
||||
* the game has the player's whole attention. Each reason gets a sentence that says what actually
|
||||
* happened, with this game's own numbers in it.
|
||||
*
|
||||
* EXPORTED for the developer replay recorder (`sim/replay.ts`), which was still printing
|
||||
* `loss — revenueFloor` into its own heading a release after this was written — the same defect the
|
||||
* issue was filed about, surviving in the one place nobody had looked (`TODO.md` #34). One
|
||||
* implementation, so the two cannot say the game ended for different reasons.
|
||||
*/
|
||||
function reasonSentence(f: Frame, o: NonNullable<Frame['outcome']>, day: number): string {
|
||||
export function reasonSentence(f: Frame, o: NonNullable<Frame['outcome']>, day: number): string {
|
||||
const combined = f.players.reduce((n, p) => n + p.revenue, 0);
|
||||
switch (o.reason) {
|
||||
case 'daysElapsed':
|
||||
@@ -347,7 +352,17 @@ function tallyHtml(t: Frame['tally']): string {
|
||||
};
|
||||
push('Loads made up', t.loadsCompleted);
|
||||
push('Loads broken', t.unloadsCompleted);
|
||||
/**
|
||||
* BOTH HALVES OF THE MEN | AT | WORK PIPELINE, not just the loading one.
|
||||
*
|
||||
* §9.1 makes loading and unloading the same shape — begun, then carried through — and the Tally
|
||||
* has counted both since it was written. The screen reported only the loading side, so a player
|
||||
* with three unloads part-finished at the final whistle was told nothing about them while the
|
||||
* equivalent loads were listed. Found 2026-08-30 auditing which Frame fields nothing reads:
|
||||
* `unloadsBegun` was one of four, and the only one whose absence was visible on screen.
|
||||
*/
|
||||
push('Loads still in the pipeline', t.loadsStarted - t.loadsCompleted);
|
||||
push('Unloads still in the pipeline', t.unloadsBegun - t.unloadsCompleted);
|
||||
push('Passengers boarded', t.passengersBoarded);
|
||||
push('Passengers detrained', t.passengersDetrained);
|
||||
push('Cars coupled', t.carsCoupled);
|
||||
@@ -381,6 +396,10 @@ function tallyHtml(t: Frame['tally']): string {
|
||||
}
|
||||
push('Cards drawn', t.cardsDrawn);
|
||||
push('Cards played', t.cardsPlayed);
|
||||
// Gitea#9 made throwing a Timetabled train away a legal and deliberate move, so a discard is a
|
||||
// CHOICE the player made rather than an accident of the hand limit — and the engine has counted
|
||||
// it all along while the screen listed only draws and plays beside it.
|
||||
push('Cards discarded', t.cardsDiscarded);
|
||||
|
||||
return `<h4 class="res-h">The railroad</h4>${factTable(rows)}`;
|
||||
}
|
||||
|
||||
+128
-214
@@ -76,6 +76,19 @@ dialog input:focus{outline:none;border-color:#4d6fa8}
|
||||
padding:5px 14px;cursor:pointer;font:inherit;font-size:13px}
|
||||
.ng-buttons button:hover{border-color:#4d6fa8}
|
||||
#ng-deal{background:#31527f;border-color:#4d6fa8}
|
||||
/* The save warning is the one thing on this screen that describes something IRREVERSIBLE, and it
|
||||
sat in `.ng-note` — the same dim 11px grey as the twenty explanatory notes above it, which is
|
||||
where the eye has already learned there is nothing to act on. Sized and coloured to be read
|
||||
(Jesse, 2026-08-30). Amber rather than red: losing a saved game is a real cost, not a danger, and
|
||||
red here would outrank the actual rules of the game sitting above it. */
|
||||
#ss-saved-note{font-size:15px;font-weight:500;line-height:1.55;color:#ffcf70;background:#332a15;
|
||||
border:1px solid #b8912c;border-left:5px solid #e0a83c;border-radius:5px;padding:12px 14px;
|
||||
margin:18px 0 0}
|
||||
#ss-saved-note b{color:#ffe3a6}
|
||||
/* Two live choices, so neither is the quiet one: `Create new game` keeps the primary blue it has when
|
||||
it is the only button, and `Continue` is given the same weight rather than reading as a cancel. */
|
||||
#ss-deal{background:#31527f;border-color:#4d6fa8}
|
||||
#ss-resume{background:#2f5340;border-color:#4f8a68}
|
||||
main{display:grid;grid-template-columns:minmax(0,1fr) 400px;gap:14px;padding:14px;align-items:start}
|
||||
@media(max-width:1100px){main{grid-template-columns:1fr}}
|
||||
section{background:var(--panel);border:1px solid var(--line);border-radius:7px;
|
||||
@@ -95,7 +108,6 @@ section{background:var(--panel);border:1px solid var(--line);border-radius:7px;
|
||||
lobby and nothing on it said so — a radio that silently refuses reads as a broken radio. */
|
||||
.ng-radio.disabled{opacity:.45;cursor:not-allowed}
|
||||
.ng-radio.disabled:hover{background:none}
|
||||
.lb-why{color:#e0b060;font-size:11px}
|
||||
#lobby h2,#solitairesetup h2{margin-top:0}
|
||||
#lobby h3,#solitairesetup h3{margin-bottom:2px}
|
||||
.lb-seat{display:flex;align-items:center;gap:8px;padding:5px 0;border-bottom:1px solid var(--line)}
|
||||
@@ -203,6 +215,17 @@ button.act{display:inline-block}
|
||||
button.ghost{background:#222831;border:1px solid #4a5361;color:#c6ccd6;font-size:11px;
|
||||
padding:2px 9px;margin-left:10px;text-transform:none;letter-spacing:0;vertical-align:middle}
|
||||
button.ghost:hover{border-color:#4d6fa8;color:var(--fg)}
|
||||
/* A SEGMENTED CONTROL, BECAUSE A CYCLE COULD NOT REACH EVERY STATE (TODO #16).
|
||||
One button that steps auto -> pinned -> auto can only ever offer the pin OPPOSITE to whatever
|
||||
auto is doing at that moment, which depends on the phase — so "always hidden" was unreachable
|
||||
from "always showing" without waiting for the right phase in between. Three controls, one per
|
||||
mode, and the current one is lit. The buttons still say what they DO rather than what the panel
|
||||
is doing, which was the earlier fix and is worth keeping. */
|
||||
.seg{display:inline-flex;margin-left:10px;vertical-align:middle;border-radius:4px;overflow:hidden;
|
||||
border:1px solid #4a5361}
|
||||
.seg button.ghost{margin:0;border:0;border-radius:0;border-left:1px solid #4a5361}
|
||||
.seg button.ghost:first-child{border-left:0}
|
||||
.seg button.ghost[aria-pressed="true"]{background:#2f3a4a;color:var(--fg);font-weight:600}
|
||||
#district.folded #grid{display:none}
|
||||
#district.folded .districtrule{display:none}
|
||||
/* Said once, quietly, beside the thing it governs — a rule a player needs on their first district
|
||||
@@ -212,6 +235,16 @@ button.ghost:hover{border-color:#4d6fa8;color:var(--fg)}
|
||||
.districtrule b{color:#cfd6e0}
|
||||
#district.folded #districtsummary{display:block;padding:2px 0 1px;font-size:12px}
|
||||
#districtsummary{display:none}
|
||||
/* The This Game card folds the same way the district does, and for the same reason: a panel that
|
||||
vanishes entirely reads as broken, so the summary line is what a folded card still says. */
|
||||
#gamecard.folded #gamecardbody{display:none}
|
||||
#gamecard #gamecardsummary{display:none}
|
||||
#gamecard.folded #gamecardsummary{display:block;padding:2px 0 1px;font-size:12px}
|
||||
#gamecardbody dl{display:grid;grid-template-columns:auto 1fr;gap:2px 10px;margin:4px 0 10px}
|
||||
#gamecardbody dt{color:#8b94a3;font-size:11px}
|
||||
#gamecardbody dd{margin:0;font-size:12px;color:#cfd6e0}
|
||||
#gamecardbody dd.changed{color:#f0b64a}
|
||||
#gamecardbody h4{margin:8px 0 0;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:#8b94a3}
|
||||
/* An action you cannot take yet keeps its place but drops its light — the amber means "press me",
|
||||
so a disabled button must not wear it. */
|
||||
#actions button.blocked,#actions button:disabled{background:#232830;border:1px dashed #4a5361;
|
||||
@@ -307,9 +340,10 @@ ul.blocked li{padding:2px 0}
|
||||
|
||||
<!-- THE LOBBY (Phase 4) — shown instead of the game UI whenever there is no game yet to play: no
|
||||
stored session token, or a token whose game hasn't started. `lobby.ts` owns everything in here;
|
||||
`main.ts` only decides whether THIS div or `#gameui` below is the one currently visible.
|
||||
`#newgamedlg` at the very end of the body is solitaire-only, and asks the same questions through
|
||||
the same shared module (`settings-form.ts`) — the two blocks are generated from one template. -->
|
||||
`main.ts` only decides whether THIS div, `#solitairesetup` or `#gameui` is the one visible.
|
||||
`#solitairesetup` asks the same questions of a solitaire player, through the same shared module
|
||||
(`settings-form.ts`) — the two blocks are generated from one template, and since 2026-08-30
|
||||
they are the ONLY two: the in-game dialog that was a third copy is gone. -->
|
||||
<div id="lobby" hidden>
|
||||
<header><b><a href="./index.html" class="home">Station Master</a></b> — <span class="dim">Multiplayer</span></header>
|
||||
|
||||
@@ -402,12 +436,13 @@ ul.blocked li{padding:2px 0}
|
||||
can be shared, compared or replayed. Leave it blank for a random one.</p>
|
||||
<!-- WITH THE TABLE SIZE IT IS ABOUT, not below the rules block — reported by Jesse, who found
|
||||
it separated from the control it explains by fifteen settings. -->
|
||||
<p class="ng-note">Every chair has to be taken before the game can start — by a person or by a
|
||||
bot. Pick the size of the table now; it cannot change once the game is created.</p>
|
||||
<p class="ng-note">Every chair must be filled before the game can start. For solitaire,
|
||||
there’s only one player. For multiplayer, that must be filled by a person or a
|
||||
bot. The number of players cannot be changed once the game is created.</p>
|
||||
</div>
|
||||
|
||||
<div class="lb-col">
|
||||
<h3>Game type</h3>
|
||||
<h3>Game type (multi-player)</h3>
|
||||
<div class="set-row" id="lb-type-row">
|
||||
<label class="ng-radio"><input type="radio" name="lb-type" value="solitaire">
|
||||
<span><b>Solitaire</b><br><span class="dim">One railroad, one player. The whole Division is yours to run.</span></span></label>
|
||||
@@ -421,7 +456,7 @@ ul.blocked li{padding:2px 0}
|
||||
<span><b>Custom</b><br><span class="dim">Whatever you set below. Selected for you the moment you change a rule; it is scored as the type you started from.</span></span></label>
|
||||
</div>
|
||||
|
||||
<p class="ng-note" id="lb-type-note"></p>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- FULL WIDTH WHEN IT OPENS. Reported by Jesse: opened inside the right-hand column it made a
|
||||
@@ -431,7 +466,7 @@ ul.blocked li{padding:2px 0}
|
||||
<summary>Game settings</summary>
|
||||
<p class="ng-note">Every rule the game type sets, and every one of them yours to change.
|
||||
Changing any of them selects <b>Custom</b>, which keeps the scoring of the type you
|
||||
started from; clicking a type again resets all of them back to it. They are fixed when the
|
||||
started from; changing the game type resets all of them back to it. They are fixed when the
|
||||
game is created and cannot be changed once it starts.</p>
|
||||
<div class="set-groups">
|
||||
|
||||
@@ -505,13 +540,13 @@ ul.blocked li{padding:2px 0}
|
||||
</div>
|
||||
<div class="set-row" id="lb-colday-row">
|
||||
<label class="ng-gate"><input type="checkbox" id="lb-colday-on" checked>
|
||||
<span>The game ends and everyone loses if collisions in one Day reach</span>
|
||||
<span>The game ends immediately and results in a loss if collisions in one Day reach</span>
|
||||
<input id="lb-colday" type="number" min="0" step="1" class="gate-num"></label>
|
||||
<span class="set-hint" id="lb-colday-hint"></span>
|
||||
</div>
|
||||
<div class="set-row" id="lb-coltotal-row">
|
||||
<label class="ng-gate"><input type="checkbox" id="lb-coltotal-on" checked>
|
||||
<span>The game ends and everyone loses after this many collisions in the whole game</span>
|
||||
<span>The game ends immediately and results in a loss after this many collisions in the whole game</span>
|
||||
<input id="lb-coltotal" type="number" min="0" step="1" class="gate-num"></label>
|
||||
<span class="set-hint" id="lb-coltotal-hint"></span>
|
||||
</div>
|
||||
@@ -522,7 +557,7 @@ ul.blocked li{padding:2px 0}
|
||||
|
||||
<div class="set-group">
|
||||
<h3>Optional rules</h3>
|
||||
<p class="ng-note">Off in every game type; each one changes how the game plays.</p>
|
||||
<p class="ng-note">Each one changes how the game plays.</p>
|
||||
<div class="set-row" id="lb-visibility-row">
|
||||
<label class="ng-num"><span>Reduced Visibility — five switching Moves instead of six in the
|
||||
night Stages (1–3 and 11–12)</span>
|
||||
@@ -555,7 +590,7 @@ ul.blocked li{padding:2px 0}
|
||||
</details>
|
||||
|
||||
<div class="lb-span">
|
||||
<button id="lb-create" type="button">Create game</button>
|
||||
<button id="lb-create" type="button">Create new game</button>
|
||||
<p class="lb-error" id="lb-create-err" role="alert"></p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -616,16 +651,29 @@ ul.blocked li{padding:2px 0}
|
||||
<p class="ng-note">One railroad, one player, five full days by default — everything below is
|
||||
yours to change before you deal. Clearing the Revenue floor wins; falling short loses.</p>
|
||||
|
||||
<!-- THE SAME THREE PARAMETERS THE LOBBY ASKS, in the same order, with the same note under them
|
||||
(Jesse, 2026-08-30: "everything beneath that should be the same"). The table size is here
|
||||
rather than hidden because it is one of the three things that describe a game, and leaving
|
||||
it out made this screen a different form that happened to share a rules block. It is LOCKED
|
||||
at one: a `LocalSession` runs the engine in this browser and a table needs a server, which
|
||||
is the same reason the four multiplayer game types are shown disabled below. -->
|
||||
<div class="lb-params">
|
||||
<label class="ng-num"><span>Seed</span>
|
||||
<input id="ss-seed" type="text" inputmode="numeric" autocomplete="off" placeholder="blank for a random seed"></label>
|
||||
<label class="ng-num"><span>Players at the table</span>
|
||||
<select id="ss-players" disabled>
|
||||
<option value="1" selected>1</option>
|
||||
</select></label>
|
||||
<label class="ng-num"><span>Days</span>
|
||||
<input id="ss-days" type="number" min="1" max="20" step="1" value="5"></label>
|
||||
</div>
|
||||
<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>
|
||||
<p class="ng-note">Every chair must be filled before the game can start. For solitaire,
|
||||
there’s only one player. For multiplayer, that must be filled by a person or a
|
||||
bot. The number of players cannot be changed once the game is created.</p>
|
||||
|
||||
<h3>Game type</h3>
|
||||
<h3>Game type (solitaire)</h3>
|
||||
<div class="set-row" id="ss-type-row">
|
||||
<label class="ng-radio"><input type="radio" name="ss-type" value="solitaire" checked>
|
||||
<span><b>Solitaire</b><br><span class="dim">One railroad, one player. The whole Division is yours to run.</span></span></label>
|
||||
@@ -639,19 +687,20 @@ ul.blocked li{padding:2px 0}
|
||||
<span><b>Custom</b><br><span class="dim">Whatever you set below. Selected for you the moment you change a rule; it is scored as the type you started from.</span></span></label>
|
||||
</div>
|
||||
|
||||
<p class="ng-note" id="ss-type-note"></p>
|
||||
|
||||
|
||||
<details id="ss-settings" open>
|
||||
<summary>Game settings</summary>
|
||||
<p class="ng-note">Every rule the game type sets, and every one of them yours to change.
|
||||
Changing any of them selects <b>Custom</b>; clicking a type again resets all of them back
|
||||
to it.</p>
|
||||
Changing any of them selects <b>Custom</b>, which keeps the scoring of the type you
|
||||
started from; changing the game type resets all of them back to it. They are fixed when the
|
||||
game is created and cannot be changed once it starts.</p>
|
||||
<div class="set-groups">
|
||||
|
||||
<div class="set-group">
|
||||
<h3>Starting hand</h3>
|
||||
<p class="ng-note">What you are dealt before the first turn. The hand limit is three either
|
||||
way — deal six and the first turn is spent choosing which of them to keep.</p>
|
||||
<p class="ng-note">What each player is dealt before the first turn. The hand limit is three
|
||||
either way — deal six and the first turn is spent choosing which of them to keep.</p>
|
||||
<div class="set-row" id="ss-hand-row">
|
||||
<label class="ng-radio"><input type="radio" name="ss-hand" value="threeRandom">
|
||||
<span><b>Three random cards</b><br><span class="dim">The original rule. At the hand limit already, and no guarantee of track.</span></span></label>
|
||||
@@ -708,7 +757,8 @@ ul.blocked li{padding:2px 0}
|
||||
|
||||
<div class="set-group">
|
||||
<h3>Victory conditions</h3>
|
||||
<p class="ng-note">The ways this game can end badly. How long it runs is set above, in Days.</p>
|
||||
<p class="ng-note">The ways this game can end badly. Each one is switched on or off in its own
|
||||
right; how long the game runs is set above, with the table size.</p>
|
||||
<div class="set-row" id="ss-minrev-row">
|
||||
<label class="ng-gate"><input type="checkbox" id="ss-minrev-on" checked>
|
||||
<span>You lose if Revenue at the end is under</span>
|
||||
@@ -717,13 +767,13 @@ ul.blocked li{padding:2px 0}
|
||||
</div>
|
||||
<div class="set-row" id="ss-colday-row">
|
||||
<label class="ng-gate"><input type="checkbox" id="ss-colday-on" checked>
|
||||
<span>The game ends in a loss if collisions in one Day reach</span>
|
||||
<span>The game ends immediately and results in a loss if collisions in one Day reach</span>
|
||||
<input id="ss-colday" type="number" min="0" step="1" class="gate-num"></label>
|
||||
<span class="set-hint" id="ss-colday-hint"></span>
|
||||
</div>
|
||||
<div class="set-row" id="ss-coltotal-row">
|
||||
<label class="ng-gate"><input type="checkbox" id="ss-coltotal-on" checked>
|
||||
<span>The game ends in a loss after this many collisions in the whole game</span>
|
||||
<span>The game ends immediately and results in a loss after this many collisions in the whole game</span>
|
||||
<input id="ss-coltotal" type="number" min="0" step="1" class="gate-num"></label>
|
||||
<span class="set-hint" id="ss-coltotal-hint"></span>
|
||||
</div>
|
||||
@@ -734,7 +784,7 @@ ul.blocked li{padding:2px 0}
|
||||
|
||||
<div class="set-group">
|
||||
<h3>Optional rules</h3>
|
||||
<p class="ng-note">Off in every game type; each one changes how the game plays.</p>
|
||||
<p class="ng-note">Each one changes how the game plays.</p>
|
||||
<div class="set-row" id="ss-visibility-row">
|
||||
<label class="ng-num"><span>Reduced Visibility — five switching Moves instead of six in the
|
||||
night Stages (1–3 and 11–12)</span>
|
||||
@@ -742,8 +792,7 @@ ul.blocked li{padding:2px 0}
|
||||
<span class="set-hint" id="ss-visibility-hint"></span>
|
||||
</div>
|
||||
<div class="set-row" id="ss-rotation-row">
|
||||
<label class="ng-num"><span>Employee Rotation — meaningless at a table of one, shown here so
|
||||
this screen and the lobby read as one list</span>
|
||||
<label class="ng-num"><span>Employee Rotation — not applicable for solitaire</span>
|
||||
<input id="ss-rotation" type="checkbox" disabled></label>
|
||||
<span class="set-hint" id="ss-rotation-hint"></span>
|
||||
</div>
|
||||
@@ -765,8 +814,17 @@ ul.blocked li{padding:2px 0}
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- Shown only when `station-master.save.v1` holds a game. Dealing from this screen CLEARS that
|
||||
save (`commitNewGame` calls `clearSave`), so without a way back the door would be a way to
|
||||
lose a game in progress — and the door is reached by clicking "Play solitaire", which nobody
|
||||
reads as "discard what I was playing". -->
|
||||
<p id="ss-saved-note" hidden><b>You have a solitaire game in progress.</b> Creating a new game
|
||||
replaces it permanently — there is no undo. Choose <b>Continue saved game</b> to pick it
|
||||
up where you left off.</p>
|
||||
|
||||
<menu class="ng-buttons">
|
||||
<button id="ss-deal" type="button">Deal</button>
|
||||
<button id="ss-resume" type="button" hidden>Continue saved game</button>
|
||||
<button id="ss-deal" type="button">Create new game</button>
|
||||
</menu>
|
||||
</section>
|
||||
</div>
|
||||
@@ -779,20 +837,23 @@ ul.blocked li{padding:2px 0}
|
||||
<!-- The objective, and nothing else: score, target, Days left. The "behind the pace" chip and the
|
||||
engine's guess at what your score ought to be were noise on the one line that must not wrap. -->
|
||||
<span id="objective" class="pace">—</span>
|
||||
<span class="dim">seed <span id="seed">—</span></span>
|
||||
<!-- THE COLLISION COUNTS, WHICH ARE A LIVE SCORE AND NOT A SETTING (TODO #28). The Frame has
|
||||
carried `collisionsToday` and `collisionsTotal` since v0.7.0 and nothing on the board drew
|
||||
them, so the one victory condition that can end a game early was invisible while it ran.
|
||||
Empty and collapsed when both limits are 0 — a game that cannot end this way should not be
|
||||
counting towards it. The limits themselves live in the This Game card; this is progress. -->
|
||||
<span class="dim" id="collisions" title=""></span>
|
||||
<!-- THE GAME CODE SURVIVES THE LOBBY. It used to end at `Lobby.Start` — the code was never carried
|
||||
into `LobbyReady` — so a seated player could not say which game they were in, could not match
|
||||
it against the administrator's Games in Progress list, and could not pass it to a latecomer.
|
||||
Empty (and collapsed) in solitaire, where there is no code. -->
|
||||
<span class="dim" id="gamecode" title="The code this game was created under. The administrator's Games in Progress list uses it, and it is how you say which game you mean."></span>
|
||||
<!-- Co-op, Competitive, Cutthroat or Custom, derived from the config the Frame carries
|
||||
(`presets.ts`). A Cutthroat game used to look exactly like a Co-op one from the board. -->
|
||||
<span class="dim" id="gametype" title=""></span>
|
||||
<!-- WHICH RULES THIS GAME IS BEING PLAYED UNDER. The settings are chosen when the game is dealt
|
||||
and then never mentioned again, which makes a playtest note ("scored 4") unreadable a week
|
||||
later: at 0 revenue per transit that is a different game from the same seed at 5. Short enough
|
||||
to keep the header on one line; the tooltip spells it out. -->
|
||||
<span class="dim" id="houserules" title="">—</span>
|
||||
<!-- The seed, the seat, the game type and every house rule MOVED TO THE THIS GAME CARD, 2026-08-30
|
||||
(TODO #28). Jesse: "we can give complete information about all the game options and not take
|
||||
up valuable real estate at the top of the screen… it is not something that they're likely to
|
||||
need all the time." What stays here is what is glanced at every turn — Revenue, the objective,
|
||||
the collision counts — plus the game code, which is identity rather than settings: it is how
|
||||
you say WHICH game you are in, out loud, without opening anything. -->
|
||||
<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
|
||||
@@ -802,7 +863,7 @@ ul.blocked li{padding:2px 0}
|
||||
</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>
|
||||
<button id="newgame" title="Set up a fresh game — the seed, the table, the opening hand and what the three economies pay. Opens the same screen a new solitaire game starts from, with your current rules filled in; your game in progress is kept until you press Deal, and Continue puts it straight back.">New game</button>
|
||||
<button id="multiplayer" title="Create or join a Competitive or Co-op game on this server, with other players.">Multiplayer</button>
|
||||
<!-- LEAVING A RUNNING GAME. Reported by Jesse 2026-08-23: "if I'm a player in the middle of the
|
||||
game and I need to leave, how do I leave the game, clear the token from my browser so I can
|
||||
@@ -836,7 +897,7 @@ ul.blocked li{padding:2px 0}
|
||||
<section id="district">
|
||||
<h2>Your Office Area
|
||||
<span class="dim" style="text-transform:none;letter-spacing:0">— hover any card for the full explanation</span>
|
||||
<button id="districttoggle" class="ghost" title="Auto-hide keeps the district open during Local Operations and Cargo — the phases that change it — and folds it otherwise. Click to pin it open or hidden instead.">auto-hide: on</button>
|
||||
<span id="districttoggle" class="seg" role="group" aria-label="When to show your Office Area"><button id="dm-auto" class="ghost" type="button" title="Open during Local Operations and Cargo — the phases that change the district — and folded otherwise.">Auto-hide</button><button id="dm-open" class="ghost" type="button" title="Keep the Office Area open in every phase.">Always show</button><button id="dm-closed" class="ghost" type="button" title="Keep the Office Area folded in every phase. The summary line stays, so it reads as folded rather than missing.">Always hide</button></span>
|
||||
</h2>
|
||||
<div id="districtsummary" class="dim"></div>
|
||||
<!-- THE RULE THAT SHAPES EVERY DISTRICT, said once where the district is.
|
||||
@@ -880,190 +941,34 @@ ul.blocked li{padding:2px 0}
|
||||
</section>
|
||||
<section><h2>Blocked — why nothing is moving</h2><ul class="blocked" id="blocked"></ul></section>
|
||||
<section><h2>Facilities</h2><div id="facs"></div></section>
|
||||
<!-- THIS GAME — the settings it was dealt under, off the top line and out of the way (TODO #28).
|
||||
Last in the column and folded by default because it is looked up, not watched: "Oh wait,
|
||||
what did we set that to?" The body is `rulesListHtml`, the same renderer the join preview
|
||||
and the seating screen draw, so what you agreed to in the lobby and what you can read
|
||||
mid-game cannot drift apart. -->
|
||||
<section id="gamecard" class="folded"><h2>This Game
|
||||
<button id="gamecardtoggle" class="ghost" type="button" title="The seed, the seat, the game type and every rule this game was dealt under.">show</button>
|
||||
</h2>
|
||||
<div id="gamecardsummary" class="dim"></div>
|
||||
<div id="gamecardbody"></div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- ===================================================================
|
||||
NEW GAME — the seed, the opening hand, and what the three economies pay.
|
||||
<!-- THE IN-GAME "NEW GAME" BUTTON GOES TO THE SOLITAIRE SETUP SCREEN — there is no second
|
||||
dialog any more (Jesse, 2026-08-30: "it should not go to a separate screen. We should reuse the
|
||||
Solitaire New Game Screen… in general we should reuse what we already have").
|
||||
|
||||
It was a `prompt()` asking for a seed. Two of the three things that decide what kind of game
|
||||
you are about to play had no way in at all: the opening hand had been changed twice with no
|
||||
way back to the earlier rule, and the revenue rates were constants in the source. Balance is
|
||||
the open question in this game (`TODO.md`), and the way to settle it is to deal several games
|
||||
at different settings — which needs a dialog, not a rebuild.
|
||||
`#newgamedlg` was a third copy of the same questions, and the one that drifted: it kept the
|
||||
multiplayer wording ("Everyone loses if COMBINED Revenue…") on a screen only ever shown to a
|
||||
solitaire player, and explained Employee Rotation in full beside a control it had disabled.
|
||||
Deleting it removes the drift rather than re-wording it.
|
||||
|
||||
Every control has a default that is the recommended answer, so DEAL with nothing touched is a
|
||||
complete, sensible game. The settings ride in the URL alongside the seed, because a seed alone
|
||||
no longer names a game: `?seed=430` with a different opening hand is a different railroad.
|
||||
==================================================================== -->
|
||||
Nothing is lost by navigating away mid-game: `render()` calls `save()` on every frame, so the
|
||||
game in progress is always on disk, and the setup screen offers "Continue saved game"
|
||||
to come straight back to it. -->
|
||||
</div><!-- /gameui -->
|
||||
|
||||
<dialog id="newgamedlg" aria-labelledby="ng-title">
|
||||
<form method="dialog" id="newgameform">
|
||||
<h2 class="big" id="ng-title">New game</h2>
|
||||
|
||||
<!-- THE SAME BLOCK THE LOBBY USES, same shared module, same order — the two screens are one
|
||||
design. Only Solitaire can be dealt here; the multiplayer types are shown disabled rather
|
||||
than hidden, so what this screen offers and what the lobby offers read as one list. -->
|
||||
<div class="lb-params">
|
||||
<label class="ng-num"><span>Seed</span>
|
||||
<input id="ng-seed" type="text" inputmode="numeric" autocomplete="off" placeholder="blank for a random seed"></label>
|
||||
<label class="ng-num"><span>Days</span>
|
||||
<input id="ng-days" type="number" min="1" max="20" step="1" value="5"></label>
|
||||
</div>
|
||||
<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>
|
||||
|
||||
<h3>Game type</h3>
|
||||
<div class="set-row" id="ng-type-row">
|
||||
<label class="ng-radio"><input type="radio" name="ng-type" value="solitaire">
|
||||
<span><b>Solitaire</b><br><span class="dim">One railroad, one player. The whole Division is yours to run.</span></span></label>
|
||||
<label class="ng-radio"><input type="radio" name="ng-type" value="coop" checked>
|
||||
<span><b>Co-op</b><br><span class="dim">Everyone’s Revenue is one table score. You win together or lose together.</span></span></label>
|
||||
<label class="ng-radio"><input type="radio" name="ng-type" value="competitive">
|
||||
<span><b>Competitive</b><br><span class="dim">Highest Revenue wins — unless the table misses its combined minimum, and then everyone loses.</span></span></label>
|
||||
<label class="ng-radio"><input type="radio" name="ng-type" value="cutthroat">
|
||||
<span><b>Cutthroat</b><br><span class="dim">Highest Revenue wins, and nothing is shared — the only way everyone loses is three collisions in one Day.</span></span></label>
|
||||
<label class="ng-radio"><input type="radio" name="ng-type" value="custom">
|
||||
<span><b>Custom</b><br><span class="dim">Whatever you set below. Selected for you the moment you change a rule; it is scored as the type you started from.</span></span></label>
|
||||
</div>
|
||||
|
||||
<p class="ng-note" id="ng-type-note"></p>
|
||||
|
||||
<details id="ng-settings" open>
|
||||
<summary>Game settings</summary>
|
||||
<p class="ng-note">Every rule the game type sets, and every one of them yours to change.
|
||||
Changing any of them selects <b>Custom</b>; clicking a type again resets all of them back
|
||||
to it.</p>
|
||||
<div class="set-groups">
|
||||
|
||||
<div class="set-group">
|
||||
<h3>Starting hand</h3>
|
||||
<p class="ng-note">What each player is dealt before the first turn. The hand limit is three
|
||||
either way — deal six and the first turn is spent choosing which of them to keep.</p>
|
||||
<div class="set-row" id="ng-hand-row">
|
||||
<label class="ng-radio"><input type="radio" name="ng-hand" value="threeRandom">
|
||||
<span><b>Three random cards</b><br><span class="dim">The original rule. At the hand limit already, and no guarantee of track.</span></span></label>
|
||||
<label class="ng-radio"><input type="radio" name="ng-hand" value="sixRandom" checked>
|
||||
<span><b>Six random cards</b><br><span class="dim">Twice the choice, still no guaranteed track — the first turn is a discard.</span></span></label>
|
||||
<label class="ng-radio"><input type="radio" name="ng-hand" value="threeTrackThreeOther">
|
||||
<span><b>Three random track and three random non-track cards</b><br><span class="dim">Dealt from two piles, so the district you can build is dealt rather than waited for.</span></span></label>
|
||||
<span class="set-hint" id="ng-hand-hint"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-group">
|
||||
<h3>Where an Extra may start</h3>
|
||||
<p class="ng-note">The player who plays an Extra Train card chooses where its Crew Tray goes,
|
||||
and the place decides which way it runs — a Division Point sends it away from itself; in the
|
||||
middle of the railroad the player picks east or west. The Division Points and the Interchange
|
||||
belong to nobody and are always available. Starting one inside a district is the part that
|
||||
favours a seat, so it is set here. An Office must be a Control Point whatever this says: a
|
||||
Whistle Post never qualifies.</p>
|
||||
<div class="set-row" id="ng-extra-row">
|
||||
<label class="ng-radio"><input type="radio" name="ng-extra" value="divisionPointsOnly">
|
||||
<span><b>Division Points and the Interchange only</b><br><span class="dim">The strictest reading. Every Extra begins on shared ground.</span></span></label>
|
||||
<label class="ng-radio"><input type="radio" name="ng-extra" value="ownOffice">
|
||||
<span><b>Also the playing player’s own Control Point</b><br><span class="dim">You may start one at home, but not in somebody else’s district.</span></span></label>
|
||||
<label class="ng-radio"><input type="radio" name="ng-extra" value="anyOffice">
|
||||
<span><b>Also any player’s Control Point</b><br><span class="dim">The most permissive — an Extra may be planted in another player’s district.</span></span></label>
|
||||
<span class="set-hint" id="ng-extra-hint"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-group">
|
||||
<h3>Revenue</h3>
|
||||
<p class="ng-note">What each piece of work pays, 0 to 5. A coach pays when it is boarded and
|
||||
again when it is detrained; a load pays when it is made up and again when it is broken. Zero
|
||||
switches an economy off so the others can be read.</p>
|
||||
<div class="set-row" id="ng-passenger-row">
|
||||
<label class="ng-num"><span>Passenger revenue per coach</span>
|
||||
<input id="ng-passenger" type="number" min="0" max="5" step="1" value="1"></label>
|
||||
<span class="set-hint" id="ng-passenger-hint"></span>
|
||||
</div>
|
||||
<div class="set-row" id="ng-freight-row">
|
||||
<label class="ng-num"><span>Freight revenue per load</span>
|
||||
<input id="ng-freight" type="number" min="0" max="5" step="1" value="1"></label>
|
||||
<span class="set-hint" id="ng-freight-hint"></span>
|
||||
</div>
|
||||
<div class="set-row" id="ng-transit-row">
|
||||
<label class="ng-num"><span>Train revenue per transit</span>
|
||||
<input id="ng-transit" type="number" min="0" max="5" step="1" value="0"></label>
|
||||
<span class="set-hint" id="ng-transit-hint"></span>
|
||||
</div>
|
||||
<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.</p>
|
||||
</div>
|
||||
|
||||
<div class="set-group">
|
||||
<h3>Victory conditions</h3>
|
||||
<p class="ng-note">The ways this game can end badly. Each one is switched on or off in its own
|
||||
right; how long the game runs is set above, with the table size.</p>
|
||||
<div class="set-row" id="ng-minrev-row">
|
||||
<label class="ng-gate"><input type="checkbox" id="ng-minrev-on" checked>
|
||||
<span>Everyone loses if combined Revenue at the end is under</span>
|
||||
<input id="ng-minrev" type="number" min="0" step="1" class="gate-num"></label>
|
||||
<span class="set-hint" id="ng-minrev-hint"></span>
|
||||
</div>
|
||||
<div class="set-row" id="ng-colday-row">
|
||||
<label class="ng-gate"><input type="checkbox" id="ng-colday-on" checked>
|
||||
<span>The game ends and everyone loses if collisions in one Day reach</span>
|
||||
<input id="ng-colday" type="number" min="0" step="1" class="gate-num"></label>
|
||||
<span class="set-hint" id="ng-colday-hint"></span>
|
||||
</div>
|
||||
<div class="set-row" id="ng-coltotal-row">
|
||||
<label class="ng-gate"><input type="checkbox" id="ng-coltotal-on" checked>
|
||||
<span>The game ends and everyone loses after this many collisions in the whole game</span>
|
||||
<input id="ng-coltotal" type="number" min="0" step="1" class="gate-num"></label>
|
||||
<span class="set-hint" id="ng-coltotal-hint"></span>
|
||||
</div>
|
||||
<p class="ng-note">The opponent-directed cards — Derail, Watertower, Hobo Jungle and the
|
||||
nineteen others, along with the seven that answer them — are not implemented yet, so no game
|
||||
type deals them whatever else is set here.</p>
|
||||
</div>
|
||||
|
||||
<div class="set-group">
|
||||
<h3>Optional rules</h3>
|
||||
<p class="ng-note">Off in every game type; each one changes how the game plays.</p>
|
||||
<div class="set-row" id="ng-visibility-row">
|
||||
<label class="ng-num"><span>Reduced Visibility — five switching Moves instead of six in the
|
||||
night Stages (1–3 and 11–12)</span>
|
||||
<input id="ng-visibility" type="checkbox"></label>
|
||||
<span class="set-hint" id="ng-visibility-hint"></span>
|
||||
</div>
|
||||
<div class="set-row" id="ng-rotation-row">
|
||||
<label class="ng-num"><span>Employee Rotation — at the end of each Day everyone moves one
|
||||
chair left and takes over the next station up the line. Your Revenue and the Fedora go with
|
||||
you; the district stays where it is</span>
|
||||
<input id="ng-rotation" type="checkbox"></label>
|
||||
<span class="set-hint" id="ng-rotation-hint"></span>
|
||||
</div>
|
||||
<div class="set-row" id="ng-toolbox-row">
|
||||
<label class="ng-num"><span>Emergency Toolbox — everyone starts holding a Red Flag, so a hand
|
||||
of four; play or discard down to three on the first turn</span>
|
||||
<input id="ng-toolbox" type="checkbox"></label>
|
||||
<span class="set-hint" id="ng-toolbox-hint"></span>
|
||||
</div>
|
||||
<div class="set-row" id="ng-tossloco-row">
|
||||
<label class="ng-num"><span>A Timetabled train may be discarded — toss it face-up to a
|
||||
Department slot, where a rival may pick it up. Turn this off and a train card can only ever
|
||||
be played onto the timetable. An Extra is never discardable either way</span>
|
||||
<input id="ng-tossloco" type="checkbox"></label>
|
||||
<span class="set-hint" id="ng-tossloco-hint"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<menu class="ng-buttons">
|
||||
<span class="ng-note" id="ng-multiplayer-note" style="margin:0 auto 0 0">Use the <b>Multiplayer</b> button instead — it creates or joins a game on this server.</span>
|
||||
<button value="cancel" id="ng-cancel" type="submit" formnovalidate>Cancel</button>
|
||||
<button value="deal" id="ng-deal" type="submit">Deal</button>
|
||||
</menu>
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<!-- THE DAY ROLLING OVER (Gitea#10). A Day turns inside the automatic phases, so it happens
|
||||
between one click and the next; the phase banner and the announcement flash both fade before
|
||||
someone reading the board notices them. A modal stops and waits, which is the whole request:
|
||||
@@ -1080,10 +985,19 @@ ul.blocked li{padding:2px 0}
|
||||
<!-- THE END-OF-GAME RESULTS (Gitea#16). Filled by `resultsHtml` and opened from `renderEnding`,
|
||||
which puts it up once per ending unasked and leaves a button to reopen it. Reopenable matters:
|
||||
Gitea#11 lets a table play past the end, and continuing must not cost you the results screen. -->
|
||||
<!-- THE EXTENSION QUESTION IS ASKED HERE, not only behind this dialog (Gitea#11 + #16).
|
||||
This opens ITSELF at every ending, and it is modal — so `renderEnding`'s "play one more Day"
|
||||
buttons, which it writes into `#actions`, sit underneath it. A player saw a results screen whose
|
||||
only control was Close and reasonably concluded the game was over: reported by Jesse
|
||||
2026-08-30, "Solitaire game ended. I did not have an option to extend the game by a day."
|
||||
Gitea#11 was verified over the HTTP API, which renders no dialog, so the browser never was.
|
||||
The two extension buttons are hidden unless the game is actually awaiting a vote. -->
|
||||
<dialog id="resultsdlg" aria-labelledby="rs-title">
|
||||
<form method="dialog">
|
||||
<div id="resultsbody"></div>
|
||||
<menu class="ng-buttons">
|
||||
<button value="extend-yes" id="rs-extend-yes" type="submit" hidden>Play One More Day</button>
|
||||
<button value="extend-no" id="rs-extend-no" type="submit" hidden>End the Game Here</button>
|
||||
<button value="ok" id="rs-ok" type="submit">Close</button>
|
||||
</menu>
|
||||
</form>
|
||||
|
||||
+8
-2
@@ -119,8 +119,14 @@ export const PRESETS: readonly Preset[] = [
|
||||
revenueFloor: (players, days) => collectiveRevenueFloor(players, days),
|
||||
rules: {
|
||||
startingHand: SIX,
|
||||
// Nobody else's district exists, so "any Control Point" and "your own" are the same rule.
|
||||
extraStart: 'anyOffice',
|
||||
/**
|
||||
* Nobody else's district exists, so "any Control Point" and "your own" are the same rule —
|
||||
* `apply.ts` only ever rejects `ownOffice` when `start.seat !== seatOf(s, player)`, which
|
||||
* cannot happen at one seat. It said `anyOffice` until 2026-08-30, which was true and read
|
||||
* wrong: a solitaire player has no "any player" to contrast themselves with, so the permissive
|
||||
* label described a permission nobody was being granted. Jesse's call; no gameplay effect.
|
||||
*/
|
||||
extraStart: 'ownOffice',
|
||||
passengerPerCoach: 1,
|
||||
freightPerLoad: 1,
|
||||
trainPerTransit: 0,
|
||||
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
handPlayable,
|
||||
isOutOfTurn,
|
||||
newGame,
|
||||
overHandLimit,
|
||||
submit,
|
||||
toSave,
|
||||
undo,
|
||||
@@ -58,8 +57,6 @@ export type Session = {
|
||||
seat(): PlayerIndex;
|
||||
/** Whose turn it is, or null when the game is over or waiting on nothing. */
|
||||
actor(): PlayerIndex | null;
|
||||
/** True when the hand is over §6.2's limit and the turn cannot be ended. */
|
||||
overHandLimit(): boolean;
|
||||
/** Which cards in hand are playable right now, in hand order. */
|
||||
handPlayable(): boolean[];
|
||||
/**
|
||||
@@ -161,7 +158,6 @@ export function createLocalSession(seed: number, options?: NewGameOptions): Loca
|
||||
menu: () => actionMenu(game),
|
||||
seat: () => 0,
|
||||
actor: () => currentActor(game),
|
||||
overHandLimit: () => overHandLimit(game),
|
||||
handPlayable: () => handPlayable(game),
|
||||
submit: async (intent: Intent) => {
|
||||
// Seat 0 is the solitaire player, and the extension vote (Gitea#11) is the one intent that
|
||||
@@ -341,7 +337,6 @@ export function createRemoteSession(
|
||||
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++;
|
||||
|
||||
+24
-1
@@ -655,13 +655,36 @@ describe('victory conditions (§3, Gap 10e) — unified 2026-08-20', () => {
|
||||
assert.notEqual(s.status, 'finished');
|
||||
});
|
||||
|
||||
it('solitaire never checks the collision floor, whatever the counts', () => {
|
||||
it('solitaire checks the collision floor too, like every other mode', () => {
|
||||
/**
|
||||
* REVERSED 2026-08-30, and this test previously asserted the opposite ("solitaire never checks
|
||||
* the collision floor, whatever the counts").
|
||||
*
|
||||
* The exclusion was never a stated rule — §3.4 does not carve solitaire out — and nothing on
|
||||
* screen reflected it: `SOLO_CONFIG` carried both limits, the New Game dialog offered them as
|
||||
* live settings, and the text beside them said the game would end in a loss. A solitaire player
|
||||
* could set a limit of 1 and crash all game. Found reviewing that screen's wording; Jesse's
|
||||
* ruling is that the settings do what they say.
|
||||
*/
|
||||
const s = game(1, { mode: 'solitaire', maxCollisionsPerDay: 1, maxCollisionsTotal: 1 });
|
||||
s.collisionsToday = 99;
|
||||
s.collisionsTotal = 99;
|
||||
s.clock.stage = 1;
|
||||
s.clock.phase = 'shiftChange';
|
||||
advance(s);
|
||||
assert.equal(s.status, 'finished');
|
||||
assert.equal(s.outcome!.reason, 'collisionFloor');
|
||||
});
|
||||
|
||||
it('still lets a solitaire game switch the collision floor off with 0', () => {
|
||||
// The disable path is what a player who does not want the new ending reaches for, so it has to
|
||||
// work at one seat exactly as it does at four.
|
||||
const s = game(1, { mode: 'solitaire', maxCollisionsPerDay: 0, maxCollisionsTotal: 0 });
|
||||
s.collisionsToday = 99;
|
||||
s.collisionsTotal = 99;
|
||||
s.clock.stage = 1;
|
||||
s.clock.phase = 'shiftChange';
|
||||
advance(s);
|
||||
assert.notEqual(s.status, 'finished');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* The card reference must not drift from the cards.
|
||||
*
|
||||
* `docs/rules/card-reference.md` spent several releases describing the v0.4.5 deck — twelve numbered
|
||||
* trains, "3 / 4 Mail-Express, 3 coaches" — while `content.ts` had train 3 as the Express with two
|
||||
* freight cars and a per-location freight rule. Worse, `content.ts` named that file as "the place
|
||||
* that now carries what the cards say", so the code sent readers to a table its own banner told them
|
||||
* not to trust. Nothing failed, because nothing checked.
|
||||
*
|
||||
* `docs/rules/as-built.md` is emitted from the same exported catalogues the engine instantiates
|
||||
* from, and this re-runs the generator and compares. Change a card face without regenerating and
|
||||
* this goes red — which is the whole point: a document nothing verifies is a document that will be
|
||||
* wrong, and this project's own history is the evidence.
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const doc = join(root, 'docs/rules/as-built.md');
|
||||
|
||||
describe('docs/rules/as-built.md is generated, and current', () => {
|
||||
it('matches what the generator emits from content.ts today', () => {
|
||||
const before = readFileSync(doc, 'utf8');
|
||||
execFileSync(process.execPath, [join(root, 'scripts/build-card-reference.ts')], { cwd: root });
|
||||
const after = readFileSync(doc, 'utf8');
|
||||
assert.equal(
|
||||
after,
|
||||
before,
|
||||
'the checked-in card reference is stale — run `npm run build:cards` and commit the result',
|
||||
);
|
||||
});
|
||||
|
||||
it('carries the current train catalogue, not the v0.4.5 deck', () => {
|
||||
// The specific drift that went unnoticed for several releases, asserted by name so a future
|
||||
// regeneration against an old content.ts cannot quietly reintroduce it.
|
||||
const md = readFileSync(doc, 'utf8');
|
||||
assert.match(md, /Crack Limited/);
|
||||
assert.match(md, /\| 3 \| Express \|/);
|
||||
assert.ok(!/Mail-Express/.test(md), 'the superseded v0.4.5 train names are back');
|
||||
assert.ok(!/Manifest Freight/.test(md), 'the superseded v0.4.5 train names are back');
|
||||
});
|
||||
|
||||
it('says it is generated, so nobody edits it by hand', () => {
|
||||
const md = readFileSync(doc, 'utf8');
|
||||
assert.match(md, /Generated from `src\/engine\/content\.ts`/);
|
||||
assert.match(md, /Do not edit by/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,437 @@
|
||||
/**
|
||||
* WHAT THE ENGINE KNOWS AND THE SCREEN DOES NOT — the 2026-09-07 sweep.
|
||||
*
|
||||
* Gitea#21, Gitea#22, #94 and #96 were four instances of one fault in a row: the engine gained a
|
||||
* thing that changes what a train may do, and nothing drew it. Each was found by a player hitting
|
||||
* it. So rather than wait for the fifth, every field of `GameState` and its nested types was
|
||||
* enumerated and checked for a reader in `sim/view.ts`, `src/web/` and `sim/narrate.ts`, and the
|
||||
* survivors were then verified by running the engine rather than by trusting the grep.
|
||||
*
|
||||
* Four fields had no reader anywhere. `movedThisPhase` is set and cleared inside one `advance` call
|
||||
* and is genuinely nobody's business. The other three are these tests. The bookkeeping fields whose
|
||||
* EFFECT is already visible as legality — `freightWorked`, `drawnThisTurn`, `freightAgentUsed`,
|
||||
* `movesUsed` (its complement `movesRemaining` is on the Frame), `switchedSince` — are deliberately
|
||||
* not here: a field is not a display gap merely because no one renders it.
|
||||
*
|
||||
* The method is worth more than the three fixes, and is written down in TODO Reference · #98.
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { createGame } from '../src/engine/setup.ts';
|
||||
import { crewTrayCount, enhancementText } from '../src/engine/content.ts';
|
||||
import { areaOf } from '../src/engine/apply.ts';
|
||||
import { impediments } from '../src/sim/narrate.ts';
|
||||
import { projectDistrict, projectSharedTable, publicSnapshot, trainRules } from '../src/sim/view.ts';
|
||||
import type { CrewTray, GameConfig, GameState, PlayerIndex, SeatIndex } from '../src/engine/state.ts';
|
||||
import { seatOf } from '../src/engine/state.ts';
|
||||
|
||||
const config: GameConfig = {
|
||||
mode: 'competitive',
|
||||
days: 3,
|
||||
minCombinedRevenue: 0,
|
||||
maxCollisionsPerDay: 0,
|
||||
maxCollisionsTotal: 0,
|
||||
pvpCardsAllowed: false,
|
||||
optionalRules: { reducedVisibility: false, employeeRotation: false, emergencyToolbox: false },
|
||||
};
|
||||
|
||||
const game = (): GameState => {
|
||||
const s = createGame({ id: 'g', seed: 4242, config, playerNames: ['Ann', 'Bob'] });
|
||||
s.status = 'active';
|
||||
return s;
|
||||
};
|
||||
|
||||
/**
|
||||
* THE CREW TRAY POOL IS A MECHANIC, AND IT WAS INVISIBLE (#98).
|
||||
*
|
||||
* `state.ts` calls tray scarcity "an explicit mechanic": there are fewer trays than there are trains
|
||||
* wanting one, and which trains get held is the whole of §7. The engine knows three things about it
|
||||
* — how many trays are free, which Extras are queued for one, and which second sections are — and
|
||||
* the view read none of them.
|
||||
*
|
||||
* The panel that answers "why is nothing moving?" had exactly one tray rule, keyed off the train due
|
||||
* out THIS Stage (`s.timetable[stage - 1]`). So a player who spent a card on an Extra, or ordered a
|
||||
* second section, got a blocked panel that was completely EMPTY while their train sat behind an
|
||||
* exhausted pool — and both had been announced once in the log, in a line that promised a future
|
||||
* event ("as soon as a Crew Tray frees up") which nothing then confirmed.
|
||||
*/
|
||||
describe('the Crew Tray pool is a mechanic the player can see (#98)', () => {
|
||||
/** A table whose trays are all out, with one Extra and one second section queued behind them. */
|
||||
const jammed = (): GameState => {
|
||||
const s = game();
|
||||
s.freeTrays = [];
|
||||
s.pendingExtras.push({ trainNumber: 17, player: 0 as PlayerIndex });
|
||||
s.pendingSecondSections.push(8);
|
||||
return s;
|
||||
};
|
||||
|
||||
it('reports how many Crew Trays are free, and how many there are', () => {
|
||||
const s = game();
|
||||
const total = crewTrayCount(2);
|
||||
assert.equal(s.freeTrays.length, total, 'the premise is gone: trays were already out at setup');
|
||||
assert.deepEqual(projectSharedTable(s).crewTrays, { free: total, total });
|
||||
|
||||
s.freeTrays = s.freeTrays.slice(0, 1);
|
||||
assert.deepEqual(
|
||||
projectSharedTable(s).crewTrays,
|
||||
{ free: 1, total },
|
||||
'the pool emptied and the shared table did not notice',
|
||||
);
|
||||
});
|
||||
|
||||
it('names the trains queued for a tray, so a promise made in the log is kept on the board', () => {
|
||||
const q = projectSharedTable(jammed()).queued;
|
||||
assert.deepEqual(q.extras, [{ trainNumber: 17, player: 0 }], 'a played Extra is waiting nowhere visible');
|
||||
assert.deepEqual(q.secondSections, [8], 'an ordered second section is waiting nowhere visible');
|
||||
});
|
||||
|
||||
it('tells the player who played the Extra that it is held for want of a crew', () => {
|
||||
const blocked = impediments(jammed(), 0 as PlayerIndex);
|
||||
const extra = blocked.find((b) => /X17/.test(b.where));
|
||||
assert.ok(extra, 'the blocked panel said nothing about an Extra held for want of a Crew Tray');
|
||||
assert.match(extra.why, /Crew Tray/, 'it was listed without naming the thing it is waiting for');
|
||||
assert.equal(extra.severity, 'stuck');
|
||||
// The POOL SIZE, not a second derivation of it. Written as `trays.size + freeTrays.length`
|
||||
// first, which reads 0 of 0 for any state where a tray is neither free nor carrying a train.
|
||||
assert.match(
|
||||
extra.why,
|
||||
new RegExp(`0 of ${crewTrayCount(2)} Crew Trays free`),
|
||||
'the panel reported the wrong pool size',
|
||||
);
|
||||
});
|
||||
|
||||
it('says the same for a second section, which waits on the identical pool', () => {
|
||||
const blocked = impediments(jammed(), 0 as PlayerIndex);
|
||||
const second = blocked.find((b) => /Train 8\b/.test(b.where) && /second section/i.test(b.why));
|
||||
assert.ok(second, 'an ordered second section was queued invisibly');
|
||||
assert.match(second.why, /Crew Tray/);
|
||||
});
|
||||
|
||||
it('says none of it once a tray is free, because then nothing is being waited on', () => {
|
||||
const s = jammed();
|
||||
s.freeTrays = ['tray0'];
|
||||
const blocked = impediments(s, 0 as PlayerIndex);
|
||||
assert.equal(
|
||||
blocked.filter((b) => /Crew Tray/.test(b.why)).length,
|
||||
0,
|
||||
'a free tray still reported trains held for want of one',
|
||||
);
|
||||
});
|
||||
|
||||
it('is on the common board too — the pool is on the table, not in a hand', () => {
|
||||
const pub = publicSnapshot(jammed()) as unknown as Record<string, unknown>;
|
||||
assert.ok('crewTrays' in pub, 'a spectator cannot see the scarcity everyone at the table can');
|
||||
assert.ok('queued' in pub);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A TRAIN HELD AT THE LIMITS IS STILL ON THE BOARD (#99).
|
||||
*
|
||||
* The Interlocking enhancement is the designed answer to a full Office: instead of the automatic
|
||||
* collision of Gap 2d, "may stop an inbound train on the Limit Track" — the train is held inside the
|
||||
* player's Limits, and takes the first A/D track that frees, ahead of any newcomer.
|
||||
*
|
||||
* It was drawn NOWHERE. `arriveAtOffice` removes the tray from the Mainline node's `transits`
|
||||
* (advance.ts) and the Interlocking branch pushes it onto `area.heldAtLimits` without assigning
|
||||
* `tray.position` — so the map, which draws mainline nodes from `transits` and district squares from
|
||||
* `position.at === 'grid'`, has nothing to draw it from in either place. The train vanished off the
|
||||
* board on arrival and reappeared in the Office some Stages later.
|
||||
*
|
||||
* Measured before fixing: with the tray in `transits` the Interchange node carries its chip; with
|
||||
* the tray moved to `heldAtLimits` exactly as the engine moves it, the node's `trains` is empty and
|
||||
* no grid square has gained it.
|
||||
*
|
||||
* The fix is in the VIEW, not the engine. The engine's state is right — a held train is inside the
|
||||
* Limits and not on an A/D track, which is what `heldAtLimits` says — and `position` is left alone
|
||||
* deliberately, so nothing may treat the train as standing on a square it could be switched from.
|
||||
*/
|
||||
describe('a train held at the Limits is drawn at the Limits (#99)', () => {
|
||||
const held = (direction: 'east' | 'west') => {
|
||||
const s = game();
|
||||
const seat = seatOf(s, 0 as PlayerIndex);
|
||||
const area = areaOf(s, 0 as PlayerIndex);
|
||||
const trayId = s.freeTrays.pop()!;
|
||||
const tray: CrewTray = {
|
||||
id: trayId,
|
||||
trainNumber: 5,
|
||||
trainIsExtra: false,
|
||||
engineAt: 0,
|
||||
consist: [],
|
||||
direction,
|
||||
movesUsed: 0,
|
||||
position: { at: 'mainline', index: 1 },
|
||||
} as CrewTray;
|
||||
s.trays.set(trayId, tray);
|
||||
area.heldAtLimits.push(trayId);
|
||||
return { s, seat, trayId, area };
|
||||
};
|
||||
|
||||
it('draws it on the Limits square it is standing at, not nowhere', () => {
|
||||
const { s, seat, trayId, area } = held('east');
|
||||
const { cells } = projectDistrict(s, seat as SeatIndex);
|
||||
const on = cells.filter((c) => c.trains.some((t) => t.trayId === trayId));
|
||||
assert.equal(on.length, 1, 'a train held at the Limits is drawn on no square at all');
|
||||
assert.equal(on[0]!.row, area.limitsWest.row, 'drawn at the wrong Limits');
|
||||
assert.equal(on[0]!.col, area.limitsWest.col);
|
||||
});
|
||||
|
||||
it('holds an EASTBOUND train at the western Limits, because that is the end it came in by', () => {
|
||||
const { s, seat, area } = held('east');
|
||||
const { cells } = projectDistrict(s, seat as SeatIndex);
|
||||
const on = cells.find((c) => c.trains.length > 0)!;
|
||||
assert.deepEqual({ row: on.row, col: on.col }, { row: area.limitsWest.row, col: area.limitsWest.col });
|
||||
});
|
||||
|
||||
it('and a WESTBOUND train at the eastern Limits', () => {
|
||||
const { s, seat, area } = held('west');
|
||||
const { cells } = projectDistrict(s, seat as SeatIndex);
|
||||
const on = cells.find((c) => c.trains.length > 0)!;
|
||||
assert.deepEqual({ row: on.row, col: on.col }, { row: area.limitsEast.row, col: area.limitsEast.col });
|
||||
});
|
||||
|
||||
it('says on the chip that it is HELD, so it is not read as a train free to switch', () => {
|
||||
const { s, seat, trayId } = held('east');
|
||||
const { cells } = projectDistrict(s, seat as SeatIndex);
|
||||
const chip = cells.flatMap((c) => c.trains).find((t) => t.trayId === trayId)!;
|
||||
assert.equal(chip.heldAtLimits, true, 'a held train looked exactly like one standing on the square');
|
||||
assert.match(chip.what, /Interlocking|held/i, 'the chip does not say why it is standing there');
|
||||
});
|
||||
|
||||
it('tells the district owner it is waiting, and what for', () => {
|
||||
const { s } = held('east');
|
||||
const blocked = impediments(s, 0 as PlayerIndex);
|
||||
const b = blocked.find((x) => /Train 5/.test(x.where) && /Limits/i.test(x.why));
|
||||
assert.ok(b, 'the blocked panel said nothing about a train held at the Limits');
|
||||
});
|
||||
|
||||
it('does not invent a train on a square when nothing is held', () => {
|
||||
const s = game();
|
||||
const { cells } = projectDistrict(s, seatOf(s, 0 as PlayerIndex) as SeatIndex);
|
||||
assert.equal(cells.flatMap((c) => c.trains).length, 0, 'a district with no trains drew one');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* THE CAMPAIGN TRAIN'S SPEECHES CHANGE ITS RULES, AND THE CARD HAS TO SAY WHICH HALF IT IS IN (#100).
|
||||
*
|
||||
* X17 is "one turn at station (speeches) then expedite". Its first Office arrival is an ordinary
|
||||
* stop; every arrival after that runs EXPEDITED, which means that if it is not back on the Office
|
||||
* square when the next Mainline Phase begins it is a Station Master fault costing 1 Revenue.
|
||||
*
|
||||
* `trainRules()` took `{ trainNumber, trainIsExtra }` — it could not see `speechMade` even though
|
||||
* both of its tray-side callers pass a whole `CrewTray` that has it. So the chip read identically
|
||||
* before and after, and worse: the "EXPEDITED — must be kept ready to highball… costs 1 Revenue"
|
||||
* warning is printed only under `rules.expedite`, so X17 became subject to a fault whose warning the
|
||||
* game shows to other trains and never to it.
|
||||
*/
|
||||
describe('the Campaign Train says whether its speeches are made (#100)', () => {
|
||||
const X17 = { trainNumber: 17, trainIsExtra: true } as const;
|
||||
|
||||
it('before the speeches, says they are still to come and does not claim it is expedited yet', () => {
|
||||
const t = trainRules({ ...X17 });
|
||||
assert.match(t, /SPEECHES/i);
|
||||
assert.doesNotMatch(t, /costs 1 Revenue/, 'it warned of a fault the train is not yet subject to');
|
||||
});
|
||||
|
||||
it('after the speeches, says it is expedited NOW and carries the fault it is now subject to', () => {
|
||||
const t = trainRules({ ...X17, speechMade: true });
|
||||
assert.match(t, /EXPEDITED/, 'a train that is now expedited did not say so');
|
||||
assert.match(t, /costs 1 Revenue/, 'the fault warning is shown to other trains and not to this one');
|
||||
});
|
||||
|
||||
it('reads differently before and after — the whole of the bug was that it did not', () => {
|
||||
assert.notEqual(trainRules({ ...X17 }), trainRules({ ...X17, speechMade: true }));
|
||||
});
|
||||
|
||||
it('still warns a permanently expedited train, which must not regress', () => {
|
||||
const fast = trainRules({ trainNumber: 5, trainIsExtra: false });
|
||||
assert.match(fast, /EXPEDITED/);
|
||||
assert.match(fast, /costs 1 Revenue/);
|
||||
});
|
||||
|
||||
it('says nothing about speeches for a train that has no such rule', () => {
|
||||
assert.doesNotMatch(trainRules({ trainNumber: 5, trainIsExtra: false }), /SPEECHES/i);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A DISPATCH DEVICE SAYS WHETHER IT IS STILL AVAILABLE TODAY (#101).
|
||||
*
|
||||
* Telegraph (+4), Telephone (+8) and Radio (+12) are "once a day, when dispatching facing trains,
|
||||
* add +N to the other train's number". The device is drawn on its card and its effect text is in the
|
||||
* tooltip — but `enhancementText(key)` takes only the KEY, so it could not vary with anything, and
|
||||
* the Radio read "once a day, add +12…" all Day after it had been spent. That is `trainRules` before
|
||||
* #100, in a different corner of the same view.
|
||||
*
|
||||
* THE SECOND HALF IS THE ONE THAT SURPRISES. `spendDispatchBonus` reads
|
||||
* `areaOf(s, s.clock.superintendent)` — the SUPERINTENDENT's own devices, not the train owner's —
|
||||
* and the Fedora moves every `STAGES_PER_SHIFT` Stages, four times a Day. So a player's Radio does
|
||||
* nothing at all for three-quarters of the Day, and is spent automatically, without being asked,
|
||||
* during the quarter it is theirs to use. The board said neither half.
|
||||
*
|
||||
* Shown on EVERY district (Jesse, 2026-09-07), not only the viewer's: it is public, and a rival's
|
||||
* spent Radio is exactly what you want to know before forcing a meet. `projectDistrict` serves both
|
||||
* the player's own cells and the common board's `districts`, so one change covers both.
|
||||
*/
|
||||
describe('a dispatch device says whether it is still available today (#101)', () => {
|
||||
/** Puts `key` on the first card of seat 0's district and returns the pieces to assert on. */
|
||||
const withDevice = (key: string, opts: { spent?: boolean; fedora?: boolean } = {}) => {
|
||||
const s = game();
|
||||
const area = areaOf(s, 0 as PlayerIndex);
|
||||
const card = [...area.grid.values()][0]!;
|
||||
card.enhancements.push(key);
|
||||
if (opts.spent) area.dispatchUsedToday.push(key);
|
||||
// The Fedora is a PLAYER; give it to somebody whose seat is not this district's.
|
||||
s.clock.superintendent = (opts.fedora ? 0 : 1) as PlayerIndex;
|
||||
const seat = seatOf(s, 0 as PlayerIndex);
|
||||
const cells = projectDistrict(s, seat as SeatIndex).cells;
|
||||
const cell = cells.find((c) => c.enhancements.length > 0)!;
|
||||
const i = cell.enhancementsWhat.findIndex((w) => new RegExp(key, 'i').test(w));
|
||||
return { s, area, cell, what: cell.enhancementsWhat[i] ?? '', spent: cell.enhancementsSpent[i] };
|
||||
};
|
||||
|
||||
it('reads as available before it is used, and says what it is worth', () => {
|
||||
const { what, spent } = withDevice('radio', { fedora: true });
|
||||
assert.equal(spent, false, 'an unused device reported itself spent');
|
||||
assert.match(what, /\+12/, 'the device no longer says what it is worth');
|
||||
assert.doesNotMatch(what, /spent/i, 'an unused device claimed it had been spent');
|
||||
});
|
||||
|
||||
it('says so once it has been spent, and says when it comes back', () => {
|
||||
const { what, spent } = withDevice('radio', { spent: true, fedora: true });
|
||||
assert.equal(spent, true, 'a spent device still reported itself available');
|
||||
assert.match(what, /spent/i, 'a spent device read exactly as it did before it was spent');
|
||||
assert.match(what, /next Day|tomorrow/i, 'it does not say the device comes back');
|
||||
});
|
||||
|
||||
it('reads differently spent and unspent — the whole of the bug was that it did not', () => {
|
||||
assert.notEqual(
|
||||
withDevice('telegraph', { fedora: true }).what,
|
||||
withDevice('telegraph', { spent: true, fedora: true }).what,
|
||||
);
|
||||
});
|
||||
|
||||
it('says a device is idle while somebody else holds the Fedora', () => {
|
||||
const { what } = withDevice('telephone');
|
||||
assert.match(what, /Fedora|Superintendent/i, 'nothing said the device is only used while dispatching');
|
||||
});
|
||||
|
||||
it('does not say that when this district IS the Superintendent', () => {
|
||||
const { what } = withDevice('telephone', { fedora: true });
|
||||
assert.doesNotMatch(what, /while .*holds? the Fedora/i);
|
||||
});
|
||||
|
||||
/**
|
||||
* EXACT equality, not "does not mention the Fedora". The first draft asserted the absence of
|
||||
* /spent|Fedora/i with the Fedora held, and a mutation that removed the `dispatchBonus` guard
|
||||
* altogether PASSED it — because the leaked text in that case reads "Available today, and this
|
||||
* district is dispatching", which contains neither word. A test for a field being left alone has
|
||||
* to compare it to what it should be.
|
||||
*/
|
||||
it('leaves an enhancement that is not a dispatch device exactly as it was', () => {
|
||||
for (const fedora of [true, false]) {
|
||||
const { what, spent } = withDevice('interlocking', { fedora });
|
||||
assert.equal(spent, false, 'a non-dispatch enhancement was marked spendable');
|
||||
assert.equal(what, enhancementText('interlocking'), 'an Interlocking was given a dispatch caveat');
|
||||
}
|
||||
});
|
||||
|
||||
it('comes back when the Day turns, which is what clears the record', () => {
|
||||
const { s, area } = withDevice('radio', { spent: true, fedora: true });
|
||||
area.dispatchUsedToday = [];
|
||||
const cell = projectDistrict(s, seatOf(s, 0 as PlayerIndex) as SeatIndex).cells.find(
|
||||
(c) => c.enhancements.length > 0,
|
||||
)!;
|
||||
assert.equal(cell.enhancementsSpent.some((x) => x), false, 'a new Day did not restore the device');
|
||||
});
|
||||
|
||||
/**
|
||||
* SEAT IS NOT PLAYER INDEX, and this is the one place the two are joined: the Fedora is held by a
|
||||
* PLAYER and the devices sit in an Office Area keyed by SEAT. `advance.ts` carried a comment
|
||||
* warning that indexing one with the other was safe only while seating was the identity map — it
|
||||
* read as a live bug and was not one, because `areaOf` resolves through `seatOf`. The comment is
|
||||
* corrected; this is the guard, because the next reader deserves better than a claim.
|
||||
*
|
||||
* §4.4's D12 makes seating a real permutation, so a two-player game where player 1 sits in seat 0
|
||||
* is ordinary rather than contrived.
|
||||
*/
|
||||
it("marks the SUPERINTENDENT's own district as dispatching under non-identity seating", () => {
|
||||
const s = game();
|
||||
s.seating = [1, 0] as PlayerIndex[];
|
||||
assert.notEqual(seatOf(s, 0 as PlayerIndex), 0, 'the premise is gone: seating is still identity');
|
||||
s.clock.superintendent = 0 as PlayerIndex;
|
||||
|
||||
const mine = areaOf(s, 0 as PlayerIndex);
|
||||
[...mine.grid.values()][0]!.enhancements.push('radio');
|
||||
const other = areaOf(s, 1 as PlayerIndex);
|
||||
[...other.grid.values()][0]!.enhancements.push('radio');
|
||||
|
||||
const whatAt = (player: PlayerIndex): string => {
|
||||
const cells = projectDistrict(s, seatOf(s, player) as SeatIndex).cells;
|
||||
return cells.find((c) => c.enhancements.length > 0)!.enhancementsWhat.join(' ');
|
||||
};
|
||||
// The Fedora is player 0's, whatever seat that is.
|
||||
assert.doesNotMatch(whatAt(0 as PlayerIndex), /IDLE/, "the Superintendent's own device read as idle");
|
||||
assert.match(whatAt(1 as PlayerIndex), /IDLE/, "somebody else's device read as dispatching");
|
||||
});
|
||||
|
||||
it('is on every district of the common board, not only the viewer own', () => {
|
||||
const { s } = withDevice('radio', { spent: true, fedora: true });
|
||||
const pub = publicSnapshot(s);
|
||||
const all = pub.districts.flatMap((d) => d.cells);
|
||||
assert.ok(
|
||||
all.some((c) => c.enhancementsSpent.some((x) => x)),
|
||||
"a spectator cannot see which devices are spent in a player's district",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* THE RED FLAG HOLDER IS NOT A PER-PLAYER FACT, so it does not belong on the public player view.
|
||||
*
|
||||
* `docs/plans/jitsi-common-board.md` step 1 asks for one: "Add the Red Flag holder to the public
|
||||
* player projection. It is public game state but is currently absent from `Frame`", and its
|
||||
* `PublicPlayerView` carries `redFlagHeld: boolean`. Every other step-1 item shipped across v0.7.9.2
|
||||
* to v0.7.9.5; this one is STRUCK OFF instead, because the premise does not hold in this codebase.
|
||||
*
|
||||
* `decks.redFlags` is written in exactly one place — `setup.ts`, from
|
||||
* `config.optionalRules.emergencyToolbox` — and never again. There is no `.set` anywhere else, and
|
||||
* `redFlag.play` (the intent gated on holding one) emits a `phaseEnded` event and does not spend it.
|
||||
* So every player holds one or none of them does, decided before the first card is dealt.
|
||||
*
|
||||
* A `redFlagHeld` on each player would therefore be `optionalRules.emergencyToolbox` copied N times
|
||||
* — already on the public projection — while implying to every reader of the common board that it
|
||||
* varies by player and might change during a game. That is worse than the absence.
|
||||
*
|
||||
* This test exists so the plan item is not re-raised from the plan text: if the rule ever DOES
|
||||
* become per-player, this fails and the projection is the right place to look.
|
||||
*/
|
||||
describe('the Red Flag holding is the Emergency Toolbox option, not a per-player fact', () => {
|
||||
const dealt = (emergencyToolbox: boolean): GameState =>
|
||||
createGame({
|
||||
id: 'g',
|
||||
seed: 99,
|
||||
config: { ...config, optionalRules: { ...config.optionalRules, emergencyToolbox } },
|
||||
playerNames: ['Ann', 'Bob', 'Cy'],
|
||||
});
|
||||
|
||||
for (const toolbox of [true, false]) {
|
||||
it(`gives every player the same answer with the toolbox ${toolbox ? 'on' : 'off'}`, () => {
|
||||
const s = dealt(toolbox);
|
||||
const held = s.players.map((p) => s.decks.redFlags.get(p.index) === true);
|
||||
assert.deepEqual(held, [toolbox, toolbox, toolbox], 'the Red Flag has become a per-player fact');
|
||||
});
|
||||
}
|
||||
|
||||
it('is already public, through the option it comes from', () => {
|
||||
const pub = publicSnapshot(dealt(true));
|
||||
assert.equal(
|
||||
pub.optionalRules.emergencyToolbox,
|
||||
true,
|
||||
'a spectator cannot tell whether the hand limit is three or four',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,8 @@ 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 { currentActorOfState, publicSnapshot, snapshot } from '../src/sim/view.ts';
|
||||
import { currentActor } from '../src/web/game.ts';
|
||||
import { developerBot, playGame, randomBot } from '../src/sim/bot.ts';
|
||||
import type { GameConfig, GameState } from '../src/engine/state.ts';
|
||||
|
||||
@@ -254,3 +256,69 @@ describe('§3.3 extended play — bots play the timetable they were dealt (Gitea
|
||||
assert.equal('agree' in choice ? choice.agree : null, false, 'a bot asked for another Day');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* §3.3 — WHO THE SCREEN SAYS THE TABLE IS WAITING ON, while the vote is open.
|
||||
*
|
||||
* The vote is PARALLEL, and `apply.ts` says so where it accepts one: "open to every seat at once:
|
||||
* it is a table decision rather than a ruling, so THERE IS NO ACTOR TO BE". Any seat that has not
|
||||
* voted may vote at any moment, in any order, and one refusal ends it. So the honest answer to "who
|
||||
* are we waiting on" is every un-voted seat — which is exactly what the vote tally beside the chart
|
||||
* already draws — and the honest answer to "whose turn is it" is nobody.
|
||||
*
|
||||
* The engine gave that answer and the screen did not. `currentActor(game)` guards on
|
||||
* `status !== 'active'` and returned null; `actingPlayer(state)` has no such guard and returned
|
||||
* `clock.currentActor`, which still holds whoever moved last before the timetable ran out. The
|
||||
* frame took the second, so the turn chart named one arbitrary seat — the last to act, who has no
|
||||
* more claim on the vote than anybody else — while the tally underneath correctly showed three
|
||||
* seats outstanding.
|
||||
*
|
||||
* The fourth of these in a row after Gitea#21, #22 and #94, and the first found by asking the
|
||||
* question of a state the game is not ACTIVE in. See TODO #96.
|
||||
*/
|
||||
describe('§3.3 extended play — the vote has no actor (#96)', () => {
|
||||
const table = (): GameState => {
|
||||
const s = atTheEnd(game({ mode: 'competitive' }, ['Ann', 'Bob', 'Cy']));
|
||||
advance(s);
|
||||
assert.equal(s.status, 'awaitingExtension', 'the table is not being asked');
|
||||
return s;
|
||||
};
|
||||
|
||||
it('reports nobody acting while the vote is open, to a player and to a spectator alike', () => {
|
||||
const s = table();
|
||||
assert.notEqual(s.clock.currentActor, null, 'the premise is gone: nothing was left on the clock');
|
||||
|
||||
assert.equal(currentActorOfState(s), null, 'the engine named an actor during a parallel vote');
|
||||
assert.equal(
|
||||
snapshot(s, [], null, null, null, false, 0).actor,
|
||||
null,
|
||||
'the turn chart named a seat while the whole table was voting',
|
||||
);
|
||||
assert.equal(publicSnapshot(s).actor, null, 'the common board named a seat during the vote');
|
||||
});
|
||||
|
||||
it('agrees with the session, which is the half that decides what is legal', () => {
|
||||
// The disagreement is the bug, not either answer on its own: `currentActor` is what refuses an
|
||||
// intent, so a screen that names somebody it would refuse is telling the table to wait on a
|
||||
// player who cannot act.
|
||||
const s = table();
|
||||
const g = { state: s, log: [] } as unknown as Parameters<typeof currentActor>[0];
|
||||
assert.equal(currentActorOfState(s), currentActor(g), 'the screen and the session disagree');
|
||||
});
|
||||
|
||||
it('still names the actor during ordinary play, which is the case that must not regress', () => {
|
||||
const s = game({ mode: 'competitive' }, ['Ann', 'Bob', 'Cy']);
|
||||
pump(s);
|
||||
assert.equal(s.status, 'active', 'the premise is gone: the game is not running');
|
||||
assert.equal(currentActorOfState(s), s.clock.currentActor, 'an active game lost its actor');
|
||||
assert.equal(snapshot(s, [], null, null, null, false, 0).actor, s.clock.currentActor);
|
||||
});
|
||||
|
||||
it('reports nobody once the table has declined and the game is finished', () => {
|
||||
const s = table();
|
||||
applyIntent(s, 1, { type: 'game.extend', player: 1, agree: false });
|
||||
assert.equal(s.status, 'finished', 'a refusal did not end it');
|
||||
assert.equal(currentActorOfState(s), null, 'a finished game still had somebody to move');
|
||||
assert.equal(publicSnapshot(s).actor, null, 'the common board named a seat after the game ended');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1014,7 +1014,11 @@ describe("a train is made up to its card's consist (§8.2)", () => {
|
||||
|
||||
describe('regions on a Mainline card (§2.1, §8.2)', () => {
|
||||
/** Put one train mid-crossing and ask the view where the map should draw it. */
|
||||
const regionFor = (stagesTotal: number, stagesRemaining: number): { region: number; regions: number } => {
|
||||
const regionFor = (
|
||||
stagesTotal: number,
|
||||
stagesRemaining: number,
|
||||
direction: 'east' | 'west' = 'east',
|
||||
): { region: number; regions: number } => {
|
||||
const s = createGame({
|
||||
id: 'reg',
|
||||
seed: 4,
|
||||
@@ -1027,7 +1031,7 @@ describe('regions on a Mainline card (§2.1, §8.2)', () => {
|
||||
const node = s.division.nodes.find((n) => n.kind === 'mainline');
|
||||
assert.ok(node && node.kind === 'mainline');
|
||||
const tray = [...s.trays.keys()][0]!;
|
||||
node.transits.push({ tray, stagesRemaining, stagesTotal, direction: 'east' });
|
||||
node.transits.push({ tray, stagesRemaining, stagesTotal, direction });
|
||||
const ml = snapshot(s, [], null).division.find((n) => n.kind === 'ml');
|
||||
assert.ok(ml, 'no Mainline node in the view');
|
||||
const t = ml!.trains.flat()[0]!;
|
||||
@@ -1070,6 +1074,74 @@ describe('regions on a Mainline card (§2.1, §8.2)', () => {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('never leaves the card it is on, whichever way it runs', () => {
|
||||
for (const direction of ['east', 'west'] as const) {
|
||||
for (let total = 1; total <= 4; total++) {
|
||||
for (let left = total; left >= 1; left--) {
|
||||
const r = regionFor(total, left, direction).region;
|
||||
assert.ok(r >= 0 && r <= 1, `${direction}, total ${total}, ${left} left put the train in region ${r}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GITEA#22 — A WESTBOUND TRAIN WAS DRAWN IN THE WRONG HALF OF THE CARD.
|
||||
*
|
||||
* `regionOfTransit` answers "how far along its crossing is this train", counted from the end it
|
||||
* ENTERED: a train with everything still to run is in region 0. That is the right question for the
|
||||
* collision rules, which is what the engine asks it, and both directions share the one index space.
|
||||
*
|
||||
* The map asks a different question — WHICH PRINTED BOX, left to right — and used the same number
|
||||
* for it. East is right on this map and always has been, so for an eastbound train the two agree by
|
||||
* luck: it enters at the west end, so "just entered" and "leftmost box" are the same box. A
|
||||
* westbound train enters at the EAST end, so its region 0 is the card's RIGHT-hand box, and drawing
|
||||
* it at index 0 put it at the left — the whole card mirrored.
|
||||
*
|
||||
* Reported from seed 550943578, undo 187, and it cost a collision. Three westbound trains: TX17 had
|
||||
* just entered (2 Stages still to run, so travel index 0) and T5 was nearly across (1 Stage left,
|
||||
* index 1). Physically TX17 was BEHIND T5 — further east, the direction they had both come from.
|
||||
* The map drew TX17 at the left and so put it further WEST, which reads as further ahead. Asked
|
||||
* whether Train 3 could follow Train 5 onto the card, the Superintendent said yes, and Train 3
|
||||
* entered behind — into TX17, exactly where the rules had it and nowhere near where the map did.
|
||||
*
|
||||
* The engine was right throughout. Only the picture lied, so the fix is one mirror in the view and
|
||||
* the collision rules are untouched. This is the same class of bug as the consist row at the
|
||||
* Whistle Post (`board-svg.ts`, seed 270861860), which came out mirrored for the same reason.
|
||||
*/
|
||||
describe('Gitea#22 — the map draws a westbound train where it actually is', () => {
|
||||
it('mirrors a westbound train, because it entered from the east end', () => {
|
||||
// Two-region card. Just entered, 2 Stages still to run: an eastbound train is in the WEST box
|
||||
// and a westbound one is in the EAST box, because they came in at opposite ends.
|
||||
assert.equal(regionFor(2, 2, 'east').region, 0);
|
||||
assert.equal(regionFor(2, 2, 'west').region, 1);
|
||||
|
||||
// One Stage left, nearly across: the two swap.
|
||||
assert.equal(regionFor(2, 1, 'east').region, 1);
|
||||
assert.equal(regionFor(2, 1, 'west').region, 0);
|
||||
});
|
||||
|
||||
it('puts the follower behind the leader, not in front of it — the seed 550943578 collision', () => {
|
||||
// TX17 had just entered; T5 was a Stage from the far end. Both westbound, so BEHIND means to
|
||||
// the east, which is to the right, which is the higher index.
|
||||
const tx17 = regionFor(2, 2, 'west').region;
|
||||
const t5 = regionFor(2, 1, 'west').region;
|
||||
assert.ok(
|
||||
tx17 > t5,
|
||||
`a westbound train that has just entered must be drawn east of one that is nearly across, ` +
|
||||
`but TX17 was drawn at ${tx17} and T5 at ${t5}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('leaves an eastbound train where it has always been drawn', () => {
|
||||
// The mirror must not disturb the direction that was right, which is every existing region test
|
||||
// above — those all run east — and the case the printed rule was written for.
|
||||
assert.equal(regionFor(2, 2, 'east').region, 0);
|
||||
assert.equal(regionFor(2, 1, 'east').region, 1);
|
||||
assert.equal(regionFor(1, 1, 'east').region, 1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Q13 — a train that catches the one ahead runs into it', () => {
|
||||
|
||||
@@ -29,7 +29,7 @@ import type { Game } from '../src/web/game.ts';
|
||||
/** The thin wrapper `actionMenu` expects, built directly around an already-created multi-player state
|
||||
* — `newGame` (game.ts) hardcodes one player, so it cannot construct this for a multi-seat game. */
|
||||
const wrap = (s: GameState): Game =>
|
||||
({ state: s, seed: s.seed, history: [], log: [], mustPlayCard: false, cues: [], scheduled: null, justDrawn: null, announced: null });
|
||||
({ state: s, seed: s.seed, history: [], log: [], cues: [], scheduled: null, justDrawn: null, announced: null });
|
||||
|
||||
const competitive: GameConfig = {
|
||||
mode: 'competitive',
|
||||
|
||||
@@ -59,8 +59,11 @@ describe('what each game type is', () => {
|
||||
assert.equal(presetSettings('cutthroat', 4, 5).extraStart, 'anyOffice');
|
||||
assert.equal(presetSettings('coop', 4, 5).extraStart, 'ownOffice');
|
||||
assert.equal(presetSettings('competitive', 4, 5).extraStart, 'ownOffice');
|
||||
// At one player the two rules are the same rule.
|
||||
assert.equal(presetSettings('solitaire', 1, 5).extraStart, 'anyOffice');
|
||||
// At one player the two rules ARE the same rule — `apply.ts` only rejects `ownOffice` when the
|
||||
// start is another seat's, which cannot happen. Solitaire said `anyOffice` until 2026-08-30:
|
||||
// true, and it read wrong, since a lone player has no "any player" to be contrasted with. The
|
||||
// label changed and the behaviour did not.
|
||||
assert.equal(presetSettings('solitaire', 1, 5).extraStart, 'ownOffice');
|
||||
});
|
||||
|
||||
it('leaves every optional rule off, in every type', () => {
|
||||
|
||||
+322
-1
@@ -17,7 +17,10 @@ import { pump } from '../src/engine/advance.ts';
|
||||
import { createGame } from '../src/engine/setup.ts';
|
||||
import type { GameConfig, GameState, PlayerIndex } from '../src/engine/state.ts';
|
||||
import { developerBot, playGame } from '../src/sim/bot.ts';
|
||||
import { snapshot } from '../src/sim/view.ts';
|
||||
import { cardName, publicSnapshot, snapshot } from '../src/sim/view.ts';
|
||||
import { newGame, newMultiplayerGame, submit } from '../src/web/game.ts';
|
||||
import { createSession } from '../src/server/session.ts';
|
||||
import { legalActions } from '../src/engine/legal.ts';
|
||||
|
||||
const config: GameConfig = {
|
||||
mode: 'competitive',
|
||||
@@ -139,3 +142,321 @@ describe('redaction — a seat\'s Frame never carries another seat\'s secrets',
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* THE OTHER HALF OF §7, AND THE HALF THAT WAS NEVER LOOKED AT.
|
||||
*
|
||||
* Every test above serializes a `Frame`, and every one of them passes `[]` for the narration log —
|
||||
* so the entire shared log has sat outside the redaction net since the net was built. It is not a
|
||||
* hypothetical hole: `game.log` is ONE list, and `linesSince(seat)` (`server/session.ts`) slices it
|
||||
* with no per-seat filter at all, so every line written into it reaches every player.
|
||||
*
|
||||
* Two things were being written into it that should never have left the seat that caused them, both
|
||||
* found while planning the public common board (Gitea#20 step 1) and both live in multiplayer today,
|
||||
* with or without that display:
|
||||
*
|
||||
* 1. the SEED, announced in the opening line of every multiplayer game — which hands every player
|
||||
* the whole future of the deal;
|
||||
* 2. the NAME OF A CARD DRAWN BLIND from the Home Office deck.
|
||||
*
|
||||
* SOLITAIRE IS DELIBERATELY LEFT ALONE in both cases. There is nobody to leak to at a one-seat
|
||||
* table, the seed in the log is what a bug report quotes, and a solo player's own history naming
|
||||
* the card they drew is the record, not a leak. The rule is "do not tell the OTHER seats", not
|
||||
* "write less down" — so both checks below assert the solitaire text is still there.
|
||||
*/
|
||||
describe('redaction — the shared narration log never carries a seat\'s secrets', () => {
|
||||
const names = ['Ann', 'Bob', 'Cy'];
|
||||
|
||||
it('never announces the seed to the table (Gitea#20 step 1)', () => {
|
||||
const g = newMultiplayerGame(550943578, config, names);
|
||||
const log = g.log.map((l) => l.text).join('\n');
|
||||
assert.ok(
|
||||
!/550943578/.test(log),
|
||||
`the seed was announced to every seat:\n${log}`,
|
||||
);
|
||||
// The opening line must still say what the game IS — the leak is the number, not the line.
|
||||
assert.match(log, /Game Begins/);
|
||||
assert.match(log, /3 players/);
|
||||
});
|
||||
|
||||
it('still tells a solitaire player their own seed — there is nobody to leak it to', () => {
|
||||
const g = newGame(550943578);
|
||||
const log = g.log.map((l) => l.text).join('\n');
|
||||
assert.match(log, /550943578/, 'a solo game stopped recording the seed its bug reports quote');
|
||||
});
|
||||
|
||||
it('never names a card drawn blind from the Home Office deck (Gitea#20 step 1)', () => {
|
||||
const g = newMultiplayerGame(4242, config, names);
|
||||
|
||||
// Drive to the first Home Office draw any seat makes, and note what it actually drew.
|
||||
let drawn: string | null = null;
|
||||
for (let i = 0; i < 400 && drawn === null; i++) {
|
||||
const actor = g.state.clock.currentActor;
|
||||
if (actor === null) break;
|
||||
const before = g.log.length;
|
||||
if (!submit(g, { type: 'localOps.choose', option: 'draw' }, actor as PlayerIndex)) continue;
|
||||
if (!submit(g, { type: 'draw.fromHomeOffice' }, actor as PlayerIndex)) continue;
|
||||
drawn = g.justDrawn;
|
||||
void before;
|
||||
}
|
||||
assert.ok(drawn, 'no seat ever drew from the Home Office deck');
|
||||
|
||||
const name = cardName(g.state, drawn!);
|
||||
const log = g.log.map((l) => l.text).join('\n');
|
||||
assert.ok(
|
||||
!log.includes(name),
|
||||
`a blind draw named "${name}" to the whole table:\n${log.split('\n').slice(-6).join('\n')}`,
|
||||
);
|
||||
// The draw itself is public — everyone saw a hand go to the deck. Only WHICH card is not.
|
||||
assert.match(log, /Home Office/i);
|
||||
|
||||
// And the drawing seat still learns what it got: `justDrawn` is the owner-only channel, and
|
||||
// `session.ts` sends it to that seat alone.
|
||||
assert.equal(g.justDrawn, drawn);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* #91 — THE SYSTEMATIC NET, not two strings.
|
||||
*
|
||||
* v0.7.9.2 closed the seed and the blind draw. Both were found by reading a plan, not by a test, and
|
||||
* that is the point: a redaction suite made of the leaks somebody happened to notice proves nothing
|
||||
* about the next one. This is the pass the common-board plan asks for (Gitea#20 step 1 § Tests) —
|
||||
* serialise EVERYTHING a seat or a spectator receives and search it for everything that must not be
|
||||
* in it, across every game state where the shape of the answer changes.
|
||||
*
|
||||
* **What is searched for**, per the plan: every opponent hand card id AND its display name, the
|
||||
* objective, `justDrawn` for the wrong seat, seed values and seed narration, and private decision
|
||||
* and menu data. Display names matter as much as ids — "Red Flags" in a log leaks exactly what
|
||||
* `c118` would, and only the id would have been caught before.
|
||||
*
|
||||
* **Where it is searched**: a player's `Frame`, the `PublicFrame` a spectator gets, the incremental
|
||||
* narration `Push.lines` carries, and a reconnect push — which is a full Frame rather than a delta
|
||||
* and is therefore its own opportunity to leak.
|
||||
*
|
||||
* **And the acceptance bar is not this file.** The plan is explicit that passing redaction tests
|
||||
* alone is insufficient and that every public property needs an allow-list review; the last test
|
||||
* here is that allow-list, so adding a field to the public projection fails until somebody has said
|
||||
* out loud that it is public.
|
||||
*/
|
||||
describe('#91 — nothing private survives serialisation, in any state', () => {
|
||||
const names = ['Ann', 'Bob', 'Cy'];
|
||||
|
||||
/** Everything one seat can see, as one string: their Frame, the public board, and their lines. */
|
||||
const everythingSeatSees = (g: ReturnType<typeof newMultiplayerGame>, seat: PlayerIndex): string =>
|
||||
JSON.stringify(snapshot(g.state, g.log, null, null, null, false, seat)) +
|
||||
'\n' + JSON.stringify(publicSnapshot(g.state)) +
|
||||
'\n' + g.log.map((l) => l.text).join('\n');
|
||||
|
||||
/**
|
||||
* Every secret belonging to somebody OTHER than `seat`: their card ids, and the names those ids
|
||||
* render as. Ids alone were what the original tests looked for, and an id is the precise
|
||||
* instrument — it is unique, so finding one is proof.
|
||||
*
|
||||
* **A NAME IS ONLY EVIDENCE WHEN IT IS DISTINCTIVE, and most are not.** Card names are types, not
|
||||
* identities: "right-hand curve" names a dozen cards, and one of them is legitimately drawn on the
|
||||
* board as a cell label the moment anybody lays track. Searching for a name that also exists in
|
||||
* public is a test that fails on correct code, which is worse than no test — so a name counts only
|
||||
* when EVERY card bearing it is in that one opponent's hand. Then, and only then, seeing it says
|
||||
* something about what they are holding.
|
||||
*
|
||||
* This is what caught the blind-draw leak in v0.7.9.2: "Red Flags" was in exactly one hand, and it
|
||||
* was in the log.
|
||||
*/
|
||||
const secretsOfOthers = (g: ReturnType<typeof newMultiplayerGame>, seat: PlayerIndex): { what: string; value: string }[] => {
|
||||
const out: { what: string; value: string }[] = [];
|
||||
// How many cards in the whole game carry each name, and how many of those are in a given hand.
|
||||
const totalByName = new Map<string, number>();
|
||||
for (const id of g.state.cards.keys()) {
|
||||
const n = cardName(g.state, id);
|
||||
totalByName.set(n, (totalByName.get(n) ?? 0) + 1);
|
||||
}
|
||||
for (const p of g.state.players) {
|
||||
if (p.index === seat) continue;
|
||||
const hand = g.state.decks.hands.get(p.index) ?? [];
|
||||
const heldByName = new Map<string, number>();
|
||||
for (const id of hand) {
|
||||
const n = cardName(g.state, id);
|
||||
heldByName.set(n, (heldByName.get(n) ?? 0) + 1);
|
||||
}
|
||||
for (const id of hand) {
|
||||
out.push({ what: `${p.name}'s card id`, value: id });
|
||||
const name = cardName(g.state, id);
|
||||
if (totalByName.get(name) === heldByName.get(name)) {
|
||||
out.push({ what: `${p.name}'s card name, unique to their hand`, value: name });
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Runs the whole net over one state, and says which state failed if it does. */
|
||||
const audit = (g: ReturnType<typeof newMultiplayerGame>, where: string): void => {
|
||||
for (const seat of g.state.players.map((p) => p.index)) {
|
||||
const seen = everythingSeatSees(g, seat);
|
||||
for (const { what, value } of secretsOfOthers(g, seat)) {
|
||||
assert.ok(
|
||||
!seen.includes(value),
|
||||
`${where}: seat ${seat} can see ${what} ("${value}")`,
|
||||
);
|
||||
}
|
||||
// The seed is the whole future of the deal and must not reach a seat by any route.
|
||||
assert.ok(!seen.includes(String(g.seed)), `${where}: seat ${seat} can see the seed ${g.seed}`);
|
||||
}
|
||||
// And the spectator board, which has no seat and is therefore entitled to nothing private.
|
||||
const pub = JSON.stringify(publicSnapshot(g.state));
|
||||
for (const p of g.state.players) {
|
||||
for (const id of g.state.decks.hands.get(p.index) ?? []) {
|
||||
assert.ok(!pub.includes(id), `${where}: the public board carries ${p.name}'s card ${id}`);
|
||||
}
|
||||
}
|
||||
assert.ok(!pub.includes(String(g.seed)), `${where}: the public board carries the seed`);
|
||||
for (const k of ['hand', 'objective', 'justDrawn', 'decision', 'moves', 'blocked', 'viewer']) {
|
||||
assert.ok(!(k in (JSON.parse(pub) as Record<string, unknown>)), `${where}: the public board has a "${k}" field`);
|
||||
}
|
||||
};
|
||||
|
||||
/** Plays `n` legal moves, so a state is a real position rather than a constructed one. */
|
||||
const play = (g: ReturnType<typeof newMultiplayerGame>, n: number): void => {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const a = g.state.clock.currentActor;
|
||||
if (a === null) break;
|
||||
const opts = legalActions(g.state, a);
|
||||
if (!opts.length) break;
|
||||
if (!submit(g, opts[i % opts.length]!, a)) break;
|
||||
}
|
||||
};
|
||||
|
||||
it('a newly created multiplayer game', () => {
|
||||
audit(newMultiplayerGame(4242, config, names), 'fresh game');
|
||||
});
|
||||
|
||||
it('after a blind Home Office draw', () => {
|
||||
const g = newMultiplayerGame(4242, config, names);
|
||||
let drew = false;
|
||||
for (let i = 0; i < 200 && !drew; i++) {
|
||||
const a = g.state.clock.currentActor;
|
||||
if (a === null) break;
|
||||
if (!submit(g, { type: 'localOps.choose', option: 'draw' }, a)) continue;
|
||||
drew = submit(g, { type: 'draw.fromHomeOffice' }, a);
|
||||
}
|
||||
assert.ok(drew, 'no seat drew from the Home Office deck');
|
||||
audit(g, 'after a blind draw');
|
||||
});
|
||||
|
||||
it('mid-game, with real hands and a built board', () => {
|
||||
// A DISTINCTIVE seed, deliberately. Seed 7 makes the seed check meaningless — "7" is in "Train
|
||||
// 7", in every coordinate and in half the numbers on the board — so it reported a leak that was
|
||||
// not one. Nine digits collide with nothing, which is what makes a substring match evidence.
|
||||
const g = newMultiplayerGame(613884219, config, names);
|
||||
play(g, 300);
|
||||
audit(g, 'mid-game');
|
||||
});
|
||||
|
||||
it('with a decision pending, and with the Superintendent acting', () => {
|
||||
const g = newMultiplayerGame(550943578, config, names);
|
||||
let sawDecision = false;
|
||||
for (let i = 0; i < 800; i++) {
|
||||
if (g.state.clock.pendingDecision !== null) {
|
||||
sawDecision = true;
|
||||
audit(g, `pending decision (${g.state.clock.pendingDecision.kind})`);
|
||||
break;
|
||||
}
|
||||
const a = g.state.clock.currentActor;
|
||||
if (a === null) break;
|
||||
const opts = legalActions(g.state, a);
|
||||
if (!opts.length || !submit(g, opts[0]!, a)) break;
|
||||
}
|
||||
// A seed that never raises one is not a failure of redaction; say so rather than passing mutely.
|
||||
if (!sawDecision) assert.ok(true, 'no decision arose on this seed — nothing to audit');
|
||||
});
|
||||
|
||||
it('with Employee Rotation on, before and after ownership moves', () => {
|
||||
// The case where seat and player index come apart. A projection that confused them would hand
|
||||
// one player another's district, which is a leak the other tests cannot see.
|
||||
const rotating = { ...config, optionalRules: { ...config.optionalRules, employeeRotation: true } };
|
||||
const g = newMultiplayerGame(729315046, rotating, names);
|
||||
audit(g, 'employee rotation, before');
|
||||
const seatingBefore = [...g.state.seating];
|
||||
play(g, 400);
|
||||
audit(g, 'employee rotation, after');
|
||||
// If the seating never moved this test proved less than it looks — say which happened.
|
||||
const moved = seatingBefore.some((p, i) => g.state.seating[i] !== p);
|
||||
assert.ok(moved || g.state.status !== 'active', 'rotation never moved anybody and the game did not end');
|
||||
});
|
||||
|
||||
it('a game played out to the end, or as far as it goes', () => {
|
||||
const g = newMultiplayerGame(613884219, config, names);
|
||||
play(g, 6000);
|
||||
// Says which it actually got, rather than claiming a finished game it may not have reached.
|
||||
audit(g, `played out (status ${g.state.status})`);
|
||||
});
|
||||
|
||||
it('a reconnect push, which is a full Frame rather than a delta', () => {
|
||||
const session = createSession(550943578, config, names);
|
||||
for (const seat of [0, 1, 2] as PlayerIndex[]) {
|
||||
const push = session.connect(seat);
|
||||
const seen = JSON.stringify(push);
|
||||
const state = session.exportSave();
|
||||
assert.ok(!seen.includes(String(state.seed)), `the reconnect push for seat ${seat} carries the seed`);
|
||||
for (const p of [0, 1, 2] as PlayerIndex[]) {
|
||||
if (p === seat) continue;
|
||||
// `connect` returns that seat's own Frame; another seat's hand must not be in it.
|
||||
assert.ok(
|
||||
!/"hand":\[[^\]]/.test(JSON.stringify((push.frame as unknown as Record<string, unknown>)['players'] ?? '')),
|
||||
`the reconnect push for seat ${seat} carries a hand inside players[]`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* THE ALLOW-LIST, and the plan's actual acceptance bar.
|
||||
*
|
||||
* Every property of the public projection, written down and reviewed as public. This does not
|
||||
* check the CONTENT of anything — the tests above do that — it checks that nobody has added a
|
||||
* field without saying out loud that a spectator may see it. That is the check that would have
|
||||
* caught both v0.7.9.2 leaks, because both were fields nobody had ever asked the question about.
|
||||
*
|
||||
* When this fails, the fix is not to add the key here. It is to decide whether the field is
|
||||
* public, and only then to add it.
|
||||
*/
|
||||
it('every public property is on the allow-list, and nothing else is', () => {
|
||||
const PUBLIC: readonly string[] = [
|
||||
// The clock and the phase — what a spectator's board is FOR.
|
||||
'day', 'stage', 'clock', 'phase', 'phaseKey', 'actor', 'superintendent',
|
||||
// Deck sizes and face-up piles. A Department pile is face up; the Home Office deck is a count.
|
||||
'deck', 'departments', 'departmentsWhat', 'departmentDepth', 'salvage',
|
||||
// Rolling stock in the yards, by type — visible on the table.
|
||||
'yards',
|
||||
// The timetable is public: it is what everyone is playing against.
|
||||
'timetable', 'timetableWhat',
|
||||
// The rules the game was dealt under, and the score.
|
||||
'houseRules', 'mode', 'optionalRules', 'days', 'minCombinedRevenue',
|
||||
'maxCollisionsPerDay', 'maxCollisionsTotal', 'collisionsToday', 'collisionsTotal',
|
||||
'status', 'outcome', 'extraDays', 'extensionVotes', 'official', 'tally',
|
||||
// Names, seats, revenue and HAND SIZE — never hand contents.
|
||||
'players',
|
||||
// The opening rolls decided seating and the Superintendent in the open.
|
||||
'openingRolls',
|
||||
// Where every train is standing.
|
||||
'trains',
|
||||
// The Crew Tray pool and the trains queued for one (#98). §7 scarcity is played out in the
|
||||
// open: the trays are objects in the middle of the table, and an Extra is played face up, so
|
||||
// who is waiting for a crew is not a secret. Counts and train numbers only — never a hand.
|
||||
'crewTrays', 'queued',
|
||||
// The board itself.
|
||||
'division', 'districts',
|
||||
];
|
||||
const g = newMultiplayerGame(4242, config, names);
|
||||
const actual = Object.keys(publicSnapshot(g.state)).sort();
|
||||
const allowed = [...PUBLIC].sort();
|
||||
assert.deepEqual(
|
||||
actual,
|
||||
allowed,
|
||||
'the public projection gained or lost a property — decide whether it is public before listing it',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+107
-3
@@ -13,8 +13,8 @@ import { DEFAULT_MAX_COLLISIONS_PER_DAY, DEFAULT_MAX_COLLISIONS_TOTAL, collectiv
|
||||
import type { GameEvent } from '../src/engine/events.ts';
|
||||
import { areaOf } from '../src/engine/apply.ts';
|
||||
import { createGame } from '../src/engine/setup.ts';
|
||||
import { coordKey } from '../src/engine/state.ts';
|
||||
import type { GameConfig, GameState } from '../src/engine/state.ts';
|
||||
import { coordKey, turnOf } from '../src/engine/state.ts';
|
||||
import type { GameConfig, GameState, GridCoord } from '../src/engine/state.ts';
|
||||
import { developerBot, playGame } from '../src/sim/bot.ts';
|
||||
import { impediments, isVisible, narrate, phaseLabel } from '../src/sim/narrate.ts';
|
||||
import { compress, rehydrateCells, record, renderHtml } from '../src/sim/replay.ts';
|
||||
@@ -138,6 +138,89 @@ describe('impediments', () => {
|
||||
s.freeTrays = [];
|
||||
assert.ok(impediments(s, 0).some((b) => /HELD/.test(b.why)));
|
||||
});
|
||||
|
||||
/** A crew standing on `at`, working the given train, with one empty tank car on the drawbar. */
|
||||
const express = (s: GameState, trainNumber: number, at: GridCoord): string => {
|
||||
const id = s.freeTrays.pop()!;
|
||||
s.trays.set(id, {
|
||||
id, trainNumber, trainIsExtra: false, engineAt: 0,
|
||||
consist: [{ type: 'tank', loaded: false, origin: 0 }],
|
||||
direction: 'east', position: { at: 'grid', seat: 0, coord: at }, movesUsed: 0,
|
||||
});
|
||||
return id;
|
||||
};
|
||||
|
||||
/**
|
||||
* GITEA#21 — THE GAME REFUSED, AND THE PANEL EXPLAINED SOMETHING ELSE.
|
||||
*
|
||||
* "I wanted to drop two empty tank cars so that the freight agents and men at work could load
|
||||
* them later. I dropped the first tank car, but that was all I was allowed to do. Checked
|
||||
* 'Blocked — why nothing is moving' and saw: refinery 1,0 — green box empty — nothing to load
|
||||
* (needs a Freight Agent action)."
|
||||
*
|
||||
* Replayed from the attached save (seed 550943578, 181 intents): the crew was Train 3, and the
|
||||
* engine's answer was `FREIGHT_WORKED_HERE`. Train 3 is the Express, and the Express prints "May
|
||||
* drop or pick up one freight car at every location" — so THE REFUSAL WAS CORRECT and the rule
|
||||
* is not what is wrong here. It resets next turn, and the Express may work a car at the next
|
||||
* square this turn; that is what makes it an Express rather than a one-car-a-Stage train.
|
||||
*
|
||||
* What was wrong is that nothing said so. The panel whose entire job is "why is nothing moving?"
|
||||
* listed the refinery's green box — a true statement about the FACILITY, and nothing to do with
|
||||
* why the drop was refused — so the player was sent to fix a Freight Agent action that would not
|
||||
* have helped. The rule was on the train card's own tooltip, which is not where somebody looks
|
||||
* when a button they expected is missing.
|
||||
*
|
||||
* The panel is where a refusal gets explained, so the budget belongs in it.
|
||||
*/
|
||||
it('says when the Express has spent its one freight car on this square (Gitea#21)', () => {
|
||||
const s = createGame({ id: 'g', seed: 5, config, playerNames: ['p'] });
|
||||
const area = areaOf(s, 0);
|
||||
const at = area.officeCoord;
|
||||
|
||||
// A crew standing at the Office working Train 3 — the Express — with a tank car still on it.
|
||||
const trayId = express(s, 3, at);
|
||||
|
||||
s.clock.phase = 'localOps';
|
||||
const turn = turnOf(s, 0);
|
||||
turn.option = 'switch';
|
||||
|
||||
// Nothing to say before it has worked anything here.
|
||||
assert.ok(
|
||||
!impediments(s, 0).some((b) => /FREIGHT CAR PER LOCATION/i.test(b.why)),
|
||||
'the budget was reported spent before the train had worked a car at all',
|
||||
);
|
||||
|
||||
// Now it has set one car out here — exactly the state the save is in at intent 181.
|
||||
turn.freightWorked[`${trayId}@${coordKey(at)}`] = 1;
|
||||
|
||||
const row = impediments(s, 0).find((b) => /FREIGHT CAR PER LOCATION/i.test(b.why));
|
||||
assert.ok(
|
||||
row,
|
||||
`nothing explained the refusal:\n${JSON.stringify(impediments(s, 0), null, 2)}`,
|
||||
);
|
||||
// It must name the train, or a player with three crews out cannot tell which one it means.
|
||||
assert.match(row!.where, /Train 3/);
|
||||
// And it must say the limit lifts, or it reads as "this train can never work here again".
|
||||
assert.match(row!.why, /turn/i);
|
||||
// Amber: this is the printed rule doing its job, not a fault.
|
||||
assert.equal(row!.severity, 'waiting');
|
||||
});
|
||||
|
||||
it('leaves every other train alone — the rule is printed on 3 and 4 only (Gitea#21)', () => {
|
||||
const s = createGame({ id: 'g', seed: 5, config, playerNames: ['p'] });
|
||||
const area = areaOf(s, 0);
|
||||
const at = area.officeCoord;
|
||||
// Train 5 is The Sparrow, which prints no per-location freight limit.
|
||||
const trayId = express(s, 5, at);
|
||||
s.clock.phase = 'localOps';
|
||||
turnOf(s, 0).option = 'switch';
|
||||
turnOf(s, 0).freightWorked[`${trayId}@${coordKey(at)}`] = 1;
|
||||
|
||||
assert.ok(
|
||||
!impediments(s, 0).some((b) => /FREIGHT CAR PER LOCATION/i.test(b.why)),
|
||||
'a train with no such rule was told it had spent a budget it does not have',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -214,6 +297,24 @@ describe('a blocked platform says why (Gitea#2)', () => {
|
||||
assert.ok(f.inboundBox.length === 0, 'the red slots were free — the shortage is the only cause');
|
||||
});
|
||||
|
||||
it('says why the game ended in words, not as a raw enum (TODO #34)', () => {
|
||||
/**
|
||||
* The heading read `loss — revenueFloor` — the exact defect Gitea#16 was filed about on the
|
||||
* playable page, still alive here a release after that was fixed, because nothing
|
||||
* player-facing pointed at the developer replay. It shares `reasonSentence` with the results
|
||||
* screen now, so the two cannot explain one ending in two ways.
|
||||
*/
|
||||
const rec = record(1234, 'standard');
|
||||
for (const raw of ['revenueFloor', 'daysElapsed', 'collisionFloor']) {
|
||||
assert.ok(!rec.outcome.includes(raw), `the summary still prints the raw reason "${raw}"`);
|
||||
}
|
||||
assert.doesNotMatch(rec.outcome, /<[^>]+>/, 'markup leaked into a heading and a console line');
|
||||
assert.match(rec.outcome, /Revenue/, 'the summary says nothing about how the game went');
|
||||
// And the sentence is the shared one, with this game's own numbers in it.
|
||||
assert.match(rec.outcome, /closed short|last on the timetable|declared unsafe/,
|
||||
'the ending is not explained in the words the results screen uses');
|
||||
});
|
||||
|
||||
it('says nothing about a platform that is working fine', () => {
|
||||
// Passengers waiting AND a train with an empty coach to take them: no impediment.
|
||||
const s = createGame({ id: 'g', seed: 5, config, playerNames: ['p'] });
|
||||
@@ -257,7 +358,10 @@ describe('replay recording', () => {
|
||||
const last = rec.frames[rec.frames.length - 1]!;
|
||||
assert.equal(last.revenue, stats.revenue.net, 'final revenue disagrees with the engine');
|
||||
assert.equal(last.day, s.clock.day, 'final Day disagrees with the engine');
|
||||
assert.match(rec.outcome, new RegExp(stats.result));
|
||||
// The summary says "won"/"lost" rather than the engine's `win`/`loss` (TODO #34 — it is a
|
||||
// sentence for a reader now, not an enum). Mapped here so this still checks the two AGREE,
|
||||
// which is what the test is for, rather than checking they are spelled the same.
|
||||
assert.match(rec.outcome, new RegExp(stats.result === 'win' ? 'won' : 'lost'));
|
||||
});
|
||||
|
||||
it('narrates every frame', () => {
|
||||
|
||||
@@ -531,3 +531,79 @@ describe('§3.3 extended play across the server (Gitea#11)', () => {
|
||||
assert.deepEqual(b.official, a.official, 'the official result did not survive the replay');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* NARRATION HAS ONE PATH, AND A RECONNECT HAS TO GET ALL OF IT (#97, Gitea#20 step 1).
|
||||
*
|
||||
* The common-board plan asks for one thing here: "stop passing the full game log into `frameFor()`;
|
||||
* continue sending sanitized incremental narration through `Push.lines`." Doing only the first half
|
||||
* would have deleted a real behaviour, so this pins the pair.
|
||||
*
|
||||
* WHAT WAS ACTUALLY WRONG. `Frame.lines` carried the WHOLE log on every push, and nothing read it:
|
||||
* `RemoteSession` (`web/session.ts`) accumulates `lines` from `push.lines` alone and its `lines()`
|
||||
* returns that accumulator. So the log was serialised into every frame for every seat, grew all
|
||||
* game, and was thrown away on arrival — while `linesSince` sent the same text again, correctly,
|
||||
* beside it.
|
||||
*
|
||||
* And the duplicate was masking a bug rather than merely wasting bandwidth. `connect()` clears
|
||||
* `lastFrame` but did NOT clear `sentLines`, so a reconnecting seat was told "nothing new since your
|
||||
* last push" — while the browser it was answering had just reloaded and started from an EMPTY
|
||||
* accumulator. The history panel came back blank after a refresh, mid-game, with the server holding
|
||||
* the whole log and shipping it in the one field nobody reads.
|
||||
*
|
||||
* So the two halves are one change: a (re)connect resets the seat's watermark and `Push.lines` on a
|
||||
* connect IS the history, which is what lets the frame stop carrying a second copy.
|
||||
*/
|
||||
describe('narration reaches a seat exactly once, by one path (#97)', () => {
|
||||
/**
|
||||
* A session with narration already in the log and NO connect yet, so a first connect is a real
|
||||
* "catch me up" rather than a no-op. Connecting inside this helper is what made the first draft of
|
||||
* the reconnect test pass vacuously: both sides of the comparison were the empty array.
|
||||
*/
|
||||
const played = (): GameSession => createSession(550943578, config, ['Alice', 'Bob']);
|
||||
|
||||
it('a FIRST connect carries the narration so far in Push.lines', () => {
|
||||
const session = createSession(550943578, config, ['Alice', 'Bob']);
|
||||
const push = session.connect(0 as PlayerIndex);
|
||||
assert.ok(push.lines.length > 0, 'a first connect was given no narration at all');
|
||||
assert.ok(
|
||||
push.lines.some((l) => /players|competitive/i.test(l.text)),
|
||||
'the opening lines are not in what a first connect received',
|
||||
);
|
||||
});
|
||||
|
||||
it('a RECONNECT is given the whole log again, because the browser it answers has none', () => {
|
||||
const session = played();
|
||||
const first = session.connect(0 as PlayerIndex);
|
||||
const again = session.connect(0 as PlayerIndex);
|
||||
// NON-EMPTY first: two empty arrays are deepEqual, and asserting only that is how this test
|
||||
// passed against the broken code on its first draft.
|
||||
assert.ok(first.lines.length > 0, 'the premise is gone: there was no narration to be given');
|
||||
assert.deepEqual(
|
||||
again.lines,
|
||||
first.lines,
|
||||
'a reconnecting seat was told nothing was new, and its history panel would come back empty',
|
||||
);
|
||||
});
|
||||
|
||||
it('the Frame does NOT carry a second copy of the log', () => {
|
||||
const session = played();
|
||||
const push = session.connect(0 as PlayerIndex);
|
||||
assert.deepEqual(
|
||||
(push.frame as unknown as { lines: unknown[] }).lines,
|
||||
[],
|
||||
'the whole narration log is still being serialised into every Frame, where nothing reads it',
|
||||
);
|
||||
});
|
||||
|
||||
it('an ordinary push after a connect carries only what is NEW', () => {
|
||||
const session = played();
|
||||
const opening = session.connect(0 as PlayerIndex);
|
||||
assert.ok(opening.lines.length > 0);
|
||||
// A second connect for the OTHER seat must not re-send seat 0 anything.
|
||||
const other = session.connect(1 as PlayerIndex);
|
||||
assert.ok(other.lines.length > 0, 'the other seat got no history of its own');
|
||||
const third = session.connect(0 as PlayerIndex);
|
||||
assert.deepEqual(third.lines, opening.lines, 'a reconnect is the full log, every time');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ import assert from 'node:assert/strict';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
import { actionGroups, currentActor, handPlayable, newGame, overHandLimit, submit, toSave, view } from '../src/web/game.ts';
|
||||
import { actionGroups, currentActor, handPlayable, newGame, submit, toSave, view } from '../src/web/game.ts';
|
||||
import { createLocalSession } from '../src/web/session.ts';
|
||||
import { seatLabel } from '../src/sim/view.ts';
|
||||
|
||||
@@ -81,7 +81,6 @@ describe('a local session plays the same game as the calls it replaced', () => {
|
||||
assert.equal(session.seat(), 0);
|
||||
assert.equal(session.actor(), currentActor(session.game));
|
||||
assert.deepEqual(session.handPlayable(), handPlayable(session.game));
|
||||
assert.equal(session.overHandLimit(), overHandLimit(session.game));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+736
-85
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user