Compare commits

..
10 Commits
Author SHA1 Message Date
Jesse.MarkowitzandClaude Opus 5 9735468d25 v0.4.9g — a caboose is not a load, a Day that says it ended, and a train you may throw away
The v0.7.1 bugfix set ported to the playtest line: Gitea#8, #10, #9 and #2. Reasoning, and what
differs from main, in CHANGELOG.md.

- Gitea#8: X22 Pee-Dee refused every caboose, including the one it was made up with. A caboose
  carries the crew, not freight, so it is never a load.
- Gitea#10: a dialog when the Day rolls over, carrying the standings, the Days left and your Revenue
  against the target with the pace. Suppressed on the first frame, on Undo stepping back across a
  rollover, and on the Day the game ends.
- Gitea#9, superseding Gitea#6 from v0.4.9f: a Timetabled train may be discarded, an Extra may not.
  This line takes the plain rule — main has it as a New Game setting.
- Gitea#2: the shortage stays, by Jesse's ruling. A blocked platform now gives its reason instead of
  simply having no button.

Three things are written for this line rather than ported: the Timetabled discard has no setting and
no URL parameter, the Day-end dialog reads f.objective (this line's per-player target) where main
reads its combined victory dials, and Frame gained the viewer index the dialog needs to mark your
row. 636 tests pass; no published replay was retired.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FLnYR4XtXQNamYJXGYT8oC
2026-08-25 10:47:10 -04:00
Jesse.Markowitz e255076b5c v0.4.9f — an Extra starts where you put it, a train card is never discarded
The 0.6.2 change, ported to the playtest line. Three from the v0.4.9e gameplay-testing round —
Gitea#4 extras did not start where the player said, #6 train cards could be discarded, #7 four
train cards had the wrong coach counts — plus two bugs found underneath #4. Gitea#2 is diagnosed
but NOT fixed; it needs a ruling, and the reasoning is in TODO.md.

GITEA#4 — AN EXTRA STARTS WHERE THE PLAYER PUTS IT. Both Division Points are offered now, and the
START decides the direction rather than the number: an odd westbound Extra placed at the WEST end
would otherwise leave the Division on its first move having crossed nothing and be paid for the
run. At an Interchange or a Control Point the player picks the direction. The Interchange start is
a YARD, off the running line, which is what makes the Superintendent clause work — placing an
Extra there can never force a collision, a guaranteed one holds it for another Stage, and a
potential one is the Superintendent's to rule on, which are §8.1's two existing answers. Where an
Extra may start is a new setting in the New Game dialog, defaulting to what the engine already did
so this build does not change under its testers mid-line.

FOUND UNDERNEATH IT, both already shipping: an Extra started away from a Division Point could
never be given a consist and ran empty, so the Control Point start has been broken since it was
added; and collide left destroyed trains' transits on the Mainline card, permanently poisoning
that card for every later train.

THE MAINLINE CARDS ARE DEALT FROM THE PRINTED DECK NOW, without replacement. They were drawn from
the nine types with replacement, so a Division could hold two Interchanges — and "an Extra may
start at the Interchange if one is on the board" only reads as a rule if the board holds at most
one. This re-deals every seed, so both published replays were retired and re-recorded.

GITEA#6 — A TRAIN CARD IS NEVER DISCARDED, Timetabled and Extra alike. No forcing mechanism was
needed: nothing discardable plus a hand over the limit leaves exactly one legal way to end the
turn, and playing a train is unconditionally legal, so a hand of four cannot trap anyone. The hand
panel says so on the train, and the blocked end-turn button changes its wording.

GITEA#7 — COACH COUNTS. 1/2 Crack Limited 3 -> 2, 5/6 The Sparrow 2 -> 3.

WHAT DIFFERS FROM THE MAIN LINE. The car-placement round rotation test that accompanies #7 there
arrived with the 0.6 multiplayer work and does not exist here, so there was nothing for the
coach-count change to follow. src/web/main.ts and test/web.test.ts needed hand-resolution: this
line's New Game dialog has neither the mode radios nor the victory dials, so only the Extra-start
parts were taken. The content.ts comment pass came across whole; main's TODO documentation item
did not, since this line keeps its own TODO.

623 tests pass, tsc clean, site builds.
2026-08-22 21:42:27 -04:00
Jesse.MarkowitzandClaude Opus 5 7c35e002af v0.4.9e — five of six playtest bugs: one button per train, and a load that has to go somewhere
Gameplay testing on 0.4.9d returned six reports. Five are fixed; the sixth could not be
reproduced and is written up in TODO.md with the two questions that would pin it down.

TWO TRAINS AT ONE PLATFORM ANSWERED TO ONE BUTTON. `porter.board` and `porter.detrain`
carried no tray, so there was one button per platform however many trains stood at it and
the reducer filled the first empty coach on the A/D tracks. `check` and the reducer were not
even asking the same question: `check` skipped a train whose card refuses passenger work and
the reducer did not. Both intents now carry an optional `trayId`, one function resolves the
train and the coach for check/execute/reduce alike, `legal.ts` offers one candidate per train,
and the label names it.

A LOAD COULD BE MADE AND BROKEN WITHOUT GOING ANYWHERE. A Freight House could unload the
boxcar it had just loaded; a platform could detrain the passengers it had just boarded. Full
Revenue at both ends for a movement that never happened. Jesse's rule: a load made anywhere in
an Office Area may not be broken anywhere in that Office Area, ever — it has to be carried to
another district. The load carries the seat that made it (`RollingStock.origin`), stripped by
`pooled` at every yard push. Measured at -0.60 +/- 0.10 Revenue a game (t = -6.1) over 400
paired deals: 78 worse, 3 better, 319 unchanged — free Revenue coming off the board, not a nerf.

THE GROCER'S WAREHOUSE SHIPPED AND THE REFINERY RECEIVED. Both were `flow: 'both'` on the
reading that "Freight House" was a collective term for exactly those two, and therefore what
§9.3 described. The engine has dealt a Freight House CARD since before v0.4.9, so §9.3 names
it and the argument goes. The card set agrees: all three Refinery modifiers grant +1 outbound.
Refinery outbound-only, Grocer's inbound-only, Freight House the one two-way industry — which
leaves exactly the one same-district pairing the rule above refuses.

NOT REPRODUCED: cars left behind when backing up over them. Five layouts tried, including cars
spotted at an industry; every one couples the lot. Three are pinned in `apply.test.ts`. One way
to create such cars was closed anyway — `flyingSwitch` wrote its cut past `carsOn`.

Both published replays that had gone dead were re-recorded; a rules change retires a save, and
`harness.test.ts` is what catches it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011nbvwWMef8CuEP6t5cgkTv
2026-08-21 23:55:08 -04:00
Jesse f9c4d9fa92 v0.4.9d — three playtest bugs: a train that looked gone, an unload that ignored the pick, a hang that wasn't one
Patched directly onto 0.4.9a rather than the in-progress 0.5.0 line.

A switching train vanished from the board the moment it left the Office. `selectedTrain` in
`officeSvg` (board-svg.ts), which gates whether a card draws a train's crew badge, was only ever
assigned inside the `cell.adTracks !== null` branch — true for the Office card alone. A train
standing anywhere else, which is everywhere it stands while actually being switched, drew no badge
at all. Game state was never affected; confirmed against the reported save with the engine directly.
Fix hoists the assignment out of the guard so it runs for any card with a train on it.

Unloading always took the westmost car, whichever one was picked. `laborer.beginUnload` carried the
player's chosen `carIndex`, and `check()` validated that specific car, but the `unloadBegan` event
it produced carried only the car's type — the reducer that performs the swap re-derived the target
with `industryTrack.cars.findIndex(c => c.loaded)`, which always answers the first loaded car in
track order regardless of what was requested. Fix adds `carIndex` to the event and uses it directly.

A legal decision could render with zero buttons, which looked exactly like a hang. The "where does
this Extra start" decision is titled by `trainCardTitle`, beginning "Making up Extra X22…" — the
same prefix `renderActions()` stripped from the action list on the assumption it only ever belonged
to the separate yard-chip car-placement panel. With no tray yet being filled, that panel is null, so
nothing rendered the Extra's decision either: a legal, correctly-computed option with no button
anywhere on the page. Replaying the reported save found no engine deadlock at any step — the engine
always had a move. Fix matches the exact title of the one group the yard-chip panel covers instead
of a title-prefix regex.

New tests for all three: a train parked on an ordinary facility card must draw its crew badge; three
differently-typed loaded cars, unloading index 2, must leave indices 0 and 1 alone; the existing
softlock regression test now mirrors the real render filter instead of only the raw menu, plus a
deterministic test for the exact reported scenario. 590 tests, 0 failures.
2026-08-20 23:26:39 -04:00
Jesse 3a5a909ec0 v0.4.9a — box art opens full size, a third splash card, and a scoped footer claim
Splash page only: the box art thumbnail opens a full-size lightbox on click, a
new "Play multiplayer" (coming soon) card balances the bottom row to three
cards, and the footer's "runs entirely in your browser" claim is now scoped
to solitaire.
2026-08-20 07:40:58 -04:00
JesseandClaude Sonnet 5 859817d173 v0.4.9 — X,Y coordinates, no-switching can still clear the mainline, Q3 corrected, a clearance bug, three sounds, and the box art
A playtest review of seed 58228926 (day 6), plus one long-standing display complaint and the
first real audio beyond a placeholder.

- Coordinate labels read X,Y everywhere shown to a player, not the internal Y,X storage order.
  Display-only.
- "No switching" now means may not add or drop cars, not "never touch it" — these trains can
  still be moved onto Secondary Track to clear the mainline.
- Q3 corrected: Expedite governs WHERE a train may be left standing, not WHEN it leaves. The
  forced same-Stage departure is gone; a new fault costs 1 Revenue if an expedited train is left
  off the station when a Mainline Phase begins. Resolves "3/4 Express prints a rule it can never
  use" as a side effect.
- evaluateClearance now checks every occupant on a Mainline card before offering a judgment
  call, instead of returning on whichever it found first — found while explaining a playtest
  report, fixed with a regression test.
- Three new synthesised sounds: arrive, depart, crash.
- The splash page shows the box art.

Full detail, measurements and reasoning in CHANGELOG.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FvU99NEakShRMg3nN3fHAZ
2026-08-19 23:51:35 -04:00
JesseandClaude Sonnet 5 37b1e5b969 the Roster Pass: every train at the Office visible
Builds "The Roster Pass" / "Two Trains, One Card" (station display for
multiple trains at one Office). The Office is the one square where
more than one train may legally stand at once (one per A/D track), and
CellView.train had room for exactly one — a second train at a busy
Station was counted in the old A/D pips and never drawn.

CellView.train -> CellView.trains: TrainView[], seat-filtered and
collecting every match rather than the first (fixes a latent
cross-district leak in the process: trainOnCard never checked seat).
The A/D pips are replaced with one roster chip per A/D track, always,
free or occupied; clicking a chip sets selectedCrew, wiring the board
and the action panel to the same value.

standingWest moves from CrewTray to TrackCard: two trays sharing one
Office card need one shared split, not one each, and there is no such
thing as "west of one particular A/D track". No save migration — Save
replays through the engine — and a stale value on an emptied card is
inert because nothing reads a split with no train standing there.

The Division map's Office cell is now sized by A/D capacity rather
than occupancy, so it holds still as trains arrive and leave; chips
lay into fixed slots instead of centre-spreading onto the Limits cards
either side.

584 tests, 0 failures. Verified end-to-end against the built app and a
direct render of a 4-train Terminal (screenshotted).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAt2YCXgd5qCjBcF2x34aK
2026-08-19 17:32:17 -04:00
JesseandClaude Sonnet 5 fbaa3d4147 switching paths: two routes to the same square
Builds docs/plans/switching-paths.md. A passing loop can offer two legal
routes between the same two squares, coupling different cars — the engine
only ever found one, an artifact of search order (Reported by Jesse, undo
379). exploreMoves now enumerates every simple route (per-path visited set,
capped at 4000 frontier nodes) and dedupes on outcome — destination, entry
side, and origin-tagged cars — rather than on reaching the square at all.

switch.move gains an optional `via: GridCoord` naming one intermediate
square on the chosen route; absent, it resolves exactly as before, so
every existing save and bot decision replays identically (575/575, then
579/579 with the new tests). Threaded through the label, the action-list
dedupe, the hover highlight (data-route), and the history (trayMoved.via).

Ruling recorded as Gap 14 in docs/rules/open-questions.md: the player may
choose the path; §A.4's "may not go around" a car does not reach a
different track the player declined to enter.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAt2YCXgd5qCjBcF2x34aK
2026-08-19 16:52:10 -04:00
JesseandClaude Opus 5 7932bb6ccf plan: switching paths — two routes to the same square
Planning only; no source files touched. The BFS visited set in exploreMoves
keys on (coord, entry), so two legal routes that rejoin through the same port
collapse to whichever is shorter — silently discarding the option that couples
cars on the way.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YQAJ4dND7enLj54eLyiF2C
2026-08-19 13:39:53 -04:00
JesseandClaude Opus 5 461c4d9bac v0.4.8 — the Limits bound the whole district, the nine spots really are nine, and an action points at its square
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YQAJ4dND7enLj54eLyiF2C
2026-08-19 13:38:06 -04:00
57 changed files with 9804 additions and 6474 deletions
+6 -1
View File
@@ -8,7 +8,12 @@ Thumbs.db
*.swp
# Dependencies / build output
node_modules/
#
# NO TRAILING SLASH on node_modules, deliberately. `node_modules/` matches a directory and not a
# SYMLINK of that name — so one pointing at a shared install was committed in v0.4.7, and because it
# pointed at a path that does not exist, a fresh checkout had no TypeScript: `npm run typecheck` said
# "tsc: not found" and 20 tests failed for a reason that had nothing to do with the code.
node_modules
dist/
build/
target/
+711
View File
@@ -19,6 +19,717 @@ page as `v0.1.0 · <sha> · <date>`, so what is deployed can always be identifie
---
## 0.4.9g — 2026-08-25
Four more off the Gitea tracker, all of them things a player saw at the board: **#8** a per-diem train
that could not couple a caboose, **#10** no way to tell when the Day turned over, **#9** a ruling that
lets a Timetabled train be thrown away — which supersedes **#6**, shipped three days ago in 0.4.9f —
and **#2**, which turned out not to be an engine bug at all, so what is fixed there is that the game
now says why.
The same four ship as **0.7.1** on the main line. The full reasoning for every item is in that line's
CHANGELOG; this entry records what reached the playtest build and what differs.
### Gitea#8 — a caboose is not a load
X22 Pee-Dee, whose card reads "may only pick up MTs", refused every caboose — including the one it was
made up with, so setting it out at the end of a sweep stranded the train. All six cabooses are minted
`loaded: true`, because §2.2's "coloured is loaded, white is empty" doubles as a PIECE COUNT in the
supply table and there is no white caboose to make a train up from. Exactly one read of the flag took
that literally. A caboose carries the crew, not freight, so it is never a load; the restriction itself
is untouched, and a loaded car alongside the caboose still refuses. The card now says so
("A caboose is not a load"), because a player reading "EMPTIES ONLY" cannot know which reading the
game took.
### Gitea#10 — a dialog when the Day rolls over
"Hard to keep track of time." Nothing on screen was wrong — the clock, the turn chart and the
timetable all said which Day it was — but a Day turns over inside the phases that run themselves, so
it passes between one click and the next, and the phase banner that announces it is gone in 2.6
seconds. A modal stops and waits, which is the whole request. It carries the Day that ended, the
standings in Revenue order, the Days left to run, and your Revenue against the target with the pace.
Suppressed on the first frame (arriving in a game already on Day 3 is not Day 2 ending), on Undo
stepping back across a rollover, and on the Day the game ends — the outcome panel is the thing to
read then.
### Gitea#9 — a Timetabled train may be thrown away
**This supersedes Gitea#6 above, which shipped in 0.4.9f three days ago.** Jesse: "Timetabled trains
are at the choice of the player — they can either play or discard. If someone else wants to pick it
up, they are more than able to. The reason: I don't want, if you decide to play a game longer than
five days, to decide that maybe there are too many trains, the stations are jammed, and the railroad
doesn't need any more. You can toss it. Someone else might disagree and pick it up."
An **Extra** is still never discardable: it never joins the timetable, so it can never be what jams
it. The second half of the ruling needed no code — a discard already goes face-up onto a Department
pile, which is exactly where a rival draws from.
**Gitea#6's corner survives, narrowed.** A hand with no discardable card still has exactly one way on
— play one — with nothing in the engine computing "you must play a train". The hand that reaches it
is now four Extras rather than any four trains.
### Gitea#2 — why nothing is moving on the platform
"The Sparrow pulled into the station with two loaded coaches. There are two passengers on the
platform. Four porters. My thought was to unload two and load two. I never get the chance to load the
last two."
**The engine is not deviating from the rules**, and this was checked step by step against the reported
save. §9.2 discards the white coach into the Classification Yard on boarding and draws one from the
Division Yard on de-training; §2.2 returns the Classification Yard only when the Division Yard is
empty. All three are implemented exactly. What bites is the interaction: both halves of every
passenger cycle consume coaches one-way, and a single global refill condition over a pile of ~60 cars
means they do not come back. Over the reported game the coach pool goes 8+/8− on Day 1 to 0+/1− by
Day 5, with eight coaches stranded in Classification.
**Jesse's ruling is that the shortage stays** — "it is possible to run out, that's part of the
strategy" — so the three balance options written up in `TODO.md` are declined, not deferred.
What was unambiguously a bug is that the game said **nothing**. A Porter action that cannot be taken
is simply absent from the menu, and the "why nothing is moving" panel covered freight facilities only,
so a platform had never had anything to say for itself. It now reports passengers with no train, a
train whose card bars Porters, full coaches, full red slots, the same-district rule, and the coach
shortage itself — naming how many coaches sit in Classification and what brings them back. The reason
text comes from the engine's own predicate, so the panel cannot drift from the rule that refused.
Fixing the label found a second defect: a Passenger Facility rides on the `office` card, so every
passenger row would have read `facility 0,0`; it is named by its Office tier now.
### What differs from the main line
- **The Timetabled discard is the plain rule here, not a setting.** On main it is a New Game checkbox
(`discardTimetabled`, on by default) because Jesse's reasoning is about games run LONGER than five
Days. This line has no settings-form scaffolding and no `?toss=` parameter — a Timetabled train can
simply be discarded. Both lines play the same game at main's default. The house rule itself is kept
in the engine, unreachable from the page, so `keepReason` is identical on both lines and old saves
still replay.
- **The Day-end dialog's goal half is written for this line's Frame, not ported.** Main reads a
COMBINED Revenue floor off its victory dials; this line has no such dials and instead has
`objective`, which already resolves a per-player target from the game length and whether you are on
pace. The dialog asks `objective` rather than recomputing it, so it cannot disagree with the status
block. Its tests were rewritten to match.
- **`Frame` gained a `viewer` field.** `snapshot` has always taken a viewer and resolved `revenue`,
`handCount` and `objective` against it; the index itself was missing, so a panel drawing the whole
table had no way to mark which row is yours without assuming the web client's `viewer = 0`.
- The lobby, the game types and the multiplayer handoff overlay that main's versions of `main.ts`,
`play.html` and `web.test.ts` are built around do not exist here, so those four files were
hand-resolved rather than patched.
**636 tests pass.** No replay was retired: Gitea#9 only ADDS a legal action, #8 only widens one, and
neither #10 nor #2 touches the engine, so nothing already recorded means something different now.
---
## 0.4.9f — 2026-08-22
Three more from the v0.4.9e gameplay-testing round, filed as Gitea issues: **#4** extras did not start
where the player said, **#6** train cards could be discarded, **#7** four train cards had the wrong
coach counts. Two further bugs were found underneath #4 and are fixed with it. **Gitea#2 is diagnosed
but NOT fixed** — it needs a ruling, and the reasoning is in `TODO.md`.
The same change ships as **0.6.2** on the main line. The full reasoning for every item is in that
line's CHANGELOG; this entry records what reached the playtest build and what differs.
### Gitea#4 — an Extra starts where the player puts it
Both Division Points are now offered, not the one the train's number dictates, and **the start decides
the direction** rather than the number — the two cannot both hold, since an odd westbound Extra placed
at the WEST end would leave the Division on its first move having crossed nothing and be paid for the
run. At an Interchange or a Control Point, where both ways are real runs, the player picks.
The Interchange start is a **yard**, off the running line, which is what makes the Superintendent
clause work: placing an Extra there can never force a collision however busy the card is; a guaranteed
collision holds it in the yard for another Stage and it tries again; a potential one is the
Superintendent's to rule on. Those are §8.1's two existing answers, so nothing new decides collisions.
Where an Extra may start is a **new setting in the New Game dialog** — Division Points and the
Interchange only, plus your own Control Point, or plus any player's — defaulting to what the engine
already did, so this build does not change under its testers mid-line.
**Found underneath it, and both had been shipping:** an Extra started anywhere but a Division Point
could never be given a consist and ran empty (so the Control Point start has been broken since it was
added), and `collide` left destroyed trains' transits on the Mainline card, which permanently poisoned
that card for every later train.
**The Mainline cards are now dealt from the printed deck without replacement.** They were drawn from
the nine types WITH replacement, so a Division could hold two Interchanges — and "an Extra may start at
the Interchange if one is on the board" only reads as a rule if the board holds at most one.
### Gitea#6 — a train card is never discarded
Timetabled and Extra alike. Hold one for as many Stages and Days as you like; it never goes onto a
Department pile. **No forcing mechanism was needed:** nothing discardable plus a hand over the limit
leaves exactly one legal way to end the turn, and playing a train is unconditionally legal, so a hand
of four trains cannot trap anyone. The hand panel says so on the train itself, and the blocked
end-turn button changes its wording when every card held is a train.
### Gitea#7 — coach counts
**1/2 Crack Limited 3 coaches → 2. 5/6 The Sparrow 2 → 3.**
### What differs from the main line
- The **car-placement round rotation test** that accompanies #7 on main was not ported: that test
arrived with the 0.6 multiplayer work and does not exist on this line, so there was nothing for the
coach-count change to follow.
- `src/web/main.ts` and `test/web.test.ts` needed hand-resolution — this line's New Game dialog has
neither the mode radios nor the victory dials, so only the Extra-start parts were taken.
- The `content.ts` comment pass came across whole; the `TODO.md` documentation item did not, since
this line keeps its own TODO.
**Both published replays were retired by the rules change and re-recorded.** 623 tests pass.
### The deploy script was broken by a host upgrade
Not part of the playtest report — found trying to publish this build. Every deploy died with
`login failed: 404 404 page not found`, because the File Browser host has been upgraded to
**FileBrowser Quantum**, a fork whose API differs from the v2.63 one `deploy-web.ts` was written
against. Three things moved at once, each fatal on its own:
1. **Auth is a session COOKIE**, not a JWT in the response body sent back as `X-Auth:`.
2. **The password is a header** — `X-Password`, URL-encoded — not a JSON body field.
3. **The path is a query parameter** (`?path=`), and every resource call must also name a
**`source`**: Quantum can serve several named stores and refuses any call that does not say which
("no source provided"). The v2.63 API had no such concept.
Rewritten against the running instance's own bundle rather than guessed — the same discipline the
v2.63 version was written with — and each path confirmed against the live host by response code: an
endpoint that exists answers a bad password with **401**, one that does not answers **404**. The
source is discovered from `GET /api/settings/sources`; one configured source is used silently, and
several makes the script stop and list them rather than deploy the site into the wrong store.
`FB_SOURCE` overrides it, and `FB_OTP` carries a two-factor code.
---
## 0.4.9e — 2026-08-22
Six bugs came back from a gameplay-testing session on 0.4.9d. Five are fixed here; the sixth could not
be reproduced and is written up in `TODO.md` with the two questions that would pin it down. Patched
onto the 0.4.9d line, and applied to the 0.5/0.6 line as the same change.
### Two trains at one platform answered to one button
**REPORTED:** "Operating two trains in a station: the select button does not work. Regardless of which
you pick, it is always one train, not the other."
It did not work because there was nothing for it to do. `porter.board` and `porter.detrain` carried
**no tray at all** — `{ type, at }` and nothing else — so there was one "board passengers at (0,0)"
button however many trains were standing at the platform, and the reducer walked `adOccupancy` and
filled the first empty coach it met. The roster chip the player clicked chose which crew the board
DREW and nothing else. Two independent things were wrong at once:
- `check` asked whether SOME train at the Office had an empty coach, skipping any whose card refuses
passenger work (`refusesPassengers`, `refusesThisOffice`). The reducer did not skip those. So with a
Military train and an ordinary one at the same platform, `check` said yes on behalf of the ordinary
one and the reducer boarded the Military.
- The action list collapses identical labels, and "board passengers at (0,0)" describes both trains —
the same trap that once ate a turnout's second rotation and a Department discard.
Both intents now carry an optional `trayId`, one function (`passengerWork`) resolves which train and
which coach for `check`, `execute` and the reducer alike, `legal.ts` enumerates one candidate per
train standing at the Office, and the label names it: *"board passengers at (0,0) onto Train 9"*.
`trayId` is OPTIONAL for the reason `switch.move`'s `via` is — intents are the canonical record every
save and undo replay against, and absent still means "the first eligible train".
The events carry `trayId` and `coachIndex` rather than leaving the reducer to find them again, which
is the lesson `unloadBegan`'s `carIndex` already taught: a reducer that re-derives the target is a
second implementation of the rule, and it disagreed with the first.
### A load could be made and broken without going anywhere
**REPORTED, twice over:** "Freight House: boxcars loaded cannot be immediately unloaded. In the game
we'll put the chip upside down in the tray to indicate." And: "Passenger stations: passengers just
boarded cannot be immediately unloaded."
They could. A Freight House permits both directions, so the boxcar its own Laborers had just loaded
was standing on its own industry track, loaded, with an empty of that type in the Division Yard and a
free red box — every gate said yes. Passengers were worse: `porter.board` filled a coach and
`porter.detrain` looked for "a loaded coach on a train at the Office", which is the coach that had
just been filled. Full Revenue at both ends of a movement that never happened, for one Porter action.
**Jesse's rule, and it is wider than the report:** freight or passengers loaded anywhere in an Office
Area may not be unloaded anywhere in that same Office Area — not at another facility, not in a later
Stage. A train has to carry them to a different district. So a load carries a stamp naming the SEAT
that made it (`RollingStock.origin`), and the stamp never expires; `laborer.beginUnload` and
`porter.detrain` refuse a car stamped with the district they are standing in, with a rejection code of
its own (`LOADED_IN_THIS_DISTRICT`) because "the car is loaded, the Laborer is free, the boxes are
clear, and the only thing wrong is where it came from" deserves better than "wrong car".
**A seat, not a player**, because Employee Rotation moves players between chairs and the district
stays with the chair. **Undefined, not −1**, for "no origin": the Division Yard opens with loaded cars
and loaded coaches out of the common supply, and those are exactly the inbound traffic a solitaire
district lives on — a sentinel inside `SeatIndex`'s own range is not a sentinel. And `pooled` strips
the stamp at every yard push, because the stamp belongs to the LOAD: a train can retire at a Division
Point with freight still aboard, and that car must not carry a district it left three Days ago into
whatever train is made up from it next.
**Measured: −0.60 ± 0.10 Revenue a game** (t = −6.1) over 400 paired deals — 78 deals worse, 3 better,
319 unchanged. That shape is the point. This is not a nerf spread across the game; it is a narrow
piece of free Revenue coming off the board, and on four deals in five the bot never took it.
The screen's version of the upside-down chip: a car or coach loaded by this district reads *"loaded
boxcar (loaded here)"* on the card, in the tray and in the facility panel.
### The Grocer's Warehouse shipped, and the Refinery received
**REPORTED:** "Grocer's warehouse should be receive only, does not ship anything out." And:
"Refinery: only ships out tanks, does not receive anything."
Both were `flow: 'both'` in `content.ts`, put there deliberately and for a reason that has since
collapsed. `card-reference.md` read: *"'Freight House' is not a card. It is the collective term for a
freight facility that loads and unloads — the Grocer's Warehouse and the Oil Refinery."* If that were
true, §9.3's "Passenger Facilities and Freight Houses permit cars to move each direction" named
exactly those two, and they had to be two-way. But the engine has dealt a `freightHouse` card since
before v0.4.9 — 6 copies, one slot each direction — so §9.3 names it, and the argument evaporates.
The card set says the same thing without needing the rules text. All three Refinery modifiers —
Pipelines, Oil Depot, Viscosity Breakers — grant **+1 outbound**; a two-way Refinery would be the only
industry in the game with no card able to raise one of its two directions.
`StationMaster-Home-Deck-v0.4.5.md` prints "Refinery · Outbound · 1 out / 0 in" and "Grocer's
Warehouse · Inbound · 0 out / 1 in".
So the Refinery ships and the Grocer's receives, and the **Freight House is the one two-way industry**
— which also means the only same-district load-and-unload the district rule above has to refuse is a
Freight House unloading its own work. The two fixes meet exactly where the report said they would.
A consequence worth naming rather than discovering: an **Ice House beside a Grocer's Warehouse is now
a dead card**, its +1 outbound dropped on a direction the host does not have. That is the design, not
an oversight — the Home Deck sheet says so outright, and names the Truck Dock's inbound grant beside
the outbound-only Packing Sheds as the other example. `suppressedGrants` already reports it on the
page. It does mean the v0.4.7 note in `TODO.md` that opened these two facilities up was half wrong,
and it is annotated there rather than deleted: the *machinery* it built (an industry's printed flow is
absolute; drop the grant, never open the direction) is exactly what makes this correction land.
### Not reproduced: cars left behind when backing up over them
**REPORTED:** "When I back up to collect standing cars and, further down the tracks, the caboose, I
get the caboose but the cars remain. I can later drive right through them."
Not found, and not for want of looking. Cars on plain track on the way; cars spotted at an INDUSTRY on
the way (Jesse's own guess at the shape); the train's own cut on the square it is pulling out of; a
stale `standingWest`; an industry locked by MEN AT WORK. Every one couples the lot, and the last
correctly blocks the whole route rather than letting the crew past. Three of them are now pinned in
`apply.test.ts` so the case, when it is found, is somewhere none of them cover.
The reason it is hard to make happen is structural: coupling is mandatory (§A.4) and `exploreMoves`
accumulates what it meets card by card, so a route that reaches the caboose has already met everything
between. `carsOn` is the single answer to "what is standing here", and the movement walk, the sweep in
`carsCoupled` and every renderer all ask it — so cars a train can drive through would have to be cars
that are on screen and not in `carsOn`, and there is no such place.
There was one way to MAKE such a place, and it is closed: `flyingSwitch`'s reducer wrote the cut
straight into `industryTrack`, which is not where `carsOn` looks on a Passenger Facility. `check`
refuses a non-freight target so it never fired, but a trap that needs another rule to stay unsprung is
still a trap; it goes through `carsOn` now.
`TODO.md` carries the two questions that would settle it: was there a second route to the caboose, and
what did the move button say it would couple. The label names every car, so "couples caboose" and
"couples 2 boxcars, caboose" are different bugs — the first is route selection, the second the sweep.
### Also
- **An unload never checks the facility's commodity** — found reading `laborer.beginUnload` for the
district rule, not from play. It gates on `allows.inbound`, a loaded car, a matching empty in the
yard and room in the red box, but never on `facilityCarTypes`, which `freightAgent.stockOutbound`
does check. So a Freight House will unload a hopper. Left alone and logged: the district rule now
refuses the one same-Office pairing that made it easy to reach, and the fix is a rule question about
what an industry will accept, not a one-line guard.
- **Both published replays that had gone dead were re-recorded** (`save-replay.ts 400 --top 3`). A save
is a save from a particular ruleset, so a rules change retires the files that no longer replay —
`harness.test.ts` catches it, which is what that test is for.
## 0.4.9d — 2026-08-21
Three bugs from the same playtest session, patched directly onto 0.4.9a rather than the in-progress
0.5.0 line: a display bug that made a switching train look like it had vanished, an engine bug that
silently ignored which car the player chose to unload, and a UI bug that could render a legal
decision with zero buttons — indistinguishable from a hang.
### A switching train vanished from the board the moment it left the Office
**REPORTED:** Train 3 stood at the Office; dropping the loaded boxcar off the back at the Freight
House made the train "vanish off the face of the earth," regardless of which way it moved
afterward. The game state was never wrong — replaying the reported save
(`docs/station-master-seed116956197-day2.json`) through the engine directly showed `tray3` fully
intact, in the right place, with the right consist, for the rest of the game. Nothing was ever lost
from `state.trays`.
The bug was in `officeSvg` (`board-svg.ts`): `selectedTrain` — the value that decides whether a
card draws a train's crew badge (its label, engine arrow, and cars) — was assigned only inside the
`cell.adTracks !== null` branch, which is true for the Office card and nothing else. A train
standing on any other card, which is every card it stands on while actually being switched, got no
badge at all. It disappeared on the very first move off the Office, not only at the Freight House —
that was simply the first place a player was likely to pause and look. Traced to the Roster Pass
(37b1e5b), which rewrote `CellView.train` into `CellView.trains[]` to show every train sharing the
Office's A/D tracks and, in doing so, nested the general consist-drawing logic inside that
Office-only branch instead of leaving it to run for any card with a train on it.
**Fixed** by hoisting the `selectedTrain` assignment out of the `adTracks !== null` guard so it
runs for every card; the A/D roster-chip loop itself stays inside the guard, since only the Office
has more than one A/D track to draw chips for. New test: a train parked on an ordinary facility
card, `adTracks: null`, now has to draw its crew badge — it did not before this fix.
### Unloading always took the westmost car, whichever one was picked
**REPORTED:** three loaded cars stood at a Freight House; asking to unload the east (right-hand)
car unloaded the west one instead, every time, no matter which car was actually chosen.
`laborer.beginUnload` already carried the player's choice as `carIndex`, and `check()` validated
that specific car — but the event it produced, `unloadBegan`, carried only the car's `carType`, not
which one it was. The reducer that actually performs the swap re-derived the target itself with
`industryTrack.cars.findIndex(c => c.loaded)`, which always answers the first loaded car in track
order regardless of what was requested — so the player's choice was thrown away between `check` and
the reducer, and the westmost loaded car came off every time.
**Fixed** by adding `carIndex` to the `unloadBegan` event and using it directly in the reducer
(`src/engine/apply.ts`, `case 'unloadBegan'`), instead of re-deriving a car by scanning for
`loaded`. New test in `apply.test.ts`: three loaded cars of three different types, asking to unload
index 2 (east) now leaves indices 0 and 1 alone and empties exactly the one requested — it did not
before this fix.
### A legal decision could render with zero buttons — the game looked hung
**REPORTED:** working the Freight House mid-cycle (unloading three cars, then reloading them), the
game "seemed to have hung up. Cannot advance." No trains were on the Division or the Limits.
Replaying the reported save turned up no engine deadlock at any point — every step had a legal
action — but the exact final state (an Extra train due to start, no tray yet being made up) exposed
a UI bug: `newTrain.startExtra`'s action group is titled by `trainCardTitle`, which begins "Making
up Extra X22…" — the same prefix `renderActions()` (`main.ts`) used to strip from the action list on
the assumption it always belonged to the separate yard-chip car-placement panel. With no tray being
filled yet, that panel (`menu.makeUp`) is `null`, so nothing else rendered the Extra's "choose where
it starts" decision either — a legal, present, correctly-computed option with no button anywhere on
the page. Clicking nothing did nothing, which is indistinguishable from a hang.
**Fixed** by matching the exact title of the one group `menu.makeUp` actually covers
(`g.title !== menu.makeUp?.title`) instead of a title-prefix regex, so any other group that happens
to start "Making up …" — however it got that title — stays on screen. The existing softlock
regression test (`never strands the player with a legal move and no way to make it`) now mirrors the
real render filter instead of only checking the raw menu, so this class of bug fails that test
directly; a new deterministic test constructs the exact reported scenario (a pending Extra, no
active make-up) and asserts its group survives the filter.
590 tests, 0 failures.
---
## 0.4.9a — 2026-08-20
Four small tweaks to the splash page (`index.html`, `splash.ts`), no engine changes.
### Box art opens full size on click
The thumbnail beside the title was too small to read. Clicking (or Enter/Space on keyboard focus)
now opens it in a full-size lightbox overlay; click the overlay or press Escape to close.
### A third card balances the bottom row
The doors row was nested beside the box art, two cards wide, leaving the width under the box art
unused. Moved to a full-width row below the hero (three columns at roughly the same card width as
before) and added **Play multiplayer**, modeled on the Play Solitaire card but describing the
not-yet-built feature, with "Coming soon" in place of a link. Its text is shorter than Play
Solitaire's so the row height — and the page's vertical size — doesn't change.
### Footer's "runs in your browser" claim scoped to solitaire
Now reads "solitaire runs entirely in your browser" rather than an unqualified claim that would no
longer hold once multiplayer needs a server.
---
## 0.4.9 — 2026-08-19
A playtest review of seed 58228926 (day 6), plus one long-standing display complaint and the first
real audio beyond a placeholder. Six changes: one display fix, two rules corrections, one engine bug
found while explaining a report rather than reported directly, three new sound cues, and the splash
page's box art.
### Office coordinates read X,Y now, not Y,X
Reported as confusing for anyone reading them the ordinary way: "at game start the office is 0,0;
the western limit should be -1,0, the eastern +1,0; a restaurant due north should be 0,1." The
engine's internal `GridCoord{row,col}` already has exactly that geometry — row increases north, col
increases east (`track.ts:59`) — so this was a **display-only fix**, not a data-model change: every
place a coordinate is shown to a player now prints `(col,row)` instead of `(row,col)`. The on-card
label in `board-svg.ts` (the one everyone sees), the switching-crew tooltip and button label in
`main.ts`, the rejected-option and switching-group text in `game.ts` and `view.ts`, and the
blocked-move text in `narrate.ts`. Internal `Map` keys built from `${row},${col}` are untouched —
nothing reads them but lookup code.
### "No switching" now means no adding or dropping cars — not "never touch it"
Reported from play: a train sitting at the Office with NO SWITCHING printed on its card (the two
expresses, Light Engine, Campaign, Circus, Military) could not be moved onto Secondary Track to
clear the mainline for other traffic, even though nothing on the card says that. `switchingRefusal()`
(`apply.ts`) blocked `switch.move` outright for these six cards; it now only refuses a move that
would COUPLE a fresh car — the same way `rules.dropOnly` was already handled for X13 — so the crew
can still be shunted clear, it just cannot pick up, set out or sort. `switch.dropCars` and
`switch.sortConsist` stay blocked. The switching-moves list (`view.ts`) no longer excludes these
trains, and the card description text was rewritten from "it runs the Division and does not shunt"
to "may not add or drop cars, but may still be moved clear of the mainline."
### Q3, corrected: Expedite is about WHERE a train may be left, not WHEN it leaves
**The reported symptom:** Train 1 arrived at an Office and was forced out at the end of the same
Stage — the read since v0.4.2 — leaving no Local Operations turn to switch it. **The rule question
underneath it:** why should "Expedite" mean a train is rushed out early at all, rather than simply
never being left parked off the station?
Corrected to the latter. An expedited train now arrives and stands exactly like any other train,
released by the ordinary §8.1 "stood a full Stage at the Office" rule — it can be switched normally
in between. Deleted entirely: `arriveAtOffice`'s `departsThisStage` flag and the whole
expedited-departures pass that used to run in `shiftChange`, plus the now-dead `pass: 'mainline' |
'expedite'` parameter on `moveTrain`.
In its place: a new fault. At the top of every Mainline Phase, any expedited train sitting on the
grid but not on the Office square itself — left on Secondary Track to clear a switching move, say —
costs 1 Revenue (`EXPEDITE_FAULT_PENALTY`, `expediteFault`), charged again every Phase it is still
caught there. A train the ordinary rules are legitimately holding AT the station — even one §8.1 is
asking the Superintendent to rule on — is not a fault; only being left elsewhere in the district is.
**This resolves "3/4 EXPRESS PRINTS A RULE IT CAN NEVER USE"** (`TODO.md`) as a side effect: the
Express can now actually reach a Local Operations turn to use its printed "may drop or pick up one
freight car at every location," which the old same-stage departure made structurally impossible.
**Measured (30 fresh bot games, standard length):** the fault fires, but the bot has no strategy for
it yet — one game left Train 4 (3/4 Express) parked off the station from Day 3 Stage 10 to the end of
the game, taking the -1 penalty 26 times. Not an engine bug: the mechanism is working as designed and
correctly reveals that the bot doesn't know to bring an expedited train home before ending a
switching turn. Logged in `TODO.md` under Bot Performance for a future pass.
### `evaluateClearance` now checks every occupant, not just the first one it finds
Found while explaining a second playtest report from the same game: the Superintendent was asked to
rule on a same-direction train instead of being automatically held against an opposite-direction one
also occupying the card. Root cause: the occupant loop (`advance.ts`) returned on whichever occupant
it examined first, in `node.transits` insertion order — correct while a Subdivision held at most one
train, but a card can now legitimately hold two at once, which is exactly what the
Telegraph/Telephone/Radio dispatch exception creates (a facing train dispatched past another sits on
the same card as it). Fixed to two passes: every occupant is checked for an opposite-direction
absolute bar first (subject to the dispatch exception) before any same-direction judgment call is
offered. Pinned with a regression test that fails against the old single-pass code
(`enhancements.test.ts`).
### Three more sounds, synthesised like the rest
`arrive`, `depart` and `crash` join `stage`/`couple`/`drop`/`schedule`/`completed`/`day`/`train` in
`sound.ts` — a train pulling into an Office (decelerating chuffs, a soft bell tap), one highballing
out of one (accelerating chuffs, a falling horn note), and a collision (dissonant tones bent sharply
down over a noise boom and a sub-bass thump), wired to `trainArrived`, `trainHighballed` (Office
departures only, so it doesn't double up with a fresh make-up's "All aboard" or a full division run's
`completed`), and `trainsDestroyed`. Three real WAV clips were sourced for this and considered, but
carried no license information anywhere — no `LICENSE` file, no embedded metadata, no note of where
they came from — so they were not committed; the synthesised versions are good enough to keep as the
real thing rather than a placeholder.
### The splash page has its box art
`docs/StationMasterSplashScreen.png` (1122×1402, 3.0 MB) is now a 560×700 JPEG at 145 KB
(`public/images/`, copied verbatim into `dist/images/` by a small addition to `build-web.ts`) and
sits beside the title, tagline, blurb and both buttons in a side-by-side hero on `index.html`,
stacking to image-above-text under the existing mobile breakpoint.
---
## 0.4.8 — 2026-08-19
Four reports from the same game, all about squares: which ones a card may go on, which one a button
in the action list means, when there is more than one legal road to the same square which one a
train actually takes, and — when more than one train is standing at the same Office — which is
which.
### The Limits bound the district, not just the Running Track
**Reported:**
> "Sidings should not be allowed to be built outside the limits."
The Limits sign "denotes the limit of your control area" (§2.1) and §3 defines Secondary Track as
"all tracks **in your limits** that are not the Running Track" — but the bound was only ever enforced
on the Running Track row itself, with a comment in `canPlaceAt` stating outright that "the district
below the Running Track is unbounded". So a siding could run east past a player's own sign, take
industries with it, and put cars on track that §8.1 and §10 do not consider his territory at all: the
rules reason about "the track between the train and the Limits", and running past another player's
Limits is what makes a collision his fault.
`withinLimits` is now the district's rule at **every row**, and a Facility is bounded by it too —
§11.2 is explicit that "Facility cards carry their own rails: placing a Facility places track". The
refusal is its own code, `OUTSIDE_LIMITS`, rather than `NOT_CONNECTED`, for the same reason
`BREAKS_RUNNING_TRACK` is: the card would join perfectly well, and is refused for a different reason.
**Inclusive of the sign's own column**, which is the half that keeps the game playable. Jesse's call.
The sign stands *on* the boundary rather than beyond it, and a district opens with signs at ±1 around
the Office — so the strict reading would leave exactly one buildable column and break §11.3's promise
that both Secondary rows, and the nine-spot Modifier neighbourhood, are usable from the first Stage.
A siding may run under the sign; nothing may go past it.
**What it costs the bot: nothing measurable.** Out-of-limits building was rare for it to begin with —
5 cards across 100 games, in 4 of them, never more than two columns over — and paired over 200 seeds
the bound moved 4 games and −0.015 Revenue (t = −0.26). It is a human building deliberately who hits
this, which is exactly how it was found.
### The nine spots really are nine — the four diagonals were legal and unofferable
**Reported:**
> "Modifiers should be able to go on any diagonal — we were unable to place it to the south-east."
§9 places a Modifier "adjacent to a Facility, on any of the nine nearby spots", and `check` has
always accepted all eight neighbours. The fault was upstream in `placementCandidates`, which walks
north, south, east and west from every occupied square: a diagonal square with no *orthogonal*
occupied neighbour was never generated, so it was never offered. Measured on a facility below the
Office: `check` says legal at all four diagonals, the menu offered the three orthogonal ones. At a
stub industry — the case in the report — every diagonal is in that position.
Generated in a **second pass, only around a Facility**. Track has to *join* and a diagonal shares no
edge, so a Modifier is the only card those squares can ever take; generating diagonals around every
card instead costs 54% more simulation time producing candidates `check` then rejects. Appending
rather than interleaving leaves the existing candidate order untouched, which matters because the bot
breaks ties by first-best — measured over 200 seeded games, **0 played differently**, so every figure
in `TODO.md` still stands.
### A Modifier may hang outside the Limits — but not in the Running Track's row
Jesse's call, both halves. A Modifier is not track (§9), so unlike a siding it keeps all nine of its
spots when its host stands at the limit: refusing the outer three would make the card unplayable
exactly where the district ends. What it may not do is stand in the row the Running Track grows
along. Inside the Limits that row is always full, so the rule bites only beyond the sign — and that
is the ground the main extends onto, where a parked Modifier would block the player's own sign from
moving outward (§2.1) with nothing on screen to warn him. Industries have been barred from the
Running Track since the "Placed" column was read properly; this is the same rule for the same reason.
### The board draws where the district ends
Two signs on one row cannot say that nothing may be built outside their columns at *any* row: a
player looking at open ground beyond a sign had no way to know it was unbuildable until the square
failed to light up. `officeSvg` now draws a quiet dashed edge down the whole canvas at each limit,
labelled, and just **outside** the sign's own column so the picture agrees with the rule — a siding
may run under the sign. It moves outward on its own as the Running Track is extended, which is the
reward for extending made visible. The Frame carries `limits` for it, resolved server-side like
everything else a remote client cannot look up (`multiplayer.md` §5).
The margin on the viewBox is not cosmetic: the west sign is usually the leftmost card on the canvas,
so the line outside its column lands at x = −1.5 and simply is not there on a canvas starting at 0.
Caught by drawing one, not by reading the code.
### Hovering an action points at the square it means
**Reported:**
> "When I have my mouse over the action for a particular square, could the corresponding square in
> the office area be highlighted to minimize my mistakes of selecting the wrong square — 1,3 versus
> −1,3? In a solitaire game with Undo it is not fatal. In a multiplayer game that could be a major
> disaster."
The action list is a column of near-identical sentences separated by a coordinate, and the board
beside it said nothing about which was which. Every action that names a square now carries it as
`data-square`, and hovering — or focusing, so the keyboard route is not a lesser one — lights that
square on the board, ghost targets included, which is precisely the moment a player is choosing
between coordinates.
The coordinate rides on the **menu**, resolved from the intent by `coordOf`, rather than being parsed
back out of the label: a remote client holds no `GameState` and cannot look up where a tray is
standing, which is the same reason the menu already carries card descriptions. Checked over 12 bot
games: 870 direct actions name a square, and all 870 carry it.
### Two routes to the same square
**Reported:**
> "There are times when a train can take two different paths to get to a destination. See game at
> undo 379. Train 11 can go from Eastern limits to the straight at 1,1 two different ways. It can go
> through the refinery and pick up the tanker on its nose, or it could go straight and then make the
> curve and skip the refinery and not pick up the car. The player should have the two different
> options."
A district with a passing loop — turnout off the main, curve down to an industry, curve back up —
offers two legal routes between the same two squares, and `exploreMoves` (`track.ts`) only ever found
one: it keyed its visited set on destination and entry port, both routes rejoin through the same
port, and the shorter one won the race before the longer one could be recorded. Which route survived
was an artifact of search order, not a choice.
**Ruling (Jesse, docs/rules/open-questions.md Gap 14):** the player may choose the path. §A.4 says
"cars **on your track**" — the industry spur is a different track, and declining to enter it is not
going around the car standing there. The mandatory half still bites in full once a route is chosen:
every car standing on it couples.
**The walk now enumerates every simple route** — a per-path visited set replaces the old global one,
so a card may be revisited across different routes but never twice within one — capped at 4,000
frontier nodes so a dense district cannot blow the walk up combinatorially; BFS order means the cap
loses only the longest routes first. Routes are deduped on **outcome**, not on reaching the square:
`(destination, entry side, [(origin card, car)…])`, so two routes coupling identical car *types* off
*different* cards are both offered and each sweeps its own card, while two routes with nothing to
tell apart collapse to one.
**`switch.move` gained an optional `via: GridCoord`** — one intermediate square on the chosen route,
never the start or the destination. `legal.ts` emits one intent per distinct route with a `via` that
distinguishes it from its siblings; `via` absent resolves exactly as before (the first route
enumerated), so every existing save and every bot decision replays identically. Checked against
`public/replays/*.json` and the full suite: 575 pass, 0 fail, unchanged.
Threaded through the label (`describeIntent` finds the route `via` names, so "couples 1 tanker"
reports the cars *that* route actually lifts), the action-list dedupe (two routes to one square would
otherwise print the identical button twice), the hover highlight (`data-route` lights every square a
route runs over, not just its destination), and the history (`trayMoved.via`, when the move was
ambiguous, names which road the crew took).
**Balance impact: none expected, and none measured able to be attributed to this.** Instrumented over
60 developer-bot games (17,884 destinations enumerated): squares reachable by 2+ distinct paths are
~1.2% (208), and in every one of those 208 the routes coupled identically — the bot has never yet
built a district where the discarded route would have mattered. 400 full games (200 developer bot,
200 random bot) completed 200/200 with no exceptions on the reworked walk. `compare.ts` needs an
ablation flag to run at all and this is not a bot heuristic, so paired A/B was not applicable here;
the enumeration-based argument above is the actual evidence.
### The Roster Pass — every train at the Office visible
**The Office is the one square where more than one train may legally stand at once** — it has
several A/D tracks, each holding one — and the board drew it as if only one ever could. Two trays
at a Station couple onto the identical `officeCoord`; `trainOnCard()` returned on the first match
and `CellView.train` had room for exactly one, so a second train was counted in the old A/D pips
and never drawn at all. Reported directly, and analysed in "Two Trains, One Card": the pips and the
picture were reading different fields.
**`CellView.train` is now `CellView.trains: TrainView[]`** — every train standing on the card, each
carrying its own `trayId`. The A/D pips are gone; in their place is one roster chip per A/D track,
always (`adTracks` of them, not one per train), free tracks reading a dashed, dimmed "free" rather
than vanishing. The selected train's chip is lit the same amber the crew strip and action buttons
use, and its consist is the one drawn at the rail — clicking any occupied chip sets `selectedCrew`,
the same value the "Which train are you switching?" picker already wrote, so the board and the
action panel drive one value in both directions.
**`standingWest` moved from `CrewTray` to `TrackCard`.** The split still means what it always meant
— west/east of the row of standing cars — and it is still only meaningful while an engine stands on
the card (an unattended cut has no near or far side; that reasoning did not change). What forced the
move: two trays sharing one Office card could otherwise hold two different splits of the identical
row, and there is no such thing as "west of one particular A/D track" — a cut lies west or east of
the *whole block* of A/D tracks, so there has to be exactly one number for the card to carry. No
save migration: `Save = {seed, history, rules?}` replays through the engine rather than being
loaded, and a stale value on an emptied card is inert because nothing reads a split with no train
standing there.
**The Division map stopped drawing trains on their neighbours.** The Office's Running Track cell was
a fixed 78px regardless of how many A/D tracks it had, so two chips centre-spread wider than the
cell and spilled onto the Limits cards either side. The cell is now sized by **capacity**
(`max(78, adTracks·54+12)`), not by how many tracks are occupied — sized by occupancy instead, the
board would have shifted the East Division Point sideways every time a train arrived or left — and
chips are laid into fixed slots, one per A/D track, so none can ever overhang the cell.
**Verified:** two trays at a Station are both drawn, each with its own chip; a Terminal's four
tracks all fit; a bare cut with a stale `standingWest` still draws left-aligned; every roster chip's
x-extent lies inside its Office cell at full occupancy; and a packed replay row from before this
feature — a lone train object, not an array — rehydrates into a one-train roster rather than
throwing. 584 tests, 0 failures.
### Also
- The three published replays were re-recorded. A save is a seed and its intents, so tightening a
placement rule kills every replay containing one — `harness.test.ts` catches it rather than letting
them go quietly dead, which has happened twice before. Old saves are not preserved across rule
changes and are not meant to be yet.
- `node_modules` was a **tracked symlink pointing at a path that does not exist**, so `tsc` was
missing and 20 tests failed before any of this was written. Replaced with the real dependencies.
## 0.4.7 — 2026-08-19
Eight play reports and one design that had been written up and not built. The through-line is the
+9 -1
View File
@@ -10,7 +10,7 @@ train into an occupied Subdivision. Get that wrong and two trains meet at speed.
## Status
**v0.4.3 — solitaire is playable in a browser.** The whole game runs client-side: the engine is pure,
**v0.4.8 — solitaire is playable in a browser.** The whole game runs client-side: the engine is pure,
imports nothing outside itself, and never touches `Math.random`, so a static host is all it needs.
- **Rules** — specified, with **three open questions** left. Thirteen gaps in the original prototype
@@ -121,6 +121,14 @@ is the thing this machinery exists to prevent.
it was worth more than the entire freight and passenger economy put together, for traffic nobody
has to work. A seed alone therefore no longer names a game — the settings ride in the URL beside
it, and every save records the rules it was dealt under.
- **A load may not be broken in the district that made it.** Freight or passengers loaded anywhere in
an Office Area cannot be unloaded anywhere in that same Office Area — not at another facility, not
in a later Stage. A train has to carry them to a different district first. The printed game turns
the chip upside down in the tray; here the load carries the seat that made it (`RollingStock.origin`
in `src/engine/state.ts`) and it never expires. Without it a Freight House could unload the boxcar
its own Laborers had just loaded and a platform could detrain the passengers it had just boarded,
each paying Revenue at both ends for a load that went nowhere: worth **0.60 ± 0.10 Revenue a game**
to the developer bot over 400 paired deals, on 78 of them.
- **A turnout can be laid on top of a card already down.** It upgrades a straight at any rotation, or
a curve whose arc matches its own diverging leg — both strict port supersets of what they replace,
so an upgrade can never sever an existing join. Without it a district could only hang off track that
+633 -441
View File
File diff suppressed because it is too large Load Diff
+9 -2
View File
@@ -98,11 +98,18 @@ Playing a timetabled train card rolls the seeded D12 and places its number in th
The listed consist is a maximum, not a minimum: a train may depart with fewer cars, but must not exceed the listed categories, put a car behind a caboose, or leave with the engine buried among cars. A Crew Tray holds no more than four rolling-stock cars.
> **Changed 2026-08-22 (Gitea#7), Jesse's call:** the coach counts on **1/2 Crack Limited** and
> **5/6 The Sparrow** were swapped — the Limited drops from three coaches to two, the Sparrow rises
> from two to three. This is a change to the CARDS, not a correction to this table: `Trains3.pdf` and
> the transcription in [`rules/implications.md`](rules/implications.md) §5 still show the original
> numbers, and are right about what the printed cards said. `src/engine/content.ts` and this table
> carry what the game plays.
| Train | Speed | Direction | Listed maximum consist | Implemented special rule |
| --- | --- | --- | --- | --- |
| 1/2 Crack Limited | Fast | 1 west / 2 east | 3 coaches | No switching; passenger work only at Terminals; expedited. |
| 1/2 Crack Limited | Fast | 1 west / 2 east | **2 coaches** | No switching; passenger work only at Terminals; expedited. |
| 3/4 Express | Fast | 3 west / 4 east | 2 freight | May exchange at most one freight car at each grid location during its switching turn; expedited. |
| 5/6 The Sparrow | Fast | 5 west / 6 east | 2 coaches | No switching; expedited. |
| 5/6 The Sparrow | Fast | 5 west / 6 east | **3 coaches** | No switching; expedited. |
| 7/8 Local | Slow | 7 west / 8 east | 1 freight, 1 coach | Its coach may not be set out during switching. |
| 9/10 Heavy Freight | Slow | 9 west / 10 east | 3 freight, 1 caboose | — |
| 11/12 Drag Freight | Slow | 11 west / 12 east | 2 freight, 1 caboose | — |
+6 -2
View File
@@ -45,9 +45,13 @@ The PDF art labels this card “Yard”; this reference uses the implementation
| Trestle | 60 mph. |
| Interchange | 60 mph. A train may be reordered there only through the card’s printed “sort cars” concept; the current engine does **not** provide a Mainline sorting action for it. |
### PDF/code mismatch requiring correction
### PDF/code mismatch — CORRECTED
`src/engine/content.ts` defines nine `MAINLINE_PROFILES` types: one Plains entry plus the eight other terrain types above. `setup.ts` selects uniformly from that nine-type list. The second Plains card shown in `Mainline Cards.pdf` is therefore not represented as a duplicate card or as extra Plains weight in setup. If the PDF inventory is authoritative, the setup selection needs a second Plains entry (or an equivalent weighted selection).
**Was:** `src/engine/content.ts` defines nine `MAINLINE_PROFILES` types: one Plains entry plus the eight other terrain types above. `setup.ts` selected uniformly from that nine-type list, **with replacement**. The second Plains card shown in `Mainline Cards.pdf` was therefore not represented as a duplicate card or as extra Plains weight in setup — and, worse than a weighting error, a Division could be dealt two Interchanges, two Tunnels or two Trestles, none of which the deck contains.
**Now:** `MAINLINE_DECK` in `content.ts` is the inventory table above — ten drawable cards, Plains twice and the other eight once each — and `buildDivision` deals from it without replacement. The two Division Point cards are not in that deck: they are the fixed ends of the Division, laid by `buildDivision` itself rather than drawn.
The Interchange is what forced the correction. §7 lets an Extra be started at the Interchange "if one is on the board" (see `docs/rules/implications.md`, §7), which only reads as a rule if the board can hold at most one.
The executable state represents East and West Division Points as fixed end nodes, not as card records. They are functionally present at the ends of the Division, but are not represented as the two PDF cards in the deck/state model.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

+207
View File
@@ -0,0 +1,207 @@
# Plan — Train Switching Paths: two routes to the same square
**Status:** built, v0.4.8. Written against `461c4d9`; see `docs/rules/open-questions.md` Gap 14 and
the CHANGELOG's "Two routes to the same square" for the ruling and what shipped.
**Reported by Jesse:** *"There are times when a train can take two different paths to get to a
destination. See game at undo 379. Train 11 can go from Eastern limits to the straight at 1,1 two
different ways. It can go through the refinery and pick up the tanker on its nose, or it could go
straight straight and then make the curve and skip the refinery and not pick up the car. The player
should have the two different options."*
---
## 1. The defect
A district with a passing loop — turnout down off the main, curve, industry, curve, turnout back up —
offers two routes from one end to the rejoin square. Both are legal under §2.4 (a Move runs any
distance without changing direction; neither route ever leaves a card by the port it entered). They
differ in what they couple.
**The engine offers only one of them, and which one is an artifact of search order.**
`exploreMoves` (`src/engine/track.ts:386`) keys its visited set on destination *and entry port*:
```ts
// src/engine/track.ts:492
const key = `${coordKey(node.coord)}|${node.entry}`;
if (seen.has(key)) continue;
```
Both routes arrive at the rejoin square through the **same port**, so they collide on that key. The
walk is breadth-first, so the shorter route is recorded and the longer one is discarded before it can
become a destination.
### Reproduction
Fixture — Running Track on row 0, industry spur on row −1:
| | col 0 | col 1 | col 2 | col 3 | col 4 |
|---|---|---|---|---|---|
| **row 0** | straight | turnout `{w,e,s}` | straight | turnout `{e,w,s}` | Limits (east) |
| **row −1** | — | curve `ne` | **Refinery + tanker** | curve `nw` | — |
Walking west from `(0,4)`, today's engine returns:
```
(0,2) entry=e couples=[] path=(0,3)
(-1,3) entry=n couples=[] path=(0,3)
(-1,2) entry=e couples=[tanker] path=(0,3)->(-1,3)
(0,0) entry=e couples=[] path=(0,3)->(0,2)->(0,1) ← only one route to (0,0)
(-1,1) entry=e couples=[tanker] path=(0,3)->(-1,3)->(-1,2)
```
The refinery route to `(0,0)` — which couples the tanker — is absent. A simple-path prototype on the
same fixture returns both. Verified identical on v0.4.7 and v0.4.8.
### It is not cosmetic
`dest.path` feeds `carsCoupled.from` (`src/engine/apply.ts`, the `switch.move` execute branch at
`:1303`) — the list of cards swept clean when cars are lifted. The route reaches the reducer, so
"which route" must be part of the intent, not just the button text.
### How often
Instrumented over 60 developer-bot games (17,884 destinations enumerated):
| measure | count |
|---|---|
| destinations enumerated | 17,884 |
| squares reachable by 2+ **distinct paths** | 208 (~1.2%) |
| squares where the routes **differed in what they couple** | **0** |
So the geometry occurs and today's engine silently discards a route about 1% of the time — but the
bot never builds a district where the discarded route *matters*. Two consequences:
- **Balance impact is expected to be nil.** Still confirm with `compare.ts` (see §6).
- **The bot will never regression-test this.** It needs explicit unit tests.
---
## 2. The rules question, and Jesse's ruling
§A.4 says: *"If you move your Crew Tray into cars on your track, you **MUST** pick them up. You may
not go around them."* Whether taking the main instead of the siding counts as "going around" decides
whether this feature is legal at all.
**Ruling (Jesse):** the player may choose the path. Different paths may pick up different cars, or
none.
The permissive reading is well-supported by the text: §A.4 says *"cars on your track"*, and the
industry spur is a different track. Declining to enter it is not going around the tanker — it is not
going to the tanker's track at all, which is ordinary railroading. The mandatory half still bites in
full: once a route is chosen, every car standing on it couples, and there is no route that passes a
car and leaves it.
**Doc changes:** add the clarifying sentence to §A.4 in `docs/rules/rules-v0.2.md`, and record the
ruling in `docs/rules/open-questions.md`.
---
## 3. Design decisions
**The discriminator is `via`: one intermediate `GridCoord` on the chosen route** (Jesse's call).
Not an index into the destination list — intents are the canonical record and `undo` replays history
minus one intent, so an order-dependent field would silently reinterpret saved games.
```ts
// src/engine/intents.ts:19
| { type: 'switch.move'; trayId: TrayId; to: GridCoord; reverse: boolean; via?: GridCoord }
```
- `via` names an **intermediate** card — never the start, never the destination.
- **Resolution:** among destinations at `to` matching `reverse`, take the first enumerated route whose
path contains `via`. Enumeration stays shortest-first.
- **`via` absent resolves exactly as today** (first route at `to`), so existing histories replay
unchanged. Note v0.4.8 already established that saves are *not* preserved across rule changes —
this is belt-and-braces, not a hard constraint.
- **`legal.ts` emits a distinguishing `via`** per route, so a generated intent is never ambiguous.
**Collapse routes whose outcome is identical.** Two routes that lift the same cars from the same
cards are not a choice; offering both is noise in the action list and doubles the bot's branching
factor for nothing.
**The dedupe key must include the origin cards, not just car types.** Two routes can couple an
identical car *multiset* lifted from *different* cards. Keying on type alone would collapse them and
sweep the wrong card clean. Key on `(coord, entry, [(origin card, car)...])`.
**Simple-path walk with an enumeration cap.** Relaxing `seen` to a per-path visited set keeps
termination (no card twice within one path), but the number of simple paths is worst-case exponential
in a dense district. Cap enumeration and prefer shortest routes when the cap bites.
> Note: the 45°-diagonal matching rule appears to make closed loops geometrically impossible — a
> rectangle of four curves cannot close, because the slopes do not match at the corners. **Do not
> rely on this.** Use a path-local visited set and a cap regardless.
---
## 4. Change list
| File | Site | Change |
|---|---|---|
| `src/engine/track.ts` | `exploreMoves` :386, `seen` :492 | Per-path visited set; dedupe on outcome; cap. Preserve shortest-first ordering. |
| `src/engine/intents.ts` | :19 | Add `via?: GridCoord`. |
| `src/engine/apply.ts` | `check` :623 | Select destination by `via`, not first-by-coord. |
| `src/engine/apply.ts` | `execute` :1303 | Same selection; `carsCoupled.from` follows the chosen path. |
| `src/engine/apply.ts` | `destinationsFor` :1210, `movesFor` :1260 | Unchanged signatures; `movesFor` still collapses to one square per coord for the board. |
| `src/engine/legal.ts` | :90 | Emit one intent per distinct route, each with a distinguishing `via`. |
| `src/sim/view.ts` | `describeIntent` :724 | Find the destination by `via` so the label names the cars *that route* couples. |
| `src/web/game.ts` | `coordOf` :113, label dedupe ~:229 | Labels must differ per route or the label-dedupe drops one button. |
| `src/web/main.ts` | `cellRef` :660 | Route-on-hover — see §5. |
| `src/sim/narrate.ts` | move narration | Name the route when it is not the only one. |
**`ownCutFor` (`apply.ts:1241`) needs no change** — it depends only on the exit port, not the route.
---
## 5. UI — route on hover (Jesse's choice)
v0.4.8 already built the mechanism: `coordOf(intent)` → `cellRef` → `data-square="r,c"` on each
action button, and hovering or focusing lights that square. This feature extends it from one square
to a route.
- Carry the path on the **menu**, resolved server-side, for the same reason `coordOf` is: a remote
client holds no `GameState`.
- Emit the route as a second attribute (`data-route="r,c r,c …"`); hovering or focusing lights every
card the route runs over, with the destination keeping its existing stronger mark.
- **On focus as well as hover**, matching v0.4.8 — the keyboard route is not a lesser one.
Target rendering:
```
Switching Train 11, standing at (1, 4)
[ move to (1,1) ]
[ move to (1,1) — couples 1 tanker on the way (onto the nose) ] ← hover
```
---
## 6. Verification
- **Unit test the fixture in §1** — both routes offered, one coupling the tanker and one not.
- **`via` round-trip** — each intent `legal.ts` emits resolves back to the route it was generated for.
- **Back-compat** — replay `public/replays/*.json` and assert identical outcomes with `via` absent.
- **Origin-card dedupe** — two routes coupling identical car *types* from *different* cards must both
be offered, and each must sweep its own card.
- **Cap** — a dense district must terminate and stay bounded.
- **Balance** — `node src/sim/compare.ts 1600`. Expect no movement (the bot never builds this
geometry); keep only at t ≥ 3 per `README.md`, and read the better/worse/identical split.
**Run the suite serially: `node --test --test-concurrency=1`.** The `npm test` script runs files in
parallel and several of them invoke the static build against a shared `dist/`, which produces ~20
spurious failures. Measured on `461c4d9`: parallel 20 fail / serial **575 pass, 0 fail**.
> v0.4.8's CHANGELOG attributes those 20 failures to the tracked `node_modules` symlink. That fix was
> real and worth making, but it is **not** the whole cause: on this checkout `tsc` resolves and
> typecheck exits 0, yet the same 20 fail under parallel execution and pass under
> `--test-concurrency=1`. The `dist/` race is still there. Worth fixing separately — give each
> build-invoking test its own output directory.
---
## 7. Open question for Jesse
A route's cards may be reachable only as a *subset* of a longer route's cards. If that ever happens,
no single `via` uniquely selects the shorter route, and it is addressable only by the
shortest-first tiebreak. It did not arise in any fixture or in 60 bot games, and it may be
geometrically impossible — but if it does arise, the alternatives are to reject the ambiguous intent
or to let shortest-first stand. **Shortest-first is assumed here.**
+38 -15
View File
@@ -42,17 +42,33 @@ Operational Rail wheel icon, an industry track of the stated length, Laborer ico
| --- | --- | --- | ---: | ---: | ---: | ---: | ---: |
| Mine Tipple | Hopper | Outbound only | 3 | 3 | — | 4 | 2 |
| Produce Shed | Reefer | Outbound only | 2 | 2 | — | 3 | 2 |
| Grocer's Warehouse | Boxcar | Both | 2 | 2 | 2 | 3 | 2 |
| Oil Refinery | Tank car | Both | 3 | 2 | 2 | 4 | 2 |
| Grocer's Warehouse | Boxcar | Inbound only | 2 | — | 2 | 3 | 2 |
| Oil Refinery | Tank car | Outbound only | 3 | 2 | — | 4 | 2 |
| Power Plant | Hopper | Inbound only | 3 | — | 3 | 4 | 2 |
Directions follow the commodity: coal originates at a Mine Tipple and is consumed at a Power Plant;
produce ships out; a warehouse and a refinery do both. This gives §9 all three of its cases —
outbound-only, inbound-only, and both.
produce ships out; a warehouse receives. This gives §9 all three of its cases — outbound-only,
inbound-only, and both — with the **Freight House the one card that does both**.
**"Freight House"** (§9.3, Appendix A) is not a card. It is the collective term for a freight facility
that loads *and* unloads — the Grocer's Warehouse and the Oil Refinery. §9.3's "Passenger Facilities
and Freight Houses permit cars to move each direction" therefore names exactly those two.
**The Grocer's Warehouse and the Oil Refinery are ONE-WAY** (corrected v0.4.9e, from gameplay
testing): "Grocer's Warehouse should be receive only, does not ship anything out"; "Refinery: only
ships out tanks, does not receive anything" (Jesse). The Direction column read "Both" for both, on the
reading below that "Freight House" named exactly those two.
**And that reading is wrong.** §9.3/Appendix A's "Passenger Facilities and Freight Houses permit cars
to move each direction" names a CARD: the engine deals a `freightHouse` industry, 6 copies, one
Laborer and one slot each direction (`content.ts`), and has since before v0.4.9. This paragraph used
to read "'Freight House' is not a card — it is the collective term for a freight facility that loads
*and* unloads, the Grocer's Warehouse and the Oil Refinery", and that premise is what made those two
two-way. `StationMaster-Home-Deck-v0.4.5.md` prints them one-way, and the modifier set agrees: all
three Refinery modifiers (Pipelines, Oil Depot, Viscosity Breakers) grant **+1 outbound**, which would
be an odd card set for a facility that receives half the time.
<!-- The Laborer and capacity numbers in the rows above were NOT re-verified against the engine in
this pass — only the Direction column was, which is what playtesting reported on. `content.ts`
gives every industry base 1 out / 1 in / 1 Laborer, so the table's 2s and 3s and the "Throughput"
reasoning built on them are likely stale. Flagged rather than silently rewritten: Laborer counts
are a balance question, not only a docs one. -->
### Throughput — why these Laborer counts
@@ -80,9 +96,10 @@ deliberately slower industries, unable to quite keep up with a dedicated player.
That is why Laborer counts track Outbound capacity: Mine Tipple 3/3, Power Plant 3/3, Produce Shed
2/2, Grocer's Warehouse 2/2. The numbers are derived from the action budget, not chosen freely.
The Oil Refinery is the exception at 3 Laborers against 2+2 capacity, and deliberately so: it serves
two flows through one three-box pipeline, so its pipeline stays fuller than a one-way facility's and
the third Laborer is earning its keep.
<!-- The paragraph that stood here explained the Oil Refinery's third Laborer as the price of serving
two flows through one pipeline. It serves one flow (v0.4.9e), so the explanation is gone with the
premise; whether the Laborer count is still right is part of the same unverified block flagged
above and in TODO.md. -->
Even so, Laborers are rarely what limits a player — spotting the empty car and hauling the loaded one
away both cost switching actions from the same budget. See §7.
@@ -138,8 +155,14 @@ above and below. Upgrades are drop-in and must never disturb a connection.
## 5. Modifier cards
Five cards, one each. A Modifier is **not track**. It is placed adjacent to a Facility, on any of the
nine nearby spots, and if adjacent to two Facilities its effect may be used on only one per Stage
(§9).
nine nearby spots — **diagonals included** — and if adjacent to two Facilities its effect may be used
on only one per Stage (§9).
Two placement rules follow from it not being track. It is **not bounded by the Limits**: a host
standing at the edge of the district keeps all nine of its spots, or the card would be unplayable
exactly where the district ends. And it may **never stand in the Running Track's row**, which inside
the Limits is always full anyway — beyond the sign that row is the ground the main grows onto, and a
Modifier parked there would block the Limits sign from moving outward (§2.1).
| Card | Effect | Applies to |
| --- | --- | --- |
@@ -252,12 +275,12 @@ with all boxes full:
| Car | Facility demand | Supply | Headroom |
| --- | ---: | ---: | --- |
| Hopper | Mine Tipple 3×2 + Power Plant 3×2 = 12 | 12 | exactly met |
| Tank | Oil Refinery (2+2)×2 = 8 | 8 | exactly met |
| Boxcar | Grocer's (2+2)×2 = 8 | 12 | 4 spare |
| Tank | Oil Refinery 2×2 = 4 | 8 | 4 spare (was "exactly met" while the Refinery was two-way) |
| Boxcar | Grocer's 2×2 = 4 | 12 | 8 spare (same correction) |
| Reefer | Produce Shed 2×2 = 4 | 8 | 4 spare |
| Coach | Terminal 4+4, per Office | 16 | scales with Office count |
Hoppers and tank cars are exactly met in the theoretical worst case, which cannot occur in practice —
Hoppers are exactly met in the theoretical worst case, which cannot occur in practice —
only 10 freight facility cards exist across a 52-card deck shared by all players, and the §2.2
Classification Yard recycle returns stock to the Division Yard whenever it empties. Both are worth
watching in playtesting.
+2 -2
View File
@@ -24,8 +24,8 @@ Every defined term, alphabetized for lookup. The core comes from the Definitions
| **Extra Platform** | Modifier card: +1 green and +1 red slot at a Passenger Facility. | §12.5 |
| **Extra Train** | A one-and-done train; its card returns to the Salvage Yard on completion. Head-on card image, so the drawing player picks its direction. Numbered with an "X" prefix; the following number gives its seniority, and it yields to the Timetabled train of that number. | §2.3, §8 |
| **Facility** | A business which loads/unloads cargo and freight. | §2.5 |
| **Freight Facility** | Mine Tipples, Produce Sheds, Grocer's Warehouses, Oil Refineries, Power Plants. Some allow only outbound, some only inbound, some both. Per-card values in §12.5. | §9, §12.5 |
| **Freight House** | Not a card — the collective term for a freight facility permitting both directions, namely the Grocer's Warehouse and the Oil Refinery. | §9.3, §12.5 |
| **Freight Facility** | Mine Tipples, Produce Sheds, Grocer's Warehouses, Oil Refineries, Power Plants, Freight Houses. Some allow only outbound, some only inbound, some both. Per-card values in §12.5. | §9, §12.5 |
| **Freight House** | A sixth Freight Facility card, dealt like any other industry (`content.ts`) — this entry used to read "not a card, the collective term for the Grocer's Warehouse and the Oil Refinery", which the engine never agreed with. **The only industry that permits both directions**: the Grocer's Warehouse receives and the Oil Refinery ships, one way each (v0.4.9e). | §9.3, §12.5 |
| **Highball** | When a train holding at an Office automatically departs. | §2.4 |
| **Home Office** | The primary face-down deck cards are drawn from. 52 cards. | §2.6, §12.1 |
| **Hopper** | Coal rolling stock (brown = loaded, white = empty). | §2.2 |
+158 -2
View File
@@ -486,13 +486,19 @@ Hotel) are what grow them.
| # | Name | Speed | Consist | Rule |
| --- | --- | --- | --- | --- |
| 1/2 | Crack Limited | Fast | 3 coaches | Stop at Terminals only. No switching. Expedite. |
| 1/2 | Crack Limited | Fast | 3 coaches † | Stop at Terminals only. No switching. Expedite. |
| 3/4 | Express | Fast | 2 freight | May drop or pick up one freight car at every location. Expedite. |
| 5/6 | The Sparrow | Fast | 2 coaches | No switching. Expedite. |
| 5/6 | The Sparrow | Fast | 2 coaches † | No switching. Expedite. |
| 7/8 | Local | Slow | 1 freight + 1 coach | Coach must remain on station track if switching. |
| 9/10 | Heavy Freight | Slow | 3 freight + caboose | |
| 11/12 | Drag Freight | Slow | 2 freight + caboose | |
† **The two coach counts have since been swapped by Jesse** (Gitea#7, 2026-08-22): the Crack Limited
now carries **2** coaches and The Sparrow **3**. The table above is left as `Trains3.pdf` prints it,
because that is what this section is for — what the design SAYS. What the game plays is
`src/engine/content.ts`, with the per-card table in
[`../StationMaster-Home-Deck-v0.4.5.md`](../StationMaster-Home-Deck-v0.4.5.md).
### Extras (X13–X22) — ten distinct trains, not four generic ones
Appleseed Extra (MT freight only, may drop but not pick up), Fruit Growers Express (reefers only),
@@ -783,3 +789,153 @@ Crossing is counted in Stages (Q1), so both trains simply run their counters dow
Until this is settled the clearance buttons describe only what the engine actually does — they say
the train "closes up behind" rather than promising a −5 risk that cannot occur. Wording that invents
a consequence is worse than wording that under-sells one.
---
## §7 — where an Extra starts, and which way it runs
**Reported from playing v0.4.9e** (Gitea#4): "When extras are played the player doing so may choose
where the extra starts. They may choose either division point. And if the interchange mainline card
has been played, they may start the extra on that card and choose the direction from there. If there
is potential for conflict with other trains in that area the superintendent may hold the extra."
**This supersedes an earlier ruling**, and the supersession is the interesting part. §2.3 gives every
train its direction from its number — odd runs west, even runs east — and an earlier pass extended
that to Extras explicitly: *"the number decides, like everything else on the timetable."* That reading
cannot survive "either Division Point". An odd Extra placed at the WEST end would run west, leave the
Division on its first move having crossed nothing, and be paid the completion Revenue for the run.
So for **Extras only**, the start decides the direction:
| Start | Direction |
| --- | --- |
| Western Division Point | east |
| Eastern Division Point | west |
| Interchange | player's choice |
| Control Point (any Office above a Whistle Post) | player's choice |
A timetabled train is unchanged: its number still decides. The Extra cards were always printed
`direction: 'playerChoice'` (§5) and the engine had been overriding it; they now mean it.
### The Interchange start is a YARD, not a spot on the running line
§7's last clause — "the superintendent may hold the extra" — is what settles how this is modelled.
An Extra started at an Interchange stands in that card's **yard**, off the running line, and highballs
onto the card itself at a later Mainline Phase. Three things follow, all of them Jesse's rule rather
than an implementation convenience:
1. **Placing it can never force a collision**, however busy the card is. It is not on the road yet.
2. **A guaranteed collision holds it in the yard** for another Stage, and it tries again next Stage.
3. **A potential collision is the Superintendent's to rule on.**
Those last two are exactly §8.1's two answers — an absolute bar against a facing train, a judgment
call against a following one — so the Extra leaves the yard through the same clearance check a train
leaves a Division Point through. Nothing new decides collisions.
The Interchange keeps its printed "sort cars in new order" concept, still unimplemented (§6). Being
the card with a Yard Limit is what makes it the one Mainline card a train can be made up on.
### Which starts are offered is a setting
The Division Points and the Interchange sit on shared ground and belong to nobody; starting an Extra
inside a player's own district does not. That is a table preference rather than a rule, so it is set
when the game is dealt (`extraStart`): Division Points and Interchange only, plus the playing
player's own Control Point, or plus any player's Control Point. A **Whistle Post never qualifies at
any setting** — being a place an Extra can start is part of what upgrading buys (§11).
### Two bugs found underneath it
- **The Mainline cards were rolled, not dealt.** `buildDivision` drew uniformly from the nine card
TYPES **with replacement**, so a Division could be dealt two Interchanges or two Tunnels, and
Plains — printed twice in the deck — carried the same weight as cards printed once.
`docs/StationMaster-Mainline-Deck-v0.4.5.md` had already flagged the mismatch as needing
correction; "an Extra may start at the Interchange if one is on the board" is what forced it, since
that only reads as a rule if the board holds at most one. Now dealt from the printed ten-card deck
without replacement.
- **An Extra started anywhere but a Division Point ran empty.** `isBeingMadeUp` asked only "is this
tray standing at a Division Point", which was the whole truth while that was the only place to
build a train — so the Control Point start had shipped since it was added with a train that could
never be given a consist, and the Interchange start would have shipped the same way. Found by
playing it, not by the tests, which had only ever asserted where the tray landed.
---
## §6.2 — which train cards may be discarded
**SUPERSEDED ONCE. Read both rulings; the second narrows the first.**
**Gitea#6, v0.4.9e playtest:** "Players are not allowed to discard Train cards. They may keep the
card in their hand for multiple stages and even multiple days, but they may not discard it. If a
player has three train cards in their hand, and they draw a fourth, then they must play one of those
cards." Extras counted: an Extra is a train.
**Gitea#9, 2026-08-24 — the ruling in force:** "Timetabled trains are at the choice of the player:
they can either play or discard. If someone else wants to pick it up, they are more than able to.
The reason: I don't want, if you decide to play a game longer than five days, to decide that maybe
there are too many trains, the stations are jammed, and the railroad doesn't need any more. You can
toss it. Someone else might disagree and pick it up."
So the rule is now:
- a **Timetabled** train may be discarded;
- an **Extra** may not. It never joins the timetable, so it can never be what jams it, and the only
rule it would dodge by being thrown away is the hand limit;
- **on `main` the Timetabled half is a New Game setting** (`discardTimetabled`, on by default),
because Jesse's reasoning is explicitly about LONG games and a five-Day game may well want
Gitea#6's pressure. The 0.4.9 playtest line has no scaffolding for a setting and takes the plain
rule. Both lines behave identically at their defaults.
**"Someone else might disagree and pick it up" needed no machinery.** A discard already goes face-up
onto a Department pile, and a Department pile is exactly what a rival draws from. The second half of
the ruling was already built; only the first half was a change.
§6.2 as transcribed says only "the player must reduce his hand to no more than three cards" with no
exception for any card type, so both of these are rulings rather than gaps — the prototype rules do
not address it either way.
### It needs no forcing mechanism, and that is the point
The interesting property of the rule is that the forced play falls out of two rules that already
exist rather than needing a third:
1. an undiscardable card is not among the ways to shed a card; and
2. `draw.end` already refuses while the hand is over the limit (§6.2).
A player holding four undiscardable trains therefore has exactly one legal way to conclude the turn —
play one — without anything in the engine ever computing "you must play a train". The corner cannot
lock a player in, because **playing a train card is unconditionally legal**: `card.play`'s train case
refuses only a board placement, and a train card played when the timetable is full still leaves the
hand (it simply schedules nothing). Confirmed by playing it: such a hand offers zero discards, no
`draw.end`, and four plays.
**Gitea#9 does not retire that corner, it narrows the way in.** With the setting on, the only hand
that reaches it is four Extras; with the setting off it is any four trains, exactly as before.
### One place decides, and the card says which rule refused
`keepReason` (`src/engine/apply.ts`) returns the sentence a player should read, or `null` if the card
may be discarded. `check`, the hand panel and the blocked "End Local Operations" button all ask it,
so none of them can drift from the rule. It returns a SENTENCE rather than a boolean because there
are now two distinct reasons — "an Extra is never discarded" and "not in this game" — and a panel
that hard-codes one of them tells half the players the wrong thing. It reaches the page as the
Frame's `handKeepWhy`.
The bot needed no rule of its own either. `legal.ts` enumerates candidates and filters them through
`check`, so the option stops being offered; and the developer bot already reaches for `card.play`
before it reaches for a discard. Measured over 400 games: 400/400 finished, revenue unmoved, and
**trains scheduled 1.2 → 1.3** — the rule's intended effect, small because a bot rarely held four.
### Consequences
- **Two of the three published replays discarded train cards** (2 and 15 of them) and were retired
and re-recorded. Jesse's call: "I'm okay with retiring the replays that no longer work under those
old rules."
- **The opening six-card hand is not exempt.** Under *six random cards* a player opens holding six
against a limit of three; if four or more are trains, they all go onto the timetable on turn one.
Jesse's call: "If the opening hand has lots of trains, then lots of trains will be placed on the
board." Rare — roughly 1.5% of deals — but deliberate.
- **The player is told, on the card and on the button.** `handDiscardable` on the Frame marks which
cards may be shed, the hand panel says so in the card's own tooltip, and when EVERY card held is a
train the blocked end-turn button changes its text to say a train must be played. That is the
Gitea#2 lesson applied: a rule the player cannot see is a board with nothing to click and no reason
given.
+33 -2
View File
@@ -28,6 +28,7 @@ left open, with the consequence noted.
| 11 | Track card orientation | **SUPERSEDED** — handedness is printed; both hands supplied |
| 12 | Balance targets | **INVALIDATED** — measured against a placeholder ruleset |
| 13 | Deck scaling by player count | **LARGELY DISSOLVED** — track is per-player by design |
| 14 | Two routes to the same square | **DECIDED** |
---
@@ -669,10 +670,15 @@ balance work was possible.
| --- | --- | --- | ---: | ---: | ---: | ---: |
| Mine Tipple | Hopper | Outbound | 3 | 3 | — | 4 |
| Produce Shed | Reefer | Outbound | 2 | 2 | — | 3 |
| Grocer's Warehouse | Boxcar | Both | 2 | 2 | 2 | 3 |
| Oil Refinery | Tank | Both | 3 | 2 | 2 | 4 |
| Grocer's Warehouse | Boxcar | Inbound | 2 | — | 2 | 3 |
| Oil Refinery | Tank | Outbound | 3 | 2 | — | 4 |
| Power Plant | Hopper | Inbound | 3 | — | 3 | 4 |
*Amended v0.4.9e.* The warehouse and the refinery were briefly "Both", on the reading that "Freight
House" was a collective term for exactly those two and therefore what §9.3's "permit cars to move
each direction" described. The Freight House turned out to be a card of its own (v0.5.0), and
playtesting confirmed the one-way reading the sheet always printed.
*Rationale.* Directions follow the commodity and give §9 all three of its stated cases. Bulk
industries get more Laborers and a 4-car track so the types feel distinct when choosing what to
build — but the counts stay moderate because Laborers are **not** the binding constraint (see 10e),
@@ -1003,3 +1009,28 @@ needs to get started, while giving each player material to build with.
**Not yet decided**, because it interacts with Gap 12's variance question: more facilities per player
would raise the ceiling on the runaway mode as well as the floor.
## Gap 14 — Two routes to the same square
**Status:** DECIDED.
**Reported by Jesse:** "There are times when a train can take two different paths to get to a
destination. See game at undo 379. Train 11 can go from Eastern limits to the straight at 1,1 two
different ways. It can go through the refinery and pick up the tanker on its nose, or it could go
straight and then make the curve and skip the refinery and not pick up the car. The player should
have the two different options."
**The question:** a passing loop — turnout off the main, curve down, industry, curve back up — offers
two legal routes between the same two squares, and they couple different cars. Does §A.4's "you may
not go around" a car standing on your track forbid taking the bypass?
**Ruling: the player may choose the path.** Different paths may pick up different cars, or none.
§A.4 says "cars **on your track**", and the industry spur is a different track — declining to enter
it is not going around the car standing on it, it is not going to that car's track at all, which is
ordinary railroading. The mandatory half still bites in full once a route is chosen: every car
standing on the chosen route couples, and there is no route that passes a car and leaves it.
**Built in v0.4.8** — see `docs/plans/switching-paths.md`. The engine enumerates every distinct
simple route, dedupes by outcome (destination, entry side, and origin-tagged cars) rather than by
destination alone, and an intent that would otherwise be ambiguous carries a `via` naming one
intermediate square on the chosen route.
+18 -6
View File
@@ -593,10 +593,16 @@ horizontal row through the Office, Limit-to-Limit; everything else is Secondary
- Plain track, turnouts and Facility cards are all played from hand into an empty adjacent grid spot,
and **must connect to existing track**. Facility cards carry their own rails — placing a Facility
places track.
- Track stays **inside the Limits at every row**, not only on the Running Track. §2.1 makes the sign
"the limit of your control area" and §3 defines Secondary Track as "all tracks in your limits", so
a siding may run *under* a sign — the sign stands on the boundary — and never past it. Widening a
district therefore means extending the main first.
- Extending the **Running Track** horizontally moves that player's Limits sign outward with it (§2.1).
Growth is uncapped in the prototype.
- Modifier Facility cards are not track. They are placed adjacent to a Facility, on any of the nine
nearby spots (§9).
nearby spots (§9) — diagonals included, and not bounded by the Limits, since a host at the edge of
the district would otherwise have nowhere to put one. The one square they may not take is in the
Running Track's own row, which is where the main grows.
A longer Running Track is more track to keep clear of arriving trains, so territory carries its own
collision risk.
@@ -729,8 +735,8 @@ Modifier effects, and track geometries — is catalogued in
| --- | --- | --- | ---: | ---: | ---: | ---: |
| Mine Tipple | Hopper | Outbound | 3 | 3 | — | 4 |
| Produce Shed | Reefer | Outbound | 2 | 2 | — | 3 |
| Grocer's Warehouse | Boxcar | Both | 2 | 2 | 2 | 3 |
| Oil Refinery | Tank | Both | 3 | 2 | 2 | 4 |
| Grocer's Warehouse | Boxcar | Inbound | 2 | — | 2 | 3 |
| Oil Refinery | Tank | Outbound | 3 | 2 | — | 4 |
| Power Plant | Hopper | Inbound | 3 | — | 3 | 4 |
| Office | Porters | Green slots | Red slots |
@@ -747,8 +753,11 @@ Modifier effects, and track geometries — is catalogued in
| Extra Platform | +1 green and +1 red slot (passenger) |
| Section Gang | +1 Laborer or +1 Porter |
**"Freight House"** (§9.3, Appendix A) is not a card — it is the collective term for a freight
facility that both loads and unloads, namely the Grocer's Warehouse and the Oil Refinery.
**"Freight House"** (§9.3, Appendix A) is a Freight Facility card, dealt like any other industry —
this used to read "not a card, only the collective term for a facility that both loads and unloads",
which the engine never agreed with. It is the **only** industry that permits both directions: the
Grocer's Warehouse receives and the Oil Refinery ships, one way each (corrected v0.4.9e from gameplay
testing — the "Both" reading was the other half of the same mistake about what "Freight House" meant).
---
@@ -795,7 +804,10 @@ same order they originally held, left-to-right.
- The exception is your Office track, which has the number of A/D tracks listed (§11.1). As long as
fewer trains are holding there than A/D tracks, you may enter and pass through.
- If you move your Crew Tray into cars on your track, you **MUST** pick them up. You may not go around
them.
them. Where a passing loop offers two routes to the same square, choosing not to enter a siding is
not "going around" a car standing on it — that car is on a different track, and declining to run
onto it is ordinary railroading. Once a route is chosen, every car standing on it still must be
coupled in full.
- A Crew Tray must always have an engine, and may move a maximum of four Rolling Stock — cabooses
included **[Gap 4c]**.
- You automatically couple to cars you meet during your Moves. The same is **not** true of trains
-1
View File
@@ -1 +0,0 @@
../../../node_modules
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "station-master",
"version": "0.0.1",
"version": "0.4.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "station-master",
"version": "0.0.1",
"version": "0.4.8",
"devDependencies": {
"@types/node": "^26.1.2",
"typescript": "^7.0.2"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "station-master",
"version": "0.4.7",
"version": "0.4.9g",
"private": true,
"type": "module",
"description": "Station Master — a railroad operations game",
Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+12 -1
View File
@@ -10,7 +10,7 @@
*/
import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -151,6 +151,17 @@ if (existsSync(replaySrc)) {
}
writeFileSync(join(replayOut, 'manifest.json'), JSON.stringify(manifest, null, 1));
/**
* Static images — the splash artwork and whatever joins it. Copied verbatim, unlike the replays
* above: an image needs no validation, only a place in `dist/` to be served from.
*/
const imageSrc = join(root, 'public/images');
if (existsSync(imageSrc)) {
const imageOut = join(dist, 'images');
mkdirSync(imageOut, { recursive: true });
for (const f of readdirSync(imageSrc)) copyFileSync(join(imageSrc, f), join(imageOut, f));
}
// A tiny note for whoever unzips this later and wonders what it needs.
writeFileSync(
join(dist, 'README.txt'),
+96 -35
View File
@@ -1,11 +1,29 @@
/**
* Build the solitaire site and push it to a File Browser instance.
* Build the solitaire site and push it to a FileBrowser instance.
*
* Written against File Browser v2.63's REST API, read from its own bundle rather than guessed:
* REWRITTEN FOR **FileBrowser Quantum** (2026-08-23). The host was upgraded from File Browser v2.63
* to the Quantum fork, whose API is different in three ways at once, and every deploy failed with
* `login failed: 404 404 page not found` — the old `/api/login` simply is not there any more.
*
* POST /api/login {username, password, recaptcha} -> JWT as plain text
* POST /api/resources/<dir>/ X-Auth: <jwt> -> create a directory
* POST /api/resources/<file>?override=true X-Auth: <jwt>, body = bytes -> upload
* Read from the running instance's own bundle rather than guessed, the same way the v2.63 version
* was (`/public/static/assets/index-*.js`, gzipped — pipe it through `gunzip` before grepping), and
* each path confirmed against the live host by the response code: an endpoint that exists answers a
* bad password with **401**, one that does not answers **404**.
*
* POST /api/auth/login?username=<u>&recaptcha=
* headers X-Password: <urlencoded>, X-Secret: <otp or empty> -> sets a session COOKIE
* GET /api/settings/sources -> the named sources
* POST /api/resources?path=<p>&source=<s>&isDir=true -> create a directory
* POST /api/resources?path=<p>&source=<s>&override=true body=bytes -> upload
*
* THREE THINGS MOVED, and each would break on its own:
* 1. AUTH IS A COOKIE, not an `X-Auth: <jwt>` header. Login returns no usable token in its body;
* the session arrives in `Set-Cookie` and every later request has to carry it back.
* 2. THE PASSWORD IS A HEADER, `X-Password`, URL-encoded — not a JSON body field.
* 3. THE PATH IS A QUERY PARAMETER, `?path=`, not part of the URL, and every resource call also
* needs a **`source`** naming which configured store to write to. Quantum throws "no source
* provided" without it. `FB_SOURCE` names it; left unset, the sole configured source is used,
* and if there is more than one this stops and lists them rather than guessing.
*
* File Browser is the STORE, not the server — Start9 Pages serves the uploaded folder as the site.
* So the job here is simply to land the built files in the right folder, intact.
@@ -18,6 +36,8 @@
* Optional:
* FB_URL default https://phoenix.local:58157
* FB_DEST default websites/stationmaster — the folder Start9 Pages serves from
* FB_SOURCE which configured source to write to; discovered automatically when there is one
* FB_OTP the one-time code, if the account has two-factor enabled
* FB_INSECURE set to 1 for a self-signed certificate (usual for a .local StartOS host)
* SITE_URL default https://65.78.82.12:54697/ — the public address Start9 Pages serves at
* --dry-run list what would be sent, contact nothing
@@ -44,6 +64,8 @@ const URL_BASE = (process.env['FB_URL'] ?? 'https://phoenix.local:58157').replac
const DEST = `/${(process.env['FB_DEST'] ?? 'websites/stationmaster').replace(/^\/+|\/+$/g, '')}`;
const USER = process.env['FB_USER'] ?? '';
const PASS = process.env['FB_PASS'] ?? '';
const OTP = process.env['FB_OTP'] ?? '';
const SOURCE_ENV = process.env['FB_SOURCE'] ?? '';
const DRY = process.argv.includes('--dry-run');
/**
@@ -75,37 +97,80 @@ const CONTENT_TYPES: Record<string, string> = {
'.txt': 'text/plain',
};
/**
* Log in and return the session cookie every later request must carry.
*
* The password goes in a HEADER and URL-encoded, which is Quantum's own client does
* (`X-Password: encodeURIComponent(password)`). The body carries nothing useful on success — the
* session is in `Set-Cookie`, so a deploy that ignored the cookie would authenticate and then be
* rejected by every upload.
*/
async function login(): Promise<string> {
const res = await fetch(`${URL_BASE}/api/login`, {
const url = `${URL_BASE}/api/auth/login?username=${encodeURIComponent(USER)}&recaptcha=`;
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: USER, password: PASS, recaptcha: '' }),
headers: { 'X-Password': encodeURIComponent(PASS), 'X-Secret': OTP },
});
const body = await res.text();
if (!res.ok) throw new Error(`login failed: ${res.status} ${body || res.statusText}`);
if (!body.trim()) throw new Error('login returned an empty token');
return body.trim();
}
async function makeDir(jwt: string, path: string): Promise<void> {
// Trailing slash is what marks a directory in this API. A 409 means it already exists, which is
// the normal case on every deploy after the first.
const res = await fetch(`${URL_BASE}/api/resources${encodePath(path)}/`, {
method: 'POST',
headers: { 'X-Auth': jwt },
});
if (!res.ok && res.status !== 409) {
throw new Error(`could not create ${path}: ${res.status} ${await res.text()}`);
if (!res.ok) {
// 401 here is a wrong username/password; 404 would mean this build has moved the API again.
throw new Error(`login failed: ${res.status} ${body || res.statusText}`);
}
const cookies = res.headers.getSetCookie();
if (cookies.length === 0) throw new Error('login succeeded but set no session cookie');
return cookies.map((c) => c.split(';')[0]).join('; ');
}
async function upload(jwt: string, localPath: string, remotePath: string): Promise<void> {
/**
* WHICH STORE TO WRITE TO. Quantum can serve several named sources and refuses any resource call
* that does not name one ("no source provided"), which is the parameter the v2.63 API had no
* concept of. One configured source is the normal case and is used without asking; more than one is
* ambiguous, and guessing would silently deploy the site into the wrong store.
*/
async function resolveSource(cookie: string): Promise<string> {
if (SOURCE_ENV) return SOURCE_ENV;
const res = await fetch(`${URL_BASE}/api/settings/sources`, { headers: { cookie } });
if (!res.ok) throw new Error(`could not list sources: ${res.status} ${await res.text()}`);
const names = Object.keys((await res.json()) ?? {});
if (names.length === 1) return names[0]!;
if (names.length === 0) throw new Error('the server reports no sources at all');
throw new Error(`several sources configured (${names.join(', ')}) — pick one with FB_SOURCE=<name>`);
}
function resourceUrl(source: string, path: string, extra: Record<string, string>): string {
const params = new URLSearchParams({ path, source, ...extra });
return `${URL_BASE}/api/resources?${params}`;
}
async function makeDir(cookie: string, source: string, path: string): Promise<void> {
const res = await fetch(resourceUrl(source, path, { isDir: 'true' }), {
method: 'POST',
headers: { cookie },
});
if (res.ok) return;
/**
* "Already there" is the normal case on every deploy after the first, and Quantum is not
* consistent about which code it reports it with. So the two failures worth stopping for are
* named — a rejected session, and a server that broke — and every other 4xx is treated as the
* directory already existing. A directory that genuinely is not there fails loudly at the upload
* a moment later, which is a better place to find out than a guess here.
*/
const fatal = res.status === 401 || res.status === 403 || res.status >= 500;
if (fatal) throw new Error(`could not create ${path}: ${res.status} ${await res.text()}`);
}
async function upload(
cookie: string,
source: string,
localPath: string,
remotePath: string,
): Promise<void> {
const bytes = readFileSync(localPath);
const ext = remotePath.slice(remotePath.lastIndexOf('.'));
const res = await fetch(`${URL_BASE}/api/resources${encodePath(remotePath)}?override=true`, {
const res = await fetch(resourceUrl(source, remotePath, { override: 'true' }), {
method: 'POST',
headers: {
'X-Auth': jwt,
cookie,
'Content-Type': CONTENT_TYPES[ext] ?? 'application/octet-stream',
'Content-Length': String(bytes.byteLength),
},
@@ -114,11 +179,6 @@ async function upload(jwt: string, localPath: string, remotePath: string): Promi
if (!res.ok) throw new Error(`upload ${remotePath} failed: ${res.status} ${await res.text()}`);
}
/** Encode each segment but keep the separators, so a path stays a path. */
function encodePath(p: string): string {
return p.split('/').map(encodeURIComponent).join('/');
}
// ---------------------------------------------------------------------------
console.log('building…');
@@ -147,15 +207,16 @@ if (DRY) {
);
}
const jwt = await login();
console.log('logged in');
const cookie = await login();
const source = await resolveSource(cookie);
console.log(`logged in — writing to source "${source}"`);
await makeDir(jwt, DEST);
for (const d of dirs) await makeDir(jwt, `${DEST}/${d}`);
await makeDir(cookie, source, DEST);
for (const d of dirs) await makeDir(cookie, source, `${DEST}/${d}`);
let done = 0;
for (const f of files) {
await upload(jwt, join(dist, f), `${DEST}/${f}`);
await upload(cookie, source, join(dist, f), `${DEST}/${f}`);
done++;
console.log(` [${String(done).padStart(2)}/${files.length}] ${f}`);
}
+143 -94
View File
@@ -18,6 +18,7 @@
import {
COLLISION_PENALTY,
EXPEDITE_FAULT_PENALTY,
MAINLINE_PROFILES,
enhancementRule,
crossingStages,
@@ -40,7 +41,7 @@ import type { GameEvent } from './events.ts';
import { areaAtSeat, areaOf, trainNeedingCars } from './apply.ts';
import { legalActions } from './legal.ts';
import type { CrewTray, DivisionNode, GameState, PlayerIndex, RollingStock, SeatIndex, TrayId } from './state.ts';
import { coordKey, freshTurns, playerAtSeat, playerLeftOf, subdivisions, totalRevenue, turnOf } from './state.ts';
import { coordKey, freshTurns, playerAtSeat, playerLeftOf, pooled, subdivisions, totalRevenue, turnOf } from './state.ts';
export type AdvanceResult = {
events: GameEvent[];
@@ -307,6 +308,38 @@ function mainlinePhase(s: GameState, events: GameEvent[]): AdvanceResult {
return d !== 0 ? d : Number(a.trainIsExtra) - Number(b.trainIsExtra);
});
/**
* Q3 — A STATION MASTER FAULT: an expedited train not at the station when a Mainline Phase begins
* was not kept ready to highball, wherever in the district it has been left — switched onto
* Secondary Track to clear a move, say. Checked against positions as they stand BEFORE this phase
* moves anything, and charged every Phase it is still caught away: the fault is in leaving it
* there, not a one-time slip. A train the ordinary §8.1 rules are holding at the Office itself is
* unaffected — this only bites when the train is not even in the queue to leave.
*/
for (const [, tray] of order) {
if (!isExpedited(tray) || tray.position.at !== 'grid') continue;
const area = areaAtSeat(s, tray.position.seat);
const { coord } = tray.position;
if (coord.row === area.officeCoord.row && coord.col === area.officeCoord.col) continue;
const owner = playerAtSeat(s, tray.position.seat);
const p = s.players[owner];
if (!p) continue;
p.revenue -= EXPEDITE_FAULT_PENALTY;
events.push({
type: 'expediteFault',
player: owner,
trainNumber: tray.trainNumber ?? 0,
where: `(${coord.col},${coord.row})`,
});
events.push({
type: 'revenueChanged',
player: owner,
delta: -EXPEDITE_FAULT_PENALTY,
total: p.revenue,
reason: 'expedited train left off the station',
});
}
for (const [id, tray] of order) {
if (s.movedThisPhase.has(id)) continue;
const where = tray.position;
@@ -329,13 +362,13 @@ function mainlinePhase(s: GameState, events: GameEvent[]): AdvanceResult {
(tray.position.at !== 'grid' ||
where.at !== 'grid' ||
(tray.position.coord.row === where.coord.row && tray.position.coord.col === where.coord.col));
if (!tray.departsThisStage && stillThere) {
if (stillThere) {
tray.stopPointClaimed = true;
// The point goes to whoever is SITTING in the district it stopped in.
const owner = tray.position.at === 'grid' ? playerAtSeat(s, tray.position.seat) : 0;
const label =
tray.position.at === 'grid'
? `(${tray.position.coord.row},${tray.position.coord.col})`
? `(${tray.position.coord.col},${tray.position.coord.row})`
: tray.position.at === 'mainline'
? `Mainline card ${tray.position.index}`
: `the ${tray.position.side} Division Point`;
@@ -412,6 +445,9 @@ function enterMainline(
);
node.transits.push({ tray: id, stagesRemaining: stages, stagesTotal: stages, direction: tray.direction });
tray.position = { at: 'mainline', index };
// It is running now, so it is no longer being assembled (state.ts). A train at a Division Point
// needs no equivalent: leaving one changes its position, which is what that case reads.
delete tray.beingMadeUp;
/**
* OUT OF THE DISTRICT, AND THE SPUR PORT GOES WITH IT.
@@ -475,14 +511,18 @@ function spendDispatchBonus(
return 0;
}
/** Q3 — an expedited train does not spend a Stage standing at the Office. */
/**
* Does this train leave in the same Stage it arrives (§7)?
* Q3 — is this train subject to the "kept ready" fault (§7)?
*
* Expedite does not change WHEN a train leaves — it is released by the ordinary §8.1 rules like any
* other train, and may be switched normally while it stands. What it means is that it must not be
* held anywhere but the station: a train the player parks on Secondary Track to clear a switching
* move faults if it is not back on the Office square by the next Mainline Phase (`mainlinePhase`).
*
* Two ways to earn it. `expedite` is printed and permanent. `stopThenExpedite` is the X17 Campaign
* Train — "one turn at station (speeches) then expedite": its FIRST arrival is an ordinary stop while
* the speeches are made, and every arrival after that is expedited. `speechMade` is set on that first
* stop, so the train is slow once and fast thereafter.
* stop, so the train is exempt once and subject to the fault thereafter.
*/
function isExpedited(tray: CrewTray): boolean {
const rules = trainProfile(tray.trainNumber ?? 0, tray.trainIsExtra)?.rules;
@@ -491,18 +531,7 @@ function isExpedited(tray: CrewTray): boolean {
return rules.stopThenExpedite === true && tray.speechMade === true;
}
function moveTrain(
s: GameState,
id: TrayId,
tray: CrewTray,
events: GameEvent[],
/**
* Which pass is asking. The Mainline Phase moves every train once; Supervisor Shift then asks the
* Expedited arrivals to go again. The train cannot tell the difference, but the player must — see
* `trainHighballed.why`.
*/
pass: 'mainline' | 'expedite' = 'mainline',
): MoveOutcome {
function moveTrain(s: GameState, id: TrayId, tray: CrewTray, events: GameEvent[]): MoveOutcome {
const dir = step(tray.direction);
if (tray.position.at === 'divisionPoint') {
@@ -588,10 +617,7 @@ function moveTrain(
trainNumber: tray.trainNumber ?? 0,
from: 'the Office',
to: 'the Mainline',
why:
pass === 'expedite'
? 'its card prints EXPEDITE, so it leaves at the end of the Stage it arrived in — you got the Cargo phase with it, but no Local Operations turn to switch it'
: 'it stood a full Stage at the Office, so §8.1 released it this Mainline Phase',
why: 'it stood a full Stage at the Office, so §8.1 released it this Mainline Phase',
});
return 'moved';
}
@@ -619,6 +645,43 @@ function moveTrain(
const node = s.division.nodes[index];
if (!node || node.kind !== 'mainline') return 'held';
/**
* §7/§8.1 — AN EXTRA HIGHBALLING OUT OF THE INTERCHANGE'S YARD.
*
* Standing in `holding` rather than crossing in `transits` (state.ts), which is the position an
* Extra started at an Interchange begins in. It leaves exactly the way a train at a Division
* Point does — clearance first, then onto the running line — except that the card it enters is
* the one it is already standing beside rather than the next one along.
*
* That reuse is the whole point of modelling the yard separately: Jesse's rule is "a guaranteed
* collision holds it at the Interchange for another Stage and it tries again; a potential one is
* the Superintendent's to hold", and those are precisely `evaluateClearance`'s `blocked` and
* `ask`. Nothing new decides collisions here.
*/
if (node.holding?.includes(id)) {
const clearance = evaluateClearance(s, id, tray, index, events);
if (clearance === 'blocked') {
events.push({
type: 'trainHeld',
trainNumber: tray.trainNumber ?? 0,
reason: 'held in the Interchange — the Subdivision ahead is occupied',
});
return 'held';
}
if (clearance === 'ask') return 'needsClearance';
node.holding = node.holding.filter((t) => t !== id);
enterMainline(s, node, id, tray, index);
events.push({
type: 'trainHighballed',
trainNumber: tray.trainNumber ?? 0,
from: 'the Interchange',
to: 'the Mainline',
why: 'it was made up in the yard and the Subdivision was clear, so its run begins',
});
return 'moved';
}
const transit = node.transits.find((t) => t.tray === id);
if (!transit) return 'held';
@@ -751,28 +814,44 @@ function evaluateClearance(
for (const t of n.transits) if (t.tray) occupants.push({ tray: t.tray, onCard: i });
}
/**
* TWO PASSES, NOT ONE — an opposite-direction occupant is an absolute bar and has to be checked
* against EVERY occupant before any same-direction judgment call is offered.
*
* A single pass returned on whichever occupant it examined first, in `node.transits` insertion
* order — which is fine while a Subdivision holds at most one train, but the dispatch exception
* below means it now legitimately can hold two: a Telegraph-cleared facing train sits on the same
* card as whatever it was cleared past. Found from a playtest report where the Superintendent was
* asked to rule on a same-direction train instead of being auto-held against an uncleared
* opposite-direction one also on the card — the loop had reached the same-direction occupant
* first simply because it entered the transit list first, and returned before ever looking at
* the other.
*/
for (const { tray: other } of occupants) {
if (other === id) continue;
const otherTray = s.trays.get(other);
if (!otherTray || otherTray.direction === tray.direction) continue;
// §8.1 — a train moving TOWARDS the considered train is an absolute bar. That stands.
//
// The exception is dispatching technology. Telegraph/Telephone/Radio exist precisely so the
// Superintendent can arrange a meet with a facing train: "once a day, when dispatching
// facing trains, add +4/+8/+12 to the other train's number". Without a device there is no
// way to pass the order, so the train simply holds.
if (spendDispatchBonus(s, tray, otherTray, events) > 0) continue;
return 'blocked';
}
for (const { tray: other, onCard } of occupants) {
if (other === id) continue;
const otherTray = s.trays.get(other);
if (!otherTray) continue;
if (!otherTray || otherTray.direction !== tray.direction) continue;
const onNode = s.division.nodes[onCard];
if (otherTray.direction !== tray.direction) {
// §8.1 — a train moving TOWARDS the considered train is an absolute bar. That stands.
//
// The exception is dispatching technology. Telegraph/Telephone/Radio exist precisely so the
// Superintendent can arrange a meet with a facing train: "once a day, when dispatching
// facing trains, add +4/+8/+12 to the other train's number". Without a device there is no
// way to pass the order, so the train simply holds.
if (spendDispatchBonus(s, tray, otherTray, events) > 0) return 'clear';
return 'blocked';
}
// Red Flags — "a stopped train is prevented from being hit; the approaching train is prevented
// from moving". Flagging is per-train rather than per-card, so it protects one specific train
// where ABS Signals protects everything on the card.
//
// Both of these now read the card the OTHER train is standing on rather than the card being
// Both of these read the card the OTHER train is standing on rather than the card being
// entered. They were the same card while this only looked one card ahead; across a Subdivision
// they are not, and the protection belongs where the train it protects actually is.
if (onNode?.kind === 'mainline' && (onNode.redFlagged ?? []).includes(other)) return 'blocked';
@@ -871,27 +950,9 @@ function arriveAtOffice(
});
/**
* Q3 — AN EXPEDITED TRAIN DEPARTS THE STAGE IT ARRIVED, BUT NOT BEFORE THE WORK IS DONE.
*
* It used to leave inside this very Mainline Phase — a second `moveTrain` on the spot. That made
* "departs the Stage it arrives" true and the coaches worthless: Load/Unload runs AFTER Mainline,
* so an expedited train was gone before a single Porter could reach it. Measured over 60 games,
* Train 2 arrived 32 times and stood at an Office during Load/Unload exactly none of them, and
* every coach-carrying express is expedited (1/2 Crack Limited, 5/6 The Sparrow, 19 Military).
* The Crack Limited's own card says "stop at Terminals only", which it could never do.
*
* So it stands here through Load/Unload and leaves at the end of the Stage instead. It still does
* not lay over to the next Stage — the keyword is honoured — and it is still subject to every
* §8.1 condition when it goes, so it can be held.
*/
if (isExpedited(tray)) {
tray.departsThisStage = true;
return 'moved';
}
/**
* X17 Campaign Train — the speeches happen at the first Office it reaches. Recorded AFTER the
* expedite test above, so this arrival is the ordinary stop the card pays for and every later one
* runs expedited.
* X17 Campaign Train — the speeches happen at the first Office it reaches, and every arrival after
* that runs expedited (`isExpedited` reads `speechMade`). Setting it here is idempotent on every
* later arrival, so it needs no guard against re-firing.
*/
if (trainProfile(tray.trainNumber ?? 0, tray.trainIsExtra)?.rules.stopThenExpedite) {
tray.speechMade = true;
@@ -922,12 +983,33 @@ function collide(
consist: [...tray.consist],
});
// Gap 2c — engines and cabooses return to the Division Yard, everything else to Classification.
// `pooled` because a car reaching a yard is back in the common supply: the load's origin stamp
// (state.ts) belongs to the load, not to the car that happened to be carrying it.
for (const car of tray.consist) {
if (car.type === 'caboose') s.yards.divisionYard.push(car);
else s.yards.classificationYard.push(car);
if (car.type === 'caboose') s.yards.divisionYard.push(pooled(car));
else s.yards.classificationYard.push(pooled(car));
}
s.trays.delete(id);
s.freeTrays.push(id);
/**
* TAKE THE WRECK OFF THE CARD.
*
* Nothing did. `s.trays.delete` removed the train and left its `Transit` sitting on the Mainline
* card it died on, and `evaluateClearance` counts every transit as an occupant — so a rear-end
* collision (the caller at "ran into the train ahead") permanently poisoned that card: every
* later train was either held against a ghost or put to the Superintendent about one. The only
* other place a transit is removed is a train rolling off the far end, which a destroyed train
* never does.
*
* Found while adding the Interchange start, which clears onto the running line through that
* same occupant list.
*/
for (const n of s.division.nodes) {
if (n.kind !== 'mainline') continue;
n.transits = n.transits.filter((t) => t.tray !== id);
if (n.holding) n.holding = n.holding.filter((t) => t !== id);
if (n.redFlagged) n.redFlagged = n.redFlagged.filter((t) => t !== id);
}
}
if (lost.length > 0) {
@@ -993,9 +1075,10 @@ function retireTrain(
side: Direction,
events: GameEvent[],
): void {
// `pooled` — see `trainsDestroyed` above; a load's origin stamp does not survive the yard.
for (const car of tray.consist) {
if (car.type === 'caboose') s.yards.divisionYard.push(car);
else s.yards.classificationYard.push(car);
if (car.type === 'caboose') s.yards.divisionYard.push(pooled(car));
else s.yards.classificationYard.push(pooled(car));
}
s.trays.delete(id);
s.freeTrays.push(id);
@@ -1018,40 +1101,6 @@ function retireTrain(
// ---------------------------------------------------------------------------
function shiftChange(s: GameState, events: GameEvent[]): AdvanceResult {
/**
* EXPEDITED DEPARTURES — the last thing that happens in a Stage (Q3, and `arriveAtOffice`).
*
* Run here rather than as a phase of its own because there is no decision in it: the trains that
* arrived expedited this Stage try to leave, in train-number order like any other movement, and
* §8.1 may still hold them. Being after Load/Unload is the whole point — it is what gives the
* Porters their one Stage with the train.
*/
const expedited = [...s.trays.entries()]
.filter(([, t]) => t.departsThisStage)
.sort(([, a], [, b]) => (a.trainNumber ?? 0) - (b.trainNumber ?? 0));
for (const [id, tray] of expedited) {
tray.departsThisStage = false;
/**
* An expedited train that would need a §8.1 ruling STAYS, and runs normally from then on.
*
* Said in the log, because it is the difference between "this train leaves at the end of the
* Stage" and "this train is still here next turn", and a player watching one Expedited train
* vanish and the next one linger has no way to tell why. Measured on one seed: with ordinary
* traffic running, Train 6 was held this way and collected four Local Operations turns.
*/
if (moveTrain(s, id, tray, events, 'expedite') === 'needsClearance') {
events.push({
type: 'trainHeld',
trainNumber: tray.trainNumber ?? 0,
reason:
'it EXPEDITES and was due out at the end of this Stage, but the Subdivision ahead needs a ' +
'clearance ruling and Supervisor Shift has no Superintendent to give one. It stays, and ' +
'runs like an ordinary train from now on — so you DO get a Local Operations turn with it',
});
continue;
}
}
// §5 — the Fedora passes every three Stages: shift changes at Stages 3, 6, 9 and 12.
if (s.clock.stage % STAGES_PER_SHIFT === 0) {
s.clock.superintendent = playerLeftOf(s, s.clock.superintendent);
+458 -127
View File
@@ -33,9 +33,9 @@ import {
officeProfile,
trainProfile,
} from './content.ts';
import type { CarType, FreightKind, Hand, MainlineKind, ModifierKind, ModifierProfile, TrackGeometry, TrainRules } from './content.ts';
import type { CarType, Direction, FreightKind, Hand, MainlineKind, ModifierKind, ModifierProfile, TrackGeometry, TrainRules } from './content.ts';
import type { GameEvent } from './events.ts';
import type { Intent, RejectionCode } from './intents.ts';
import type { ExtraStart, Intent, RejectionCode } from './intents.ts';
import type {
CardId,
CrewTray,
@@ -59,6 +59,7 @@ import {
cutTowards,
isOperationalRail,
playerAtSeat,
pooled,
railFacingOf,
seatOf,
spaceOn,
@@ -66,7 +67,7 @@ import {
trackOrder,
turnOf,
} from './state.ts';
import type { MoveBlock, Occupancy, Port } from './track.ts';
import type { MoveBlock, MoveDestination, Occupancy, Port } from './track.ts';
import {
canDropCarsAt,
canPlaceAt,
@@ -77,6 +78,7 @@ import {
opposite,
reachableDestinations,
variantsFor,
withinLimits,
} from './track.ts';
export type ApplyResult =
@@ -387,17 +389,11 @@ export function canStartLoad(f: Facility): boolean {
}
/** §9.2 — boarding needs a loaded coach in a green slot and a train with an empty coach. */
export function canBoard(s: GameState, player: PlayerIndex, at: GridCoord): boolean {
export function canBoard(s: GameState, player: PlayerIndex, at: GridCoord, trayId?: TrayId): boolean {
const f = facilityAt(s, player, at);
if (!f || f.kind !== 'passenger' || portersLeft(f) < 1) return false;
if (!f.outboundBox.some((c) => c.type === 'coach' && c.loaded)) return false;
// §7 — a train whose card refuses passenger work, or which is not booked to stop here, is not a
// train these passengers can board however many empty coaches it is carrying.
return trainAtOfficeWith(
s, player,
(c) => c.type === 'coach' && !c.loaded,
(t) => !refusesPassengers(t) && !refusesThisOffice(s, player, t),
);
return passengerWork(s, player, 'board', trayId) !== null;
}
/**
@@ -412,29 +408,159 @@ export function canBoard(s: GameState, player: PlayerIndex, at: GridCoord): bool
* de-training MINTED a coach: the loaded one went to the red box and a new empty one appeared in the
* train. Measured at 1.29 cars a game created out of nothing across the two inbound paths.
*/
export function canDetrain(s: GameState, player: PlayerIndex, at: GridCoord): boolean {
export function canDetrain(s: GameState, player: PlayerIndex, at: GridCoord, trayId?: TrayId): boolean {
const f = facilityAt(s, player, at);
if (!f || f.kind !== 'passenger' || portersLeft(f) < 1) return false;
if (f.inboundBox.length >= f.capacity.inbound) return false;
if (!s.yards.divisionYard.some((c) => c.type === 'coach' && !c.loaded)) return false;
return trainAtOfficeWith(
s, player,
(c) => c.type === 'coach' && c.loaded,
(t) => !refusesPassengers(t) && !refusesThisOffice(s, player, t),
);
return passengerWork(s, player, 'detrain', trayId) !== null;
}
function trainAtOfficeWith(
/**
* A Timetabled or Extra train card (§6.2) — the one place that decides what "a train card" means.
*/
export function isTrainCard(s: GameState, cardId: CardId): boolean {
const kind = s.cards.get(cardId)?.kind.kind;
return kind === 'timetabledTrain' || kind === 'extraTrain';
}
/**
* WHY THIS CARD CANNOT BE THROWN AWAY, or `null` if it can (§6.2, Gitea#9 superseding Gitea#6).
*
* The one place that answers the question, so `check`, the hand panel and the blocked "End Local
* Operations" button all give the same reason rather than three hand-written approximations of it.
* Gitea#6 made every train card unconditionally undiscardable; Gitea#9 narrows that:
*
* - a TIMETABLED train is discardable unless the `discardTimetabled` house rule is off. Jesse's
* reasoning is about a long game whose timetable has filled up — "the stations are jammed and
* the railroad doesn't need any more. You can toss it";
* - an EXTRA is never discardable. It never joins the timetable, so it cannot jam it, and the
* rule it would otherwise dodge is the hand limit.
*
* Returns the sentence rather than a code because it is written for a player, and the two cases
* fail for genuinely different reasons — "not in this game" and "not ever".
*/
export function keepReason(s: GameState, cardId: CardId): string | null {
const kind = s.cards.get(cardId)?.kind.kind;
if (kind === 'extraTrain') {
return 'An Extra is never discarded. It runs once and ends in the Salvage Yard, so it can only ' +
'be played — hold it for as many Stages and Days as you like.';
}
if (kind === 'timetabledTrain' && !houseRules(s.config).discardTimetabled) {
return 'A train card is never discarded in this game. The only way it leaves your hand is onto ' +
'the timetable — hold it for as many Stages and Days as you like.';
}
return null;
}
/**
* WHERE AN EXTRA STARTS AND WHICH WAY IT RUNS — the one answer `check`, `execute` and the reducer
* all use, so a placement can never be checked against one square and made on another.
*
* §7 lets the player who played the card choose the start, and Jesse's ruling makes the start
* decide the direction rather than the number (`runDirection`'s comment carries the supersession):
*
* - a DIVISION POINT runs the train away from itself — the west end runs east, the east end west.
* `direction` on the intent is ignored rather than refused, because there is only one answer;
* - an INTERCHANGE or a CONTROL POINT sits in the middle of the railroad, where both ways are real
* runs, so the intent must say which.
*
* Which of those are on offer is the `extraStart` house rule. The two that belong to nobody — the
* Division Points and the Interchange — are always available; an Office is a seat's own ground and
* is gated, to `ownOffice` (the player who played the card) or `anyOffice`.
*
* Returns a refusal code rather than throwing, so `check` can hand it straight back.
*/
export function resolveExtraStart(
s: GameState,
player: PlayerIndex,
pred: (c: RollingStock) => boolean,
trayOk: (t: CrewTray) => boolean = () => true,
): boolean {
i: { trainNumber: number; atSeat?: SeatIndex | null; start?: ExtraStart; direction?: Direction },
): { at: ExtraStart; direction: Direction } | RejectionCode {
/**
* A save written before the choice existed. `atSeat` null meant the Division Point the NUMBER
* sent the train to, a seat meant that Office, and both ran in the number's direction — so that
* is what these replay as, whatever the rules say today.
*/
if (!i.start) {
const direction = runDirection(i.trainNumber);
if (i.atSeat === null || i.atSeat === undefined) {
return { at: { kind: 'divisionPoint', side: startingDivisionPoint(i.trainNumber) }, direction };
}
return { at: { kind: 'office', seat: i.atSeat }, direction };
}
const start = i.start;
if (start.kind === 'divisionPoint') {
if (!s.division.nodes.some((n) => n.kind === 'divisionPoint' && n.side === start.side)) {
return 'NO_SUCH_DIVISION_POINT';
}
// Away from the end it is standing at. Nothing else is a run.
return { at: start, direction: start.side === 'west' ? 'east' : 'west' };
}
if (i.direction === undefined) return 'NO_DIRECTION_CHOSEN';
if (start.kind === 'mainline') {
const node = s.division.nodes[start.node];
if (!node || node.kind !== 'mainline') return 'NO_SUCH_CARD';
// The Interchange is the one Mainline card an Extra may be made up on — it is the one with a
// yard. `sortsCars` is what the card prints and the only thing that distinguishes it.
if (!mainlineProfile(node.card).sortsCars) return 'NOT_AN_INTERCHANGE';
return { at: start, direction: i.direction };
}
const rule = houseRules(s.config).extraStart;
if (rule === 'divisionPointsOnly') return 'OFFICE_STARTS_NOT_ALLOWED';
if (rule === 'ownOffice' && start.seat !== seatOf(s, player)) return 'NOT_YOUR_OFFICE';
const area = s.officeAreas.get(start.seat);
if (!area) return 'NO_SUCH_FACILITY';
// A Control Point is any Office above a Whistle Post (§8). A Whistle Post is not one, which is
// the whole reason upgrading buys a place for an Extra to start — and no setting of the house
// rule lets one in.
if (!officeProfile(area.tier).isControlPoint) return 'NOT_A_CONTROL_POINT';
return { at: start, direction: i.direction };
}
/**
* WHICH TRAIN, AND WHICH COACH ON IT — the one answer `check`, `execute` and the reducer all use.
*
* TWO PLAYTEST BUGS SHARED ONE CAUSE HERE. Reported against v0.4.9d: "operating two trains in a
* station, the select button does not work — regardless of which you pick, it is always one train,
* not the other". `porter.board` carried no tray at all, so `check` asked whether SOME train at the
* Office had an empty coach and the reducer then walked `adOccupancy` and filled the first one it
* found. The two were not even asking the same question: `check` skipped a train whose card refuses
* passenger work and the reducer did not, so a Military train could be boarded as long as some other
* train at the platform was eligible. The intent now names its tray (`intents.ts`) and this is the
* one place that resolves it.
*
* And "passengers just boarded cannot be immediately unloaded": a coach carries the district that
* filled it (`RollingStock.origin`), and a homegrown coach is not a coach these passengers may
* alight from — they have to be carried to a different Office Area first.
*
* `trayId` absent means "any eligible train", which is what every intent recorded before this
* existed meant, so an old save replays unchanged.
*/
function passengerWork(
s: GameState,
player: PlayerIndex,
dir: 'board' | 'detrain',
trayId?: TrayId,
): { trayId: TrayId; coachIndex: number } | null {
const area = areaOf(s, player);
return area.adOccupancy.some((id) => {
const t = s.trays.get(id);
return !!t && trayOk(t) && t.consist.some(pred);
});
const seat = seatOf(s, player);
const wanted = (c: RollingStock): boolean =>
c.type === 'coach' && (dir === 'board' ? !c.loaded : c.loaded && c.origin !== seat);
for (const id of area.adOccupancy) {
if (trayId !== undefined && id !== trayId) continue;
const tray = s.trays.get(id);
if (!tray) continue;
// §7 — a train whose card refuses passenger work, or which is not booked to stop here, is not a
// train these passengers can board however many empty coaches it is carrying.
if (refusesPassengers(tray) || refusesThisOffice(s, player, tray)) continue;
const coachIndex = tray.consist.findIndex(wanted);
if (coachIndex >= 0) return { trayId: id, coachIndex };
}
return null;
}
// ---------------------------------------------------------------------------
@@ -465,6 +591,21 @@ function freightWorkedKey(trayId: TrayId, at: GridCoord): string {
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.
*
* `ROLLING_STOCK_SUPPLY` mints all six cabooses as `{ loaded: 6, empty: 0 }` because §2.2's
* "a coloured car is loaded, a white car is empty" is doing double duty there as a PIECE COUNT,
* and a caboose has no white version — there is no such thing as an empty one to make up a train
* from. Every other reading of `.loaded` in this file is already scoped to a coach or to a named
* car type, so the flag's second meaning only ever escaped here.
*
* Reported as Gitea#8: X22 Pee-Dee, whose whole card is "may only pick up MTs", could not couple a
* caboose at all — including the one it was made up with. Drop it and it was stranded, which made
* the train unplayable rather than merely restricted.
*/
const carriesLoad = (c: RollingStock): boolean => c.loaded && c.type !== 'caboose';
/**
* May this train work these freight cars on this square?
*
@@ -485,11 +626,14 @@ function freightBudgetLeft(
}
/**
* Whether a train may do switching work at all (§7).
* Whether a train may set out or sort cars (§7).
*
* Six cards print "no switching" — the two expresses, the Light Engine, the Campaign, Circus and
* Military trains. They run the Division; they do not shunt. This covers moving, setting out and
* sorting alike, because all three are switching.
* Military trains — which means they may not ADD or DROP cars, not that they may never be touched: a
* train held at the Office may still need to clear onto Secondary Track ahead of other traffic. So
* this covers `switch.dropCars` and `switch.sortConsist` only; `switch.move` handles `noSwitching`
* itself, the same way it handles `dropOnly`, because the restriction has to bite on the pick-up a
* move would make, not on the move itself.
*/
function switchingRefusal(tray: CrewTray): RejectionCode | null {
return rulesOf(tray).noSwitching ? 'NO_SWITCHING' : null;
@@ -561,17 +705,35 @@ function refusesThisOffice(s: GameState, player: PlayerIndex, tray: CrewTray): b
* this works out whether a card is the reason. Without it a Military train standing at the platform
* reported "no train at the Office", which is both wrong and unhelpful.
*/
function passengerRefusal(
export function passengerRefusal(
s: GameState,
player: PlayerIndex,
at: GridCoord,
dir: 'board' | 'detrain',
trayId?: TrayId,
): RejectionCode {
const area = areaOf(s, player);
const trains = area.adOccupancy.map((id) => s.trays.get(id)).filter((t): t is CrewTray => !!t);
const trains = area.adOccupancy
.filter((id) => trayId === undefined || id === trayId)
.map((id) => s.trays.get(id))
.filter((t): t is CrewTray => !!t);
if (trains.length > 0 && trains.every((t) => refusesThisOffice(s, player, t))) return 'NOT_A_TERMINAL';
if (trains.length > 0 && trains.every(refusesPassengers)) return 'NO_PASSENGER_WORK';
if (trains.length === 0) return 'NO_TRAIN_AT_OFFICE';
/**
* EVERY LOADED COACH ABOARD BOARDED HERE — so the refusal is the district rule, not "no loaded
* coach". Told apart because the two read as opposite situations to a player: one is an empty
* train, the other is a train full of passengers who have not been anywhere yet.
*/
if (
dir === 'detrain' &&
trains.some((t) => t.consist.some((c) => c.type === 'coach' && c.loaded)) &&
trains.every((t) =>
t.consist.every((c) => !(c.type === 'coach' && c.loaded) || c.origin === seatOf(s, player)),
)
) {
return 'LOADED_IN_THIS_DISTRICT';
}
/**
* A TRAIN IS STANDING THERE, so say what is actually missing.
@@ -625,12 +787,10 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
if (turnOf(s, player).movesRemaining < 1) return 'NO_MOVES_REMAINING';
const tray = s.trays.get(i.trayId);
if (!tray) return 'NO_SUCH_TRAY';
const noSwitch = switchingRefusal(tray);
if (noSwitch) return noSwitch;
const from = trayCoord(s, i.trayId);
if (!from) return 'ILLEGAL_MOVE';
const dests = destinationsFor(s, player, i.trayId, from, i.reverse);
const dest = dests.find((d) => d.coord.row === i.to.row && d.coord.col === i.to.col);
const dest = selectDestination(dests, i.to, i.via);
if (!dest) return 'ILLEGAL_MOVE';
/**
@@ -651,8 +811,16 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
*/
const fresh = dest.couples.slice(ownCutFor(s, player, i.trayId, i.reverse).length);
if (fresh.length > 0) {
/**
* "NO SWITCHING" MEANS NO ADDING OR DROPPING CARS, not "never move". A no-switching train
* held at the Office may still need to clear onto Secondary Track ahead of other traffic —
* §7 governs coupling, setting out and sorting, and a move that picks nothing up is none of
* those. Handled here, alongside `dropOnly`, rather than as a blanket refusal on the intent:
* the restriction has to bite on the pick-up itself, the same reasoning as the comment above.
*/
if (rules.noSwitching) return 'PICKUP_NOT_ALLOWED';
if (rules.dropOnly) return 'PICKUP_NOT_ALLOWED';
if (rules.pickUpEmptiesOnly && fresh.some((c) => c.loaded)) return 'EMPTIES_ONLY';
if (rules.pickUpEmptiesOnly && fresh.some(carriesLoad)) return 'EMPTIES_ONLY';
const freight = fresh.filter(isFreight).length;
if (freight > 0 && !freightBudgetLeft(s, player, tray, i.to, freight)) return 'FREIGHT_WORKED_HERE';
}
@@ -756,11 +924,30 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
return checkPlay(s, player, i.cardId, i.placement, i.variant, i.node);
}
/**
* §6.2 — WHICH TRAIN CARDS MAY BE THROWN AWAY (Gitea#9, superseding Gitea#6).
*
* `keepReason` holds the rule; this asks it. A Timetabled train is discardable unless the
* `discardTimetabled` house rule is off, and an Extra never is.
*
* WHERE THE DISCARD GOES IS THE OTHER HALF OF THE RULING. "If someone else wants to pick it up,
* they are more than able to" — a discard goes face-up on a Department pile, which is exactly
* where a rival can draw it from, so the second half needed no machinery at all.
*
* The corner Gitea#6 created still exists when the setting is off, and is still deliberate: a
* player holding four undiscardable trains has one way forward, which is to PLAY one. `draw.end`
* refuses while the hand is over the limit, and playing a train card is unconditionally legal
* (`card.play`'s `timetabledTrain` case refuses only a board placement), so it can never lock.
*
* `legal.ts` enumerates candidates and filters them through here, so an undiscardable card
* simply stops being offered; the bot needs no separate rule.
*/
case 'card.discard': {
if (!inPhase(s, 'localOps')) return 'WRONG_PHASE';
const hand = s.decks.hands.get(player) ?? [];
if (!hand.includes(i.cardId)) return 'CARD_NOT_IN_HAND';
if (i.toSlot < 0 || i.toSlot > 2) return 'SLOT_EMPTY';
if (keepReason(s, i.cardId) !== null) return 'TRAINS_ARE_NEVER_DISCARDED';
return null;
}
@@ -779,8 +966,9 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
if (rule.gradeOnly && mainlineProfile(node.card).speed.kind !== 'grade') return 'NOT_A_GRADE';
if (rule.requiresOnCard && !on.includes(rule.requiresOnCard)) return 'NOT_CONNECTED';
// "Not while a train is on it" — realigning under a moving train is exactly the situation the
// restriction exists to prevent.
if (node.transits.length > 0) return 'TRAIN_ON_CARD';
// restriction exists to prevent. A train standing in the Interchange's yard counts: it is on
// the card, and it is about to pull out onto the very rail being relaid.
if (node.transits.length > 0 || (node.holding?.length ?? 0) > 0) return 'TRAIN_ON_CARD';
if (rule.key === 'realignment' && !REALIGNMENTS.some((r) => r.from === node.card)) {
return 'NO_PLACEMENT';
}
@@ -907,12 +1095,16 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
if (!inPhase(s, 'newTrain')) return 'WRONG_PHASE';
if (!s.pendingExtras.includes(i.trainNumber)) return 'NO_EXTRA_PENDING';
if (s.freeTrays.length === 0) return 'NO_FREE_TRAY';
if (i.atSeat === null) return null;
// A Control Point is any Office above a Whistle Post (§8). A Whistle Post is not one, which is
// the whole reason upgrading buys a place for an Extra to start.
const area = s.officeAreas.get(i.atSeat);
if (!area) return 'NO_SUCH_FACILITY';
if (!officeProfile(area.tier).isControlPoint) return 'NOT_A_CONTROL_POINT';
const where = resolveExtraStart(s, player, i);
if (typeof where === 'string') return where;
if (where.at.kind === 'divisionPoint') return null;
if (where.at.kind === 'mainline') {
// Nothing to refuse. The train is made up in the Interchange's yard, off the running line,
// so however busy the card is this cannot be the collision §7 says it must not force. What
// it may not do is get OUT — that is §8.1's question, asked at the Mainline Phase.
return null;
}
const area = s.officeAreas.get(where.at.seat)!;
// It still has to fit: an Extra starting here takes an A/D track like any other arrival.
return area.adOccupancy.length >= officeProfile(area.tier).adTracks ? 'NO_FREE_AD_TRACK' : null;
}
@@ -972,7 +1164,8 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
if (!f) return 'NO_SUCH_FACILITY';
if (f.porters < 1) return 'NO_PORTERS_HERE';
if (portersLeft(f) < 1) return 'RESOURCE_SPENT';
return canBoard(s, player, i.at) ? null : passengerRefusal(s, player, i.at, 'board');
if (i.trayId !== undefined && !s.trays.has(i.trayId)) return 'NO_SUCH_TRAY';
return canBoard(s, player, i.at, i.trayId) ? null : passengerRefusal(s, player, i.at, 'board', i.trayId);
}
case 'porter.detrain': {
@@ -981,7 +1174,8 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
if (!f) return 'NO_SUCH_FACILITY';
if (f.porters < 1) return 'NO_PORTERS_HERE';
if (portersLeft(f) < 1) return 'RESOURCE_SPENT';
return canDetrain(s, player, i.at) ? null : passengerRefusal(s, player, i.at, 'detrain');
if (i.trayId !== undefined && !s.trays.has(i.trayId)) return 'NO_SUCH_TRAY';
return canDetrain(s, player, i.at, i.trayId) ? null : passengerRefusal(s, player, i.at, 'detrain', i.trayId);
}
case 'laborer.startLoad': {
@@ -1017,6 +1211,19 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
if (laborersLeft(f) < 1) return 'RESOURCE_SPENT';
const car = f.industryTrack.cars[i.carIndex];
if (!car || !car.loaded) return 'WRONG_CAR_TYPE';
/**
* A LOAD MAY NOT BE BROKEN IN THE DISTRICT THAT MADE IT (Jesse's ruling, v0.4.9e).
*
* Reported from playtesting v0.4.9d: "Freight House: boxcars loaded cannot be immediately
* unloaded." They could — a Freight House permits both directions, so the car its own Laborers
* had just loaded was standing on its own track, loaded, with an empty of that type in the
* yard, and every gate below said yes. Full Revenue at both ends for a load that never moved.
*
* The rule is district-wide and permanent, not "not at this facility" and not "not this
* Stage": the stamp says which Office Area made the load, and it never expires. Traffic runs
* BETWEEN districts, which is what the lockout pairs in `content.ts` exist to force.
*/
if (car.origin === seatOf(s, player)) return 'LOADED_IN_THIS_DISTRICT';
/**
* §9.3 — "*Requirements: a load on the industry's track AND AN EMPTY CAR OF THAT TYPE IN THE
* DIVISION YARD. The first Laborer replaces the load with an empty car of that type.*"
@@ -1105,6 +1312,9 @@ function checkPlay(
if (placement.row === area.runningRow && !carriesThroughTrack(proto)) {
return 'BREAKS_RUNNING_TRACK';
}
// Same reasoning: a siding reaching past your own sign JOINS perfectly well, and is refused
// because it leaves your territory (§2.1). `canPlaceAt` enforces it too — this only names it.
if (!withinLimits(area, placement)) return 'OUTSIDE_LIMITS';
return canPlaceAt(area, placement, proto) ? null : 'NOT_CONNECTED';
}
@@ -1123,6 +1333,10 @@ function checkPlay(
* main line.
*/
if (placement.row === area.runningRow) return 'ON_RUNNING_TRACK';
// A Facility CARRIES TRACK — "placing a Facility places track" (§11.2) — so it is bounded by
// the Limits exactly as a siding is. An industry outside them is how a district used to leave
// its own territory.
if (!withinLimits(area, placement)) return 'OUTSIDE_LIMITS';
// Q4 — a lockout prevents BUILDING both in one district: no duplicate, and never a producer
// alongside the consumer of the same commodity.
if (isLockedOut(area, card.kind.facility)) return 'FACILITY_LOCKED';
@@ -1133,6 +1347,18 @@ function checkPlay(
case 'modifier': {
if (!placement) return 'NO_PLACEMENT';
if (area.grid.has(coordKey(placement))) return 'NOT_CONNECTED';
/**
* NOT ON THE RUNNING TRACK ROW — AND NOT BOUNDED BY THE LIMITS EITHER. Jesse's call, both
* halves.
*
* A Modifier is not track (§9), so unlike a siding it may hang outside the Limits: a Facility
* standing at the limit has three of its nine spots out there, and refusing them would make
* the card unplayable exactly where the district ends. What it may NOT do is stand in the row
* the Running Track grows along. Inside the Limits that row is always full, so this bites only
* beyond the sign — which is the ground the main extends onto, and a Modifier parked there
* would block your own sign from moving outward (§2.1) with nothing on screen to warn you.
*/
if (placement.row === area.runningRow) return 'ON_RUNNING_TRACK';
// One of a kind per Office Area, as with industries (Q4) — no district gets two Ice Houses.
if (hasModifierInArea(area, card.kind.modifier)) return 'FACILITY_LOCKED';
// §9 — a Modifier is not track. It must sit adjacent to a Facility THAT CAN HOST IT (one of
@@ -1187,6 +1413,23 @@ function checkPlay(
}
}
/**
* Among destinations at `to`, the one `via` names — or the first `legal.ts` enumerated there, if
* `via` is absent or names no route on record. That fallback is what makes an old save (or any
* caller that never learned about routing) replay exactly as before: the first-enumerated route is
* the only one that ever existed until this feature did.
*/
export function selectDestination(
dests: MoveDestination[],
to: GridCoord,
via: GridCoord | undefined,
): MoveDestination | undefined {
const atTo = dests.filter((d) => d.coord.row === to.row && d.coord.col === to.col);
if (via === undefined) return atTo[0];
const chosen = atTo.find((d) => d.path.some((step) => step.coord.row === via.row && step.coord.col === via.col));
return chosen ?? atTo[0];
}
function destinationsFor(
s: GameState,
player: PlayerIndex,
@@ -1203,7 +1446,6 @@ function destinationsFor(
occupancy: occupancyFor(s, player, trayId),
consistSize: tray.consist.length,
self: trayId,
...(tray.standingWest === undefined ? {} : { standingWest: tray.standingWest }),
},
from,
exit,
@@ -1224,7 +1466,8 @@ export function ownCutFor(s: GameState, player: PlayerIndex, trayId: TrayId, rev
const here = tray.position.coord;
const facing = facingPort(s, trayId);
const exit: Port = reverse ? reversePort(s, player, here, facing) : facing;
return cutTowards(tray, carsOn(areaOf(s, player).grid.get(coordKey(here)) ?? emptyCard()), exit);
const card = areaOf(s, player).grid.get(coordKey(here)) ?? emptyCard();
return cutTowards(card, carsOn(card), exit);
}
/**
@@ -1250,7 +1493,6 @@ export function movesFor(
occupancy: occupancyFor(s, player, trayId),
consistSize: tray.consist.length,
self: trayId,
...(tray.standingWest === undefined ? {} : { standingWest: tray.standingWest }),
};
const facing = facingPort(s, trayId);
const forward = exploreMoves(ctx, from, facing);
@@ -1283,7 +1525,7 @@ function execute(s: GameState, player: PlayerIndex, i: Intent): GameEvent[] {
case 'switch.move': {
const from = trayCoord(s, i.trayId)!;
const dests = destinationsFor(s, player, i.trayId, from, i.reverse);
const dest = dests.find((d) => d.coord.row === i.to.row && d.coord.col === i.to.col)!;
const dest = selectDestination(dests, i.to, i.via)!;
const tray = s.trays.get(i.trayId)!;
// The port the crew pulls out THROUGH — the same one `destinationsFor` explored from, so the
// cut it recouples on the way out is the cut the walk counted.
@@ -1323,6 +1565,7 @@ function execute(s: GameState, player: PlayerIndex, i: Intent): GameEvent[] {
* Move on one (§A.1) — so there is exactly one way out of it.
*/
facing: i.reverse ? dest.entry : farPort(areaOf(s, player).grid.get(coordKey(i.to)), dest.entry),
...(i.via ? { via: i.via } : {}),
},
];
if (dest.couples.length > 0) {
@@ -1336,17 +1579,19 @@ function execute(s: GameState, player: PlayerIndex, i: Intent): GameEvent[] {
* from `dest.path` plus the destination, neither of which can ever contain the start — so a
* cut recoupled off your own card was added to the consist and left standing on the board at
* the same time, one car becoming two. The cars that stay behind (a cut set out off the
* OTHER end) ride along on `leaves`, because by the time this is reduced the tray has moved
* and `standingWest` no longer describes this card.
* OTHER end) ride along on `leaves`, computed here against the card's CURRENT split — the
* reducer applying this event goes on to zero `standingWest` on the destination card, never
* the origin, so nothing downstream needs this snapshot to have been taken any earlier.
*/
const grid = areaOf(s, player).grid;
const startCut = cutTowards(tray, carsOn(grid.get(coordKey(from)) ?? emptyCard()), exitPort);
const startCard = grid.get(coordKey(from)) ?? emptyCard();
const startCut = cutTowards(startCard, carsOn(startCard), exitPort);
const lifted = [
...(startCut.length > 0 ? [from] : []),
...dest.path.map((step) => step.coord),
i.to,
].filter((c) => carsOn(grid.get(coordKey(c)) ?? emptyCard()).length > 0);
const sides = standingSides(tray, carsOn(grid.get(coordKey(from)) ?? emptyCard()));
const sides = standingSides(startCard, carsOn(startCard));
const stayed = exitPort === 'e' ? sides.west : exitPort === 'w' ? sides.east : [];
// §A.3 — "engines also have couplers on the front end, so a train can pick cars up onto
// its nose". Running forward the engine meets cars head-on and takes them in front; backing
@@ -1537,8 +1782,13 @@ function execute(s: GameState, player: PlayerIndex, i: Intent): GameEvent[] {
return [{ type: 'facilityUnjammed', player, at: i.at, from: i.from, stock }];
}
case 'newTrain.startExtra':
return [{ type: 'extraStarted', player, trainNumber: i.trainNumber, atSeat: i.atSeat }];
case 'newTrain.startExtra': {
// `check` has already accepted this, so the resolve cannot fail here.
const where = resolveExtraStart(s, player, i) as { at: ExtraStart; direction: Direction };
return [
{ type: 'extraStarted', player, trainNumber: i.trainNumber, at: where.at, direction: where.direction },
];
}
case 'newTrain.placeCar':
return [
@@ -1570,17 +1820,23 @@ function execute(s: GameState, player: PlayerIndex, i: Intent): GameEvent[] {
* `passengerPerCoach` (`content.ts`). Half a passenger movement is half the work, and the rate
* is named per COACH because a Porter handles exactly one coach per action.
*/
case 'porter.board':
case 'porter.board': {
// `check` has already established there is one; resolving it HERE, once, is what stops the
// reducer from finding a different train than the one the rules were tested against.
const work = passengerWork(s, player, 'board', i.trayId)!;
return [
{ type: 'passengersBoarded', player, at: i.at },
{ type: 'passengersBoarded', player, at: i.at, ...work },
...earns(s, player, houseRules(s.config).revenue.passengerPerCoach, 'boarding'),
];
}
case 'porter.detrain':
case 'porter.detrain': {
const work = passengerWork(s, player, 'detrain', i.trayId)!;
return [
{ type: 'passengersDetrained', player, at: i.at },
{ type: 'passengersDetrained', player, at: i.at, ...work },
...earns(s, player, houseRules(s.config).revenue.passengerPerCoach, 'detraining'),
];
}
case 'laborer.startLoad': {
const f = facilityAt(s, player, i.at)!;
@@ -1615,7 +1871,13 @@ function execute(s: GameState, player: PlayerIndex, i: Intent): GameEvent[] {
case 'laborer.beginUnload': {
const f = facilityAt(s, player, i.at)!;
return [
{ type: 'unloadBegan', player, at: i.at, carType: f.industryTrack.cars[i.carIndex]!.type },
{
type: 'unloadBegan',
player,
at: i.at,
carType: f.industryTrack.cars[i.carIndex]!.type,
carIndex: i.carIndex,
},
];
}
@@ -1684,14 +1946,17 @@ export function reduce(s: GameState, e: GameEvent): void {
// their turn. The event carries no player of its own.
turnOf(s, playerAtSeat(s, seat)).movesRemaining = e.movesRemaining;
const area = areaAtSeat(s, seat);
// A MOVE ENDS ON AN EMPTY CARD, always: coupling is mandatory, so anything standing on the
// destination has just been lifted into the tray. Whatever this crew had beside it belonged to
// the square it left, so its place in that row is gone with it.
tray.standingWest = 0;
// destination has just been lifted into the tray. Zero the DESTINATION card's split — the
// origin's is left alone rather than cleared, which costs nothing: nothing reads `standingWest`
// on a card with no train standing there, so a stale value left behind is inert, not wrong.
const destCard = area.grid.get(coordKey(e.to));
if (destCard) destCard.standingWest = 0;
// An A/D track is held only while the train is actually standing at the Office (§2.1).
// Leaving it out of sync means the Office looks permanently full and every arrival collides.
const area = areaAtSeat(s, seat);
const atOffice =
e.to.row === area.officeCoord.row && e.to.col === area.officeCoord.col;
area.adOccupancy = area.adOccupancy.filter((t) => t !== e.trayId);
@@ -1739,9 +2004,9 @@ export function reduce(s: GameState, e: GameEvent): void {
const card = area.grid.get(coordKey(e.leaves.at));
if (card) carsOn(card).push(...e.leaves.stock.map((c) => ({ ...c })));
}
// A tray that has moved is standing on a card it has just emptied, so nothing of its own is
// left beside it. Any cut it did leave behind is on the square it came FROM.
tray.standingWest = 0;
// `trayMoved`, which always precedes this for the same move, already zeroed the destination
// card's `standingWest` — coupling is mandatory, so a tray that has just moved is standing on
// a card it has just emptied, and nothing of its own is left beside it there.
/**
* Charge only the cars that were ALREADY standing where the crew ran — the own cut at the
* front of `stock` is a drop being undone, so it is refunded on the square it was left on
@@ -1793,20 +2058,20 @@ export function reduce(s: GameState, e: GameEvent): void {
*
* Successive cuts off the same end stack up TOWARDS the engine — the first car set out is left
* furthest away, and each one after it is left in the gap between the train and the last —
* so the insertion point is the train's own position in the row, `standingWest`, from either
* side. That is what makes the result batch-invariant: four cars at once, four singles, or two
* pairs all park in the same order, which is the reported bug and the regression test.
* so the insertion point is the card's own `standingWest`, read against this train's side. That
* is what makes the result batch-invariant: four cars at once, four singles, or two pairs all
* park in the same order, which is the reported bug and the regression test.
*/
if (card) {
const cars = carsOn(card);
const facing = railFacingOf(tray);
const onWestSide = e.fromNose ? facing === 'w' : facing === 'e';
const k = Math.max(0, Math.min(cars.length, tray.standingWest ?? 0));
const k = Math.max(0, Math.min(cars.length, card.standingWest));
const cut = trackOrder(e.stock, facing);
cars.splice(k, 0, ...cut);
// The train has not moved, so cars set out on its WEST side push its index along the row;
// The train has not moved, so cars set out on its WEST side push the split along the row;
// cars set out to the east leave it where it was.
tray.standingWest = onWestSide ? k + cut.length : k;
card.standingWest = onWestSide ? k + cut.length : k;
}
spendFreightBudget(s, playerAtSeat(s, trayySeat(tray)), tray, e.at, e.stock);
break;
@@ -1863,9 +2128,10 @@ export function reduce(s: GameState, e: GameEvent): void {
geometry: { kind: 'modifier', modifier: card.kind.modifier },
baseOperationalRail: false,
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
enhancements: [],
});
applyModifier(area, e.placement, card.kind.modifier);
} else if (card.kind.kind !== 'office') {
@@ -1899,9 +2165,14 @@ export function reduce(s: GameState, e: GameEvent): void {
const card = area.grid.get(coordKey(e.to));
if (tray && card) {
tray.consist = tray.consist.slice(0, tray.consist.length - e.stock.length);
const track = card.facility?.industryTrack;
if (track) track.cars.push(...e.stock);
else card.standing.push(...e.stock);
// `carsOn` is the one function that knows WHERE cars stand on a given card — an industry
// track for a freight facility, the card itself for everything else. Written out longhand
// here it was a second copy of that rule, and the copy was wrong for a Passenger Facility:
// it has an `industryTrack` too (an empty one, `setup.ts`), so a cut pushed into an Office
// would have landed somewhere `carsOn` cannot see — cars on the board that no train can
// couple and no walk is blocked by. `check` refuses a non-freight target, so this never
// fired; a trap that needs another rule to stay unsprung is still a trap.
carsOn(card).push(...e.stock);
}
turnOf(s, e.player).movesRemaining -= 1;
spendCard(s, e.player, e.cardId);
@@ -1992,7 +2263,8 @@ export function reduce(s: GameState, e: GameEvent): void {
const f = facilityAt(s, e.player, e.at)!;
const idx = f.inboundBox.findIndex((c) => c.type === e.stock.type && c.loaded === e.stock.loaded);
if (idx >= 0) f.inboundBox.splice(idx, 1);
s.yards.classificationYard.push(e.stock);
// `pooled` — a car back in a yard is back in the common supply, carrying nothing (state.ts).
s.yards.classificationYard.push(pooled(e.stock));
turnOf(s, e.player).freightAgentUsed = true;
break;
}
@@ -2007,7 +2279,7 @@ export function reduce(s: GameState, e: GameEvent): void {
const idx = box.findIndex((c) => c.type === e.stock.type);
if (idx >= 0) box.splice(idx, 1);
}
s.yards.classificationYard.push(e.stock);
s.yards.classificationYard.push(pooled(e.stock));
turnOf(s, e.player).freightAgentUsed = true;
break;
}
@@ -2049,45 +2321,82 @@ export function reduce(s: GameState, e: GameEvent): void {
break;
}
/**
* THE THREE PLACES AN EXTRA MAY BE MADE UP (§7, Jesse's ruling) — and all three leave it
* STANDING somewhere it must later highball out of, never already running.
*/
case 'extraStarted': {
const trayId = s.freeTrays.pop()!;
s.pendingExtras = s.pendingExtras.filter((n) => n !== e.trainNumber);
const direction = runDirection(e.trainNumber);
if (e.atSeat === null) {
const side = startingDivisionPoint(e.trainNumber);
s.trays.set(trayId, {
id: trayId, trainNumber: e.trainNumber, trainIsExtra: true, engineAt: 0, consist: [],
direction, position: { at: 'divisionPoint', side }, movesUsed: 0,
});
const { direction } = e;
const base = {
id: trayId, trainNumber: e.trainNumber, trainIsExtra: true, engineAt: 0,
consist: [] as RollingStock[], direction, movesUsed: 0,
};
// Which way the tray physically points, for the cards it will pick up. A Division Point start
// does not set it: those trays have never carried a facing and `enterMainline` does not read
// one, so writing it here would be inventing state the DP path has always done without.
const facing = { facing: direction === 'west' ? ('w' as const) : ('e' as const),
railFacing: direction === 'west' ? ('w' as const) : ('e' as const) };
if (e.at.kind === 'divisionPoint') {
const side = e.at.side;
s.trays.set(trayId, { ...base, position: { at: 'divisionPoint', side } });
const dp = s.division.nodes.find((n) => n.kind === 'divisionPoint' && n.side === side);
if (dp?.kind === 'divisionPoint') dp.holding.push(trayId);
} else {
// Starting at a Control Point: it stands on the Office card and takes an A/D track, exactly
// as though it had arrived there.
const area = areaAtSeat(s, e.atSeat);
s.trays.set(trayId, {
id: trayId, trainNumber: e.trainNumber, trainIsExtra: true, engineAt: 0, consist: [],
direction, facing: direction === 'west' ? 'w' : 'e', railFacing: direction === 'west' ? 'w' : 'e',
position: { at: 'grid', seat: e.atSeat, coord: area.officeCoord }, movesUsed: 0,
});
area.adOccupancy.push(trayId);
break;
}
if (e.at.kind === 'mainline') {
/**
* IN THE INTERCHANGE'S YARD, NOT ON THE MAINLINE — the distinction §7 turns on.
*
* `holding` rather than `transits`, so the card can be nose to tail with traffic and this
* placement still forces no collision. It joins the running line at a later Mainline Phase
* through `evaluateClearance`, which is what gives the Superintendent the hold Jesse asked
* for: an automatic one against a facing train, a ruling against a following one.
*/
const node = s.division.nodes[e.at.node];
s.trays.set(trayId, {
...base, ...facing, beingMadeUp: true, position: { at: 'mainline', index: e.at.node },
});
if (node?.kind === 'mainline') (node.holding ??= []).push(trayId);
break;
}
// Starting at a Control Point: it stands on the Office card and takes an A/D track, exactly
// as though it had arrived there.
const area = areaAtSeat(s, e.at.seat);
s.trays.set(trayId, {
...base, ...facing, beingMadeUp: true,
position: { at: 'grid', seat: e.at.seat, coord: area.officeCoord },
});
area.adOccupancy.push(trayId);
break;
}
/**
* THE TRAIN AND THE COACH THE PLAYER PICKED, not "the first one on the A/D tracks".
*
* This used to walk `adOccupancy` and fill the first empty coach it met, which is why two trains
* standing at one station both answered to whichever chip was clicked (v0.4.9d playtest), and
* why it could fill a coach on a train whose card refuses passenger work — `check` skipped such
* a train and the reducer did not. `e.trayId`/`e.coachIndex` are exactly what `passengerWork`
* resolved for `check`, carried on the event rather than looked up again here.
*/
case 'passengersBoarded': {
const f = facilityAt(s, e.player, e.at)!;
const area = areaOf(s, e.player);
const idx = f.outboundBox.findIndex((c) => c.type === 'coach' && c.loaded);
const loaded = f.outboundBox.splice(idx, 1)[0]!;
for (const id of area.adOccupancy) {
const tray = s.trays.get(id);
const ci = tray?.consist.findIndex((c) => c.type === 'coach' && !c.loaded) ?? -1;
if (tray && ci >= 0) {
s.yards.classificationYard.push(tray.consist[ci]!);
tray.consist[ci] = loaded;
break;
}
const tray = s.trays.get(e.trayId);
if (tray && tray.consist[e.coachIndex]) {
s.yards.classificationYard.push(pooled(tray.consist[e.coachIndex]!));
/**
* Stamped with the district that filled it — the chip turned upside down in the tray. These
* passengers may not alight anywhere in this Office Area; the train has to carry them to a
* different one. See `RollingStock.origin` in state.ts.
*/
tray.consist[e.coachIndex] = { ...loaded, origin: seatOf(s, e.player) };
}
f.usedThisStage.porters += 1;
break;
@@ -2095,21 +2404,18 @@ export function reduce(s: GameState, e: GameEvent): void {
case 'passengersDetrained': {
const f = facilityAt(s, e.player, e.at)!;
const area = areaOf(s, e.player);
for (const id of area.adOccupancy) {
const tray = s.trays.get(id);
const ci = tray?.consist.findIndex((c) => c.type === 'coach' && c.loaded) ?? -1;
if (tray && ci >= 0) {
// The empty coach comes OUT OF THE DIVISION YARD, as §9.2 says. It used to be conjured,
// which minted a coach on every de-training. Throws now, for the reason in `unloadBegan`.
const yi = s.yards.divisionYard.findIndex((c) => c.type === 'coach' && !c.loaded);
if (yi < 0) throw new Error('passengersDetrained: no empty coach in the Division Yard');
const empty = s.yards.divisionYard.splice(yi, 1)[0]!;
refillDivisionYardIfEmpty(s);
f.inboundBox.push(tray.consist[ci]!);
tray.consist[ci] = empty;
break;
}
const tray = s.trays.get(e.trayId);
if (tray && tray.consist[e.coachIndex]) {
// The empty coach comes OUT OF THE DIVISION YARD, as §9.2 says. It used to be conjured,
// which minted a coach on every de-training. Throws now, for the reason in `unloadBegan`.
const yi = s.yards.divisionYard.findIndex((c) => c.type === 'coach' && !c.loaded);
if (yi < 0) throw new Error('passengersDetrained: no empty coach in the Division Yard');
const empty = s.yards.divisionYard.splice(yi, 1)[0]!;
refillDivisionYardIfEmpty(s);
// The arriving coach goes into the red box carrying nothing: the journey it was stamped for
// is over, and the box feeds straight back to a yard through the Freight Agent.
f.inboundBox.push(pooled(tray.consist[e.coachIndex]!));
tray.consist[e.coachIndex] = empty;
}
f.usedThisStage.porters += 1;
break;
@@ -2145,8 +2451,14 @@ export function reduce(s: GameState, e: GameEvent): void {
workTrack(f)[workTrack(f).length - 1] = null;
const ci = f.industryTrack.cars.findIndex((c) => !c.loaded && c.type === e.carType);
if (ci >= 0) {
s.yards.classificationYard.push(f.industryTrack.cars[ci]!);
f.industryTrack.cars[ci] = { type: e.carType, loaded: true };
s.yards.classificationYard.push(pooled(f.industryTrack.cars[ci]!));
/**
* THE LOAD IS STAMPED WITH THE DISTRICT THAT MADE IT — the chip turned upside down in the
* tray. `laborer.beginUnload` refuses a car stamped with the district it is standing in, so
* this load now has to leave the Office Area on a train before anyone can break it. See
* `RollingStock.origin` in state.ts for the rule and why it is a seat.
*/
f.industryTrack.cars[ci] = { type: e.carType, loaded: true, origin: seatOf(s, e.player) };
}
f.usedThisStage.laborers += 1;
break;
@@ -2154,7 +2466,17 @@ export function reduce(s: GameState, e: GameEvent): void {
case 'unloadBegan': {
const f = facilityAt(s, e.player, e.at)!;
const ci = f.industryTrack.cars.findIndex((c) => c.loaded);
/**
* THE CAR THE PLAYER PICKED, not merely "a loaded one".
*
* REPORTED: with several loaded cars spotted on one industry track, unloading always took the
* WESTMOST car regardless of which one was chosen. This used to re-derive the target with
* `industryTrack.cars.findIndex(c => c.loaded)`, which returns the same answer — the first
* loaded car in track order — no matter which `carIndex` the intent actually named; `check`
* had already validated that specific car, and the choice was thrown away between there and
* here. `e.carIndex` is exactly what `laborer.beginUnload`'s reducer read off the intent.
*/
const ci = e.carIndex;
if (ci >= 0) {
/**
* §9.3 — the replacement empty comes out of the Division Yard. Conjuring it here is what
@@ -2206,7 +2528,7 @@ function protoCard(
kind: { kind: string; geometry?: string; facility?: string; hand?: string },
variant: number | undefined,
): TrackCard | null {
const base = { standing: [], facility: null, modifiers: [], enhancements: [] };
const base = { standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [] };
if (kind.kind === 'track') {
const geometry = kind.geometry as TrackGeometry;
@@ -2414,6 +2736,7 @@ function emptyCard(): TrackCard {
geometry: { kind: 'limits' },
baseOperationalRail: false,
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -2620,9 +2943,16 @@ export function acceptsCar(tray: CrewTray, carType: CarType): boolean {
/**
* §7 — IS THIS TRAY THE ONE BEING MADE UP?
*
* A train is made up where it is built, standing at a Division Point, and only until its consist
* matches its card. Everything else with a Crew Tray — a train working your district, a train
* halfway across the Division — is running, not being assembled.
* A train is made up where it is built and only until its consist matches its card. Everything else
* with a Crew Tray — a train working your district, a train halfway across the Division — is
* running, not being assembled.
*
* WHERE that is used to be the whole test: "standing at a Division Point". True while a Division
* Point was the only place to build one, and wrong once an Extra could be started at a Control Point
* or in an Interchange's yard (§7) — those trains were never offered a car and ran empty. The extra
* clause is `beingMadeUp` (state.ts), a flag set on exactly those trays and cleared when they start
* running, rather than a second positional rule: a train STANDING at an Office is usually one that
* arrived, and must not be fillable from the yard.
*
* SHARED with the New Train Phase, which uses it to decide whether to stop and ask. It has to be:
* `check` accepted any tray with room in its consist, so during a New Train Phase the Division Yard
@@ -2632,7 +2962,7 @@ export function acceptsCar(tray: CrewTray, carType: CarType): boolean {
*/
export function isBeingMadeUp(tray: CrewTray): boolean {
if (tray.trainNumber === null) return false;
if (tray.position.at !== 'divisionPoint') return false;
if (tray.position.at !== 'divisionPoint' && !tray.beingMadeUp) return false;
const profile = trainProfile(tray.trainNumber, tray.trainIsExtra);
if (!profile) return false;
return tray.consist.length < consistSize(profile.consist);
@@ -2686,6 +3016,7 @@ function limitsCard(): TrackCard {
geometry: { kind: 'limits' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
+242 -97
View File
@@ -3,8 +3,8 @@
*
* TRANSCRIBED FROM THE RECOVERED DESIGN FILES (2026-07-30):
* docs/Deck cards2.xlsx — the complete card list and counts
* docs/Trains3.pdf — all 22 train cards
* docs/Mainline Cards.pdf — the ten Mainline card types
* docs/Trains3.pdf — the train cards
* docs/Mainline Cards.pdf — the Mainline card types, and the two Division Points
* docs/tracks.png — card art
*
* This replaced an invented 52-card placeholder. See docs/rules/implications.md for what changed
@@ -60,13 +60,17 @@ export type TrackProfile = {
/**
* TRACK IS IN THE HOME OFFICE DECK, and is drawn and played like any other card.
*
* 96 dealt of the sheet's 104 (column B of `docs/Deck cards2.xlsx`) — the 8 sharp curves are dealt
* zero, see below. An earlier reading made track a
* separate per-player supply of 26 pieces, sitting outside the deck and laid one a turn. That came
* from misreading the sheet's LAST column, headed "Track Per Player" — 8/4/4/1/1/4/4 = 26, which is
* a note about each player's likely share of 104 across four players, not a second stack of cards.
* The sheet's own totals settle it: "Sum other 115", "Total track 104", and a grand total of 231
* once the 12 start cards are counted. 115 + 104 + 12 = 231.
* Every row's dealt count is in `copiesInDeck` below; the sharp curves are dealt zero, see below.
* How many that comes to is `TRACK_IN_DECK`, computed rather than written down — it moves with
* balance work, so a number in this comment would be wrong before long.
*
* An earlier reading made track a separate per-player supply, sitting outside the deck and laid one
* a turn. That came from misreading the sheet's LAST column, headed "Track Per Player" —
* 8/4/4/1/1/4/4 = 26, which is a note about each player's likely share across four players, not a
* second stack of cards. The sheet's own totals settle it: "Sum other 115", "Total track 104", and a
* grand total of 231 once the 12 start cards are counted. 115 + 104 + 12 = 231. Those are figures
* from `docs/Deck cards2.xlsx`, a fixed document, and stay here as the audit trail for the
* transcription — they are not claims about what the game deals today.
*
* It matters well beyond bookkeeping. Track competes for the draw with industry, trains and
* enhancements, so building a district is paid for in cards you did not draw instead — and the
@@ -89,10 +93,10 @@ export const TRACK_CARDS: readonly TrackProfile[] = [
* SHARP CURVES ARE DEALT ZERO COPIES — Jesse's call, and the same treatment as Poling.
*
* The only thing that made them different from an ordinary curve was `moveCost: 2`, and nothing
* ever charged it: every switching move costs exactly 1, hard-coded. So the 8 cards in the deck
* were geometric duplicates of the curves, taking 8 draws from a deck the rebalance already thinks
* is too diluted. They come out rather than having the Move cost built, because a per-card movement
* cost is a change to the Move model and the rebalance can wait.
* ever charged it: every switching move costs exactly 1, hard-coded. So they were geometric
* duplicates of the curves, taking draws from a deck the rebalance already thinks is too diluted.
* They come out rather than having the Move cost built, because a per-card movement cost is a
* change to the Move model and the rebalance can wait.
*
* The rows stay in the catalogue at zero, exactly as Poling does, so the design is still visible
* and the geometry still works if they are ever dealt again.
@@ -103,10 +107,10 @@ export const TRACK_CARDS: readonly TrackProfile[] = [
{ geometry: 'turnout', hand: 'left', name: 'Turnout (left)', copiesInDeck: 16, isOperationalRail: false, moveCost: 1 },
];
/** 96 — the sheet's "Total track" of 104, less the 8 sharp curves now dealt at zero. */
/** Summed from `copiesInDeck` above, never written down — it moves whenever the deck is retuned. */
export const TRACK_IN_DECK = TRACK_CARDS.reduce((n, t) => n + t.copiesInDeck, 0);
/** Start cards, placed at setup and never shuffled: 4 Whistle Posts, 8 Limits. */
/** Start cards, placed at setup and never shuffled. */
export const WHISTLE_POST_SUPPLY = 4;
export const LIMITS_SUPPLY = 8;
@@ -116,7 +120,7 @@ export function trackProfile(geometry: TrackGeometry, hand: Hand): TrackProfile
}
// ---------------------------------------------------------------------------
// Offices — Depot 4, Station 2, Terminal 1
// Offices — the upgrade ladder: Whistle Post, Depot, Station, Terminal
// ---------------------------------------------------------------------------
export type OfficeProfile = {
@@ -139,13 +143,12 @@ export type OfficeProfile = {
* passenger modifier cards (Waiting Area, Restaurant, Hotel).
*/
/**
* Office cards. `copiesInDeck` was **doubled** (Depot 4→8, Station 2→4, Terminal 1→2) — Q12.
* Office cards. Every tier's `copiesInDeck` was **doubled** against the recovered design — Q12.
*
* Players always start at a Whistle Post, which has ONE A/D track, so a second arrival is an
* automatic collision (§8.3, Gap 2a). Measured at the original density, 25 of 100 games never drew
* a Depot and never escaped: they averaged **−6.0** revenue against **−0.4** for games that
* upgraded at least once, and 25 of 26 collisions happened at Whistle Post. Escaping needed one of
* 4 Depot cards in 111, roughly a 59% chance across a game's draws.
* upgraded at least once, and 25 of 26 collisions happened at Whistle Post.
*
* Upgrades are strictly sequential (Gap 3b, no skipping), so Station and Terminal are rarer than
* their raw counts imply — Terminal needs all three cards in order. Station and Terminal were
@@ -153,9 +156,10 @@ export type OfficeProfile = {
*
* PROVISIONAL — re-evaluate. This was chosen to remove a 25% chance of an unwinnable opening deal,
* not from the recovered design, and it is a blunt instrument: it lifts the whole office ladder and
* dilutes every other category slightly (deck 133 → 140). Revisit once the victory target is
* settled and freight is carrying its intended share; the right answer may instead be fewer
* Terminals, a cheaper first upgrade, or more A/D capacity at Whistle Post.
* dilutes every other category slightly. Revisit once the victory target is settled and freight is
* carrying its intended share; the right answer may instead be fewer Terminals, a cheaper first
* upgrade, or more A/D capacity at Whistle Post. The counts themselves are in the rows below, which
* is the only place they should be read from.
*/
export const OFFICE_PROFILES: readonly OfficeProfile[] = [
{ tier: 'whistlePost', name: 'Whistle Post', isControlPoint: false, isPassengerFacility: false, adTracks: 1, porters: 0, passengerOut: 0, passengerIn: 0, copiesInDeck: 0 },
@@ -199,13 +203,14 @@ export type IndustryProfile = {
/**
* Industry density (Gap 12). The recovered sheet lists 9 industries in a 115-card deck; the
* prototype ran 10 in 52. At 9-in-115 a game saw 1.6 Freight Facilities, freight was 10% of gross
* revenue, and `carsCoupled` fired 4 times per 100 games — the freight loop, which is the point of
* the game, effectively never ran.
* prototype ran 10 in 52. At the sheet's density a game saw 1.6 Freight Facilities, freight was 10%
* of gross revenue, and `carsCoupled` fired 4 times per 100 games — the freight loop, which is the
* point of the game, effectively never ran.
*
* Each industry's `copies` is TRIPLED, giving 27 in 133. That restores roughly the prototype's
* Each industry's `copies` is TRIPLED against the sheet, which restores roughly the prototype's
* ratio while preserving the sheet's proportions exactly: the outbound/inbound balance and the
* lockout structure are unchanged, because every kind scales by the same factor.
* lockout structure are unchanged, because every kind scales by the same factor. The multiplier is
* the decision; the resulting totals are in the rows below and move with every retune.
*/
/**
* LOCKOUTS, from the sheet's "Lockouts" column verbatim:
@@ -231,42 +236,51 @@ export const INDUSTRY_PROFILES: readonly IndustryProfile[] = [
{ kind: 'freightHouse', name: 'Freight House', carTypes: ['boxcar'], flow: 'both', baseOut: 1, baseIn: 1, baseLoaders: 1, lockouts: ['grocersWarehouse'], copies: 6 },
{ kind: 'mineTipple', name: 'Mine Tipple', carTypes: ['hopper'], flow: 'outbound', baseOut: 1, baseIn: 0, baseLoaders: 1, lockouts: ['powerPlant'], copies: 6 },
/**
* BOTH DIRECTIONS, per the card reference — this was `outbound` and it contradicted the rules.
* OUTBOUND ONLY. A Refinery ships oil out and receives nothing; reported from playtesting and
* confirmed by Jesse (v0.4.9e): "only ships out tanks, does not receive anything".
*
* `card-reference.md`: "Oil Refinery | Tank car | Both | 3 | 2 | 2 | 4", and in prose — "'Freight
* House' is not a card. It is the collective term for a freight facility that loads *and* unloads
* — the Grocer's Warehouse and the Oil Refinery." §9.3's "Passenger Facilities and Freight Houses
* permit cars to move each direction" therefore names exactly these two, and the engine had both
* of them one-way.
* It was briefly `flow: 'both'`, on the reading that "'Freight House' is not a card — it is the
* collective term for a freight facility that loads *and* unloads, the Grocer's Warehouse and the
* Oil Refinery", which made §9.3's "Passenger Facilities and Freight Houses permit cars to move
* each direction" name exactly those two. That premise is dead: `glossary.md` and
* `rules-v0.2.md` corrected the Freight House to a card of its own, dealt like any other industry,
* so §9.3 names the Freight House and nothing else, and card-reference.md's "Both" column loses
* the only argument it had.
*
* The consequence was silent: `usableGrant` drops a Modifier's grant on a direction its host
* cannot use, so every +1 inbound beside a Refinery went nowhere.
*
* The base numbers stay at the engine's own scale (1 per direction it allows) rather than the card
* reference's 2/2 — every industry here is scaled down the same way, Mine Tipple included, and
* raising one of them alone would be a balance change rather than a correction. Flagged in TODO.
* The card set says the same thing on its own. All three Refinery modifiers — Pipelines, Oil
* Depot, Viscosity Breakers — grant `+1 outbound`; a two-way Refinery would be the one industry in
* the game with no way to raise the direction it is supposed to use half its capacity on.
* `StationMaster-Home-Deck-v0.4.5.md` prints it "Outbound, 1 out / 0 in".
*/
{ kind: 'refinery', name: 'Refinery', carTypes: ['tank'], flow: 'both', baseOut: 1, baseIn: 1, baseLoaders: 1, lockouts: ['powerPlant'], copies: 3 },
{ kind: 'refinery', name: 'Refinery', carTypes: ['tank'], flow: 'outbound', baseOut: 1, baseIn: 0, baseLoaders: 1, lockouts: ['powerPlant'], copies: 3 },
{ kind: 'powerPlant', name: 'Power Plant', carTypes: ['hopper', 'tank'], flow: 'inbound', baseOut: 0, baseIn: 1, baseLoaders: 1, lockouts: ['mineTipple', 'refinery'], copies: 6 },
{ kind: 'packingSheds', name: 'Packing Sheds', carTypes: ['reefer'], flow: 'outbound', baseOut: 1, baseIn: 0, baseLoaders: 1, lockouts: ['grocersWarehouse'], copies: 3 },
/**
* BOTH DIRECTIONS — see the Refinery above; "Grocer's Warehouse | Boxcar | Both | 2 | 2 | 2 | 3".
* INBOUND ONLY — the mirror of the Refinery above, and the same correction. Reported from
* playtesting and confirmed by Jesse (v0.4.9e): "Grocer's Warehouse should be receive only, does
* not ship anything out". `StationMaster-Home-Deck-v0.4.5.md` prints it "Inbound, 0 out / 1 in".
*
* Reported from play: "grocer's warehouse didn't get extra outbound slot for truck dock." It could
* not: the Truck Dock printed +1 outbound at the time and this was `flow: 'inbound'`, so the grant
* was dropped on a direction the facility did not have. The same trap still swallows an Ice House
* set beside a Grocer's that has been left one-way.
*
* `TODO.md` had previously recorded this as "checked, and there is no bug" on the reasoning that a
* Grocer's is inbound-only. That premise was the bug.
* THE ICE HOUSE IS THEREFORE A DEAD CARD BESIDE A GROCER'S, and that is the design, not an
* oversight: `usableGrant` drops a Modifier's grant on a direction its host cannot use, and the
* Home Deck sheet says so outright — "a bonus beside a facility that cannot use its direction is
* not usable", naming the Truck Dock's inbound bonus beside the outbound-only Packing Sheds as the
* other example. The Truck Dock (+1 inbound) and Local Small Groceries (+1 Laborer) are the two
* that do work here.
*/
{ kind: 'grocersWarehouse', name: "Grocer's Warehouse", carTypes: ['boxcar', 'reefer'], flow: 'both', baseOut: 1, baseIn: 1, baseLoaders: 1, lockouts: ['packingSheds', 'freightHouse'], copies: 3 },
{ kind: 'grocersWarehouse', name: "Grocer's Warehouse", carTypes: ['boxcar', 'reefer'], flow: 'inbound', baseOut: 0, baseIn: 1, baseLoaders: 1, lockouts: ['packingSheds', 'freightHouse'], copies: 3 },
];
/** Legacy alias; the engine still reads FREIGHT_PROFILES in places. */
export const FREIGHT_PROFILES = INDUSTRY_PROFILES;
/** §9.3 — the collective term for an industry that both loads and unloads. */
/**
* §9.3 — "Passenger Facilities and Freight Houses permit cars to move each direction".
*
* ONE CARD ANSWERS TO THIS NOW: the Freight House itself. It was briefly three, while the Refinery
* and the Grocer's Warehouse were also `both` on a reading of the term the glossary has since
* corrected — a Freight House is a card, not a collective noun. Kept as a predicate on `flow`
* rather than a comparison against the kind, because it is the DIRECTION §9.3 is talking about.
*/
export function isFreightHouse(p: IndustryProfile): boolean {
return p.flow === 'both';
}
@@ -278,7 +292,7 @@ export function industryProfile(kind: FreightKind): IndustryProfile {
}
// ---------------------------------------------------------------------------
// Modifiers — 17 industry + 6 passenger, each tied to specific hosts
// Modifiers — passenger and industry, each tied to specific hosts
// ---------------------------------------------------------------------------
export type ModifierKind =
@@ -347,7 +361,7 @@ export function modifierProfile(kind: ModifierKind): ModifierProfile {
}
// ---------------------------------------------------------------------------
// Trains — 22 cards, named, with speed class and individual rules
// Trains — named, with a speed class and individual printed rules
// ---------------------------------------------------------------------------
export type TrainSpeed = 'fast' | 'slow';
@@ -411,11 +425,18 @@ function pair(odd: number, name: string, speed: TrainSpeed, consist: ConsistSpec
}
export const TIMETABLED_TRAINS: readonly TrainProfile[] = [
...pair(1, 'Crack Limited', 'fast', { freight: 0, coach: 3, caboose: 0 },
/**
* 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.
*/
...pair(1, 'Crack Limited', 'fast', { freight: 0, coach: 2, caboose: 0 },
{ terminalsOnly: true, noSwitching: true, expedite: true, note: 'Stop at Terminals only.' }),
...pair(3, 'Express', 'fast', { freight: 2, coach: 0, caboose: 0 },
{ oneFreightPerLocation: true, expedite: true, note: 'May drop or pick up one freight car at every location.' }),
...pair(5, 'The Sparrow', 'fast', { freight: 0, coach: 2, caboose: 0 },
...pair(5, 'The Sparrow', 'fast', { freight: 0, coach: 3, caboose: 0 },
{ noSwitching: true, expedite: true }),
...pair(7, 'Local', 'slow', { freight: 1, coach: 1, caboose: 0 },
{ coachStaysOnStationTrack: true, note: 'Maximum one freight, one coach.' }),
@@ -443,11 +464,18 @@ export const EXTRA_TRAINS: readonly TrainProfile[] = [
export const ALL_TRAINS: readonly TrainProfile[] = [...TIMETABLED_TRAINS, ...EXTRA_TRAINS];
/**
* §2.3 — ODD RUNS WEST, EVEN RUNS EAST. The number is the direction, for an Extra as much as for a
* timetabled train, and the Division Point it starts at is therefore the one it runs away from.
* §2.3 — ODD RUNS WEST, EVEN RUNS EAST. The number is the direction for a TIMETABLED train.
*
* Extras print `direction: 'playerChoice'`, which the engine read as "always eastbound from the West
* Division Point". Jesse's ruling: the number decides, like everything else on the timetable.
* NOT for an Extra any more. Extras print `direction: 'playerChoice'` and now mean it (Jesse's
* ruling, superseding "the number decides, like everything else on the timetable"): the player who
* played the card picks where it starts, and the start decides the direction — a Crew Tray placed
* at the Western Division Point runs east and one at the Eastern runs west, because the alternative
* is a train that leaves the Division on its first move having crossed nothing. Where the start is
* NOT an end of the Division — an Interchange, or a Control Point — both ways are real runs and the
* player says which. `resolveExtraStart` in apply.ts is where that happens.
*
* Still read for an Extra in one place: replaying a save written before the choice existed, where
* `newTrain.startExtra` carries only the legacy `atSeat` field.
*/
export function runDirection(trainNumber: number): Direction {
return trainNumber % 2 === 0 ? 'east' : 'west';
@@ -518,6 +546,29 @@ export const MAINLINE_PROFILES: readonly MainlineProfile[] = [
{ kind: 'interchange', name: 'Interchange', speed: { kind: 'uniform', value: 60 }, trainsMayPass: false, sortsCars: true, entryPoints: ['start', 'sortCars'] },
];
/**
* THE MAINLINE DECK AS PRINTED, dealt WITHOUT replacement.
*
* `MAINLINE_PROFILES` above is a list of card TYPES, one entry each. It is not the deck, and setup
* used it as one: `buildDivision` drew uniformly from those types with replacement, which made two
* Interchanges (or two Trestles, or two Tunnels) an ordinary outcome and gave Plains the same weight
* as everything else although the deck prints two of it. `Mainline Cards.pdf` is the
* inventory, transcribed in `docs/StationMaster-Mainline-Deck-v0.4.5.md`, which had already flagged
* the mismatch as needing correction.
*
* It matters more than card flavour now that an Extra may start at an Interchange (§7): "if an
* Interchange is on the board" has to mean a card there is at most one of, not a type the deal can
* hand out twice.
*
* The two Division Point cards in that inventory are not here — they are the fixed ends of the
* Division, laid by `buildDivision` itself rather than drawn. Plains appears twice because the deck
* prints it twice; every other type once. The list below is the deck, so it is not counted here.
*/
export const MAINLINE_DECK: readonly MainlineKind[] = [
'plains', 'plains', 'curves', 'hilly', 'heavyGrade',
'doubleTrack', 'uncontrolledSiding', 'tunnel', 'trestle', 'interchange',
];
/**
* How many Stages a train needs to cross a Mainline card.
*
@@ -684,9 +735,9 @@ export type SimpleCard = {
* The opponent-directed card this exists SOLELY to answer.
*
* A defence with nothing to defend against is a dead draw, exactly as the attack itself would be.
* The 22 Space-use and Action cards are held out of every deck until they are implemented (Q6),
* and these go with them — named here rather than in a list somewhere else so the pairing is
* visible on the card, and so they come back together when their attacker does.
* The Space-use and Action cards are held out of every deck until they are implemented (Q6), and
* these go with them — named here rather than in a list somewhere else so the pairing is visible
* on the card, and so they come back together when their attacker does.
*/
answers?: string;
};
@@ -732,39 +783,48 @@ export type EnhancementRule = {
* opponent-directed card that a solitaire deck does not contain (Q6).
* - `unbuilt` — nothing reads it at all. The effect is recorded here and not yet written.
*
* Seven of the ten are live. Each row below cites the file that reads it, because the first
* attempt at this table got FIVE of the ten wrong: it was filled in by grepping for four helper
* function names and reading "no match" as "no implementation", when Interlocking, Yard Office,
* Small Yard and ABS Signals are all read directly by key — and all four are covered by tests in
* `enhancements.test.ts` that were passing the whole time. The result was a tooltip telling players
* that four working cards did nothing, which is worse than the bare label it replaced.
* Most are live. Each row below cites the file that reads it — the row is the answer, and no
* tally is kept here, because a tally is one more thing to forget when a card is implemented.
*
* The first attempt at this table got FIVE of the ten wrong: it was filled in by grepping for four
* helper function names and reading "no match" as "no implementation", when Interlocking, Yard
* Office, Small Yard and ABS Signals are all read directly by key — and all four are covered by
* tests in `enhancements.test.ts` that were passing the whole time. The result was a tooltip
* telling players that four working cards did nothing, which is worse than the bare label it
* replaced.
*
* KEEP THIS HONEST, AND CHECK THE CITATION. Implementing one of these means changing its value in
* the same commit; otherwise the card goes on apologising for something it now does. It is data
* rather than something derived because "is this key read anywhere" is not a question the type
* system can answer — but a claim here without a file reference beside it is a claim nobody checked.
* system can answer — but a claim here without a reference beside it is a claim nobody checked.
*
* CITE THE FUNCTION, NEVER THE LINE NUMBER. Every one of these rows once carried a `file.ts:NNN`
* and every one of them had rotted — `apply.ts:405` for Small Yard was pointing four hundred lines
* short by the time anyone looked. A line number is a citation that decays silently on the next
* edit anywhere above it, which is the opposite of what this note is for.
*/
effect: 'live' | 'dormantSolo' | 'unbuilt';
};
export const ENHANCEMENT_RULES: readonly EnhancementRule[] = [
// Holds an arrival at the Limits instead of colliding when the Office is full — advance.ts:770.
// Holds an arrival at the Limits instead of colliding when the Office is full — `arriveAtOffice`.
{ key: 'interlocking', placement: 'runningTrackStraight', effect: 'live' },
// Wired at apply.ts:1738, but it answers Derail, an Action card the solitaire deck omits (Q6).
// Wired in `isProtectedFromDerail`, but it answers Derail, an Action card the solo deck omits (Q6).
{ key: 'facingPointLocks', placement: 'onCard', requiresInDistrict: 'interlocking', effect: 'dormantSolo' },
// Diverts a coachless arrival away from the Train Order Office — advance.ts:750.
// Diverts a coachless arrival away from the Train Order Office — `arriveAtOffice`.
{ key: 'yardOffice', placement: 'secondaryTrackStraight', effect: 'live' },
// Lets a consist be re-ordered for one Move — apply.ts:405.
// Lets a consist be re-ordered for one Move — `check`'s `switch.sortConsist` case.
{ key: 'smallYard', placement: 'secondaryTrackStraight', effect: 'live' },
// Wired at apply.ts:1743, but it removes a Watertower, a Space-use card the solo deck omits.
// Wired in `watertowersRemovable`, but it removes a Watertower, a Space-use card the solo deck omits.
{ key: 'waterColumn', placement: 'runningTrackStraight', effect: 'dormantSolo' },
// The only one with NO code path at all: nothing anywhere reads `overpass`.
{ key: 'overpass', placement: 'onCard', effect: 'unbuilt' },
{ key: 'telegraph', placement: 'runningTrackStraight', dispatchBonus: 4, effect: 'live' },
{ key: 'telephone', placement: 'onCard', requiresOnSameCard: 'telegraph', dispatchBonus: 8, effect: 'live' },
{ key: 'radio', placement: 'onCard', requiresOnSameCard: 'telephone', dispatchBonus: 12, effect: 'live' },
// Stored on the Mainline node rather than in `enhancements[]` — apply.ts:1461, read at
// advance.ts:599 (no rear-ending) and advance.ts:721 (the follower holds instead of being ruled on).
// Stored on the Mainline node rather than in `enhancements[]` — written by `reduce`'s
// `enhancementPlaced`, read in `moveTrain` (no rear-ending) and `evaluateClearance` (the follower
// holds instead of being ruled on).
{ key: 'absSignals', placement: 'mainlineCard', effect: 'live' },
];
@@ -855,11 +915,15 @@ export type StockSupply = { type: CarType; loaded: number; empty: number };
/**
* NOT in the recovered files — still the provisional figure.
*
* Scaled up alongside the Gap 12 industry increase. Worst-case demand (every copy of every
* industry in play at full capacity) is boxcar 15, hopper 12, tank 9, reefer 6; the supply must
* cover that, since a Division Yard that runs dry starves the freight loop the increase exists to
* feed. Lockouts and district size mean the worst case cannot actually occur, so this carries
* deliberate headroom.
* Scaled up alongside the Gap 12 industry increase. The rule it was set by, rather than the numbers
* it produced: worst-case demand for a car type is every copy of every industry that uses it, in
* play at full capacity, and the supply must cover that — a Division Yard that runs dry starves the
* freight loop the increase exists to feed. Lockouts and district size mean the worst case cannot
* actually occur, so this carries deliberate headroom. RE-DERIVE IT FROM `INDUSTRY_PROFILES`
* whenever industry copies move; a figure written here would not survive the next retune.
*
* Coaches are the type this rule does NOT cover, because no industry asks for one — their demand
* comes from passenger work, and Gitea#2 is the open report that the supply is short (see TODO.md).
*/
export const ROLLING_STOCK_SUPPLY: readonly StockSupply[] = [
{ type: 'coach', loaded: 8, empty: 8 },
@@ -887,11 +951,11 @@ export const STAGES_PER_SHIFT = 3;
export const HAND_LIMIT = 3;
/**
* The split opening deal: 3 track cards and 3 others, from two separately shuffled piles
* (`setup.ts`). One of the three `StartingHand` options below, not the only one any more.
* The split opening deal — track cards and others, from two separately shuffled piles (`setup.ts`).
* One of the three `StartingHand` options below, not the only one any more.
*
* Six against a limit of three on purpose — the first turn is spent choosing which district you can
* afford to build.
* Deliberately over the hand limit: the first turn is spent choosing which district you can afford
* to build. The two constants below are the deal.
*/
export const OPENING_TRACK = 3;
export const OPENING_OTHER = 3;
@@ -925,10 +989,16 @@ export const OPENING_DEALS: Readonly<Record<StartingHand, { any: number; track:
/**
* WHAT THE THREE WORKING ECONOMIES PAY.
*
* Balance is the open problem in this game — the developer bot averages 7.0 Revenue against a target
* of 20, of which most came from traffic nobody had to work — and the way to settle it is to play it
* at several settings rather than to keep re-deriving it. So the three rates are dials, set when the
* game is dealt and fixed for its duration.
* Balance is the open problem in this game, and the way to settle it is to play it at several
* settings rather than to keep re-deriving it. So the three rates are dials, set when the game is
* dealt and fixed for its duration.
*
* DO NOT WRITE A CURRENT BALANCE FIGURE HERE. This said "the developer bot averages 7.0 Revenue
* against a target of 20" long after that stopped being true: 7.0 was measured while
* `trainPerTransit` still defaulted to 1, and the paragraph below explains that this very setting
* was then defaulted to 0 for being worth ~5.4 of it. Re-measured 2026-08-22 over 400 games at the
* current defaults, the developer bot means about ZERO. Run `node src/sim/harness.ts 400 standard`
* for today's number rather than trusting one written here.
*
* `passengerPerCoach` and `freightPerLoad` each pay on BOTH halves of their cycle: a coach pays when
* it is boarded and again when it is detrained, a load pays when it is made up outbound and again
@@ -945,10 +1015,53 @@ export type RevenueRules = {
trainPerTransit: number;
};
export type HouseRules = { startingHand: StartingHand; revenue: RevenueRules };
/**
* WHERE AN EXTRA MAY BE STARTED — a setting, because the table disagrees about it.
*
* §7 gives an Extra "either Division Point", and Jesse's ruling adds the Interchange to that base
* set: both are places on the shared Division that belong to nobody, so neither favours a seat.
* Starting one inside a player's own district is the part that does, which is what this dials.
*
* - `divisionPointsOnly` — the Division Points and the Interchange. No Office start at all.
* - `ownOffice` — those, plus a Control Point in the district of the player who played the card.
* - `anyOffice` — those, plus a Control Point in ANY player's district.
*
* A Whistle Post never qualifies however this is set: an Office has to be a Control Point to start
* an Extra, which is part of what upgrading buys (§11).
*/
export type ExtraStartRule = 'divisionPointsOnly' | 'ownOffice' | 'anyOffice';
export type HouseRules = {
startingHand: StartingHand;
revenue: RevenueRules;
extraStart: ExtraStartRule;
/**
* §6.2 — MAY A TIMETABLED TRAIN BE THROWN AWAY? (Gitea#9, superseding Gitea#6.)
*
* Jesse: "Timetabled trains are at the choice of the player — they can either play or discard. If
* someone else wants to pick it up, they are more than able to. The reason: I don't want, if you
* decide to play a game longer than five days, to decide that maybe there are too many trains, the
* stations are jammed, and the railroad doesn't need any more. You can toss it. Someone else might
* disagree and pick it up."
*
* A setting rather than a flat rule because Jesse asked for it as one — the reasoning above is
* about LONG games, and a five-Day game may well want the pressure Gitea#6 created. Discarding
* puts the card face-up on a Department pile, so "someone else might pick it up" needs no
* machinery of its own: that is where every discard already goes.
*
* AN EXTRA IS NEVER DISCARDED WHATEVER THIS SAYS. Gitea#9 is about the timetable filling up, and
* an Extra never joins it — it runs once and ends in the Salvage Yard, so it cannot jam anything.
*/
discardTimetabled: boolean;
};
/** What a caller may name — any subset, down to none — resolved by `houseRules()`. */
export type HouseRuleOverrides = { startingHand?: StartingHand; revenue?: Partial<RevenueRules> };
export type HouseRuleOverrides = {
startingHand?: StartingHand;
revenue?: Partial<RevenueRules>;
extraStart?: ExtraStartRule;
discardTimetabled?: boolean;
};
/** The dialog's range. Zero is a real setting: it switches an economy off so the others can be read. */
export const REVENUE_MIN = 0;
@@ -957,6 +1070,14 @@ export const REVENUE_MAX = 5;
export const DEFAULT_HOUSE_RULES: HouseRules = {
startingHand: 'threeRandom',
revenue: { passengerPerCoach: 1, freightPerLoad: 1, trainPerTransit: 0 },
// `anyOffice` is what the engine did before the setting existed, so a game dealt without naming
// it plays the way it always has. Jesse's call, so the 0.4.9 playtest line does not change under
// its testers in the middle of a bugfix release.
extraStart: 'anyOffice',
// Gitea#9's ruling is the default, so a game dealt without naming it plays the rule Jesse most
// recently gave rather than the one it replaced. This keeps main and the 0.4.9 playtest line —
// which has no setting and simply allows it — playing the same game.
discardTimetabled: true,
};
/**
@@ -971,6 +1092,11 @@ export const DEFAULT_HOUSE_RULES: HouseRules = {
export const LEGACY_HOUSE_RULES: HouseRules = {
startingHand: 'threeTrackThreeOther',
revenue: { passengerPerCoach: 1, freightPerLoad: 1, trainPerTransit: 1 },
// An Extra could always be started at a Control Point in these games, in any district.
extraStart: 'anyOffice',
// These games predate Gitea#6 as well as Gitea#9: a train card could simply be discarded. `true`
// is what they were played under, and a replay that discards a Timetabled train needs it.
discardTimetabled: true,
};
/** A whole, valid rule set from a config that may carry none, some, or out-of-range values. */
@@ -989,6 +1115,8 @@ export function houseRules(config: { houseRules?: HouseRuleOverrides }): HouseRu
freightPerLoad: clamp(rev.freightPerLoad, d.revenue.freightPerLoad),
trainPerTransit: clamp(rev.trainPerTransit, d.revenue.trainPerTransit),
},
extraStart: given.extraStart ?? d.extraStart,
discardTimetabled: given.discardTimetabled ?? d.discardTimetabled,
};
}
@@ -998,12 +1126,24 @@ export const STARTING_HAND_LABELS: readonly { value: StartingHand; label: string
{ value: 'sixRandom', label: 'Six random cards' },
{ value: 'threeTrackThreeOther', label: 'Three random track and three random non-track cards' },
];
/** What the dialog calls each `ExtraStartRule`, in the order it offers them. */
export const EXTRA_START_LABELS: readonly { value: ExtraStartRule; label: string }[] = [
{ value: 'divisionPointsOnly', label: 'Division Points and the Interchange only' },
{ value: 'ownOffice', label: 'Also the playing player\u2019s own Control Point' },
{ value: 'anyOffice', label: 'Also any player\u2019s Control Point' },
];
export const MAX_CONSIST = 4;
export const MOVES_PER_LOCAL_OPS = 6;
export const MOVES_PER_LOCAL_OPS_NIGHT = 5;
export const LABORER_ACTIONS_PER_LOAD = 4;
export const COLLISION_PENALTY = 5;
export const COLLISION_FLOOR_PER_DAY = 3;
/**
* Q3 — an expedited train left parked off the Office when a Mainline Phase begins is a Station
* Master fault: the train was not kept ready to highball the moment the Subdivision allowed it.
* Charged every Phase it is caught there, not just once, since the fault is being left that way.
*/
export const EXPEDITE_FAULT_PENALTY = 1;
export function collectiveRevenueFloor(players: number, days: number): number {
return 3 * players * days;
@@ -1031,7 +1171,8 @@ export function lengthProfile(length: GameLength): LengthProfile {
/**
* Cards that can only be played AT another player (Q6). In a solitaire game they have no legal
* target, so they are removed from the deck rather than sitting in hand as 19% dead draws.
* target, so they are removed from the deck rather than sitting in hand as dead draws — which, when
* this was written, was very nearly a fifth of the deck.
*/
export const OPPONENT_ONLY_CATEGORIES: readonly string[] = ['spaceUse', 'action'];
@@ -1039,8 +1180,10 @@ export function isOpponentOnly(category: string): boolean {
return OPPONENT_ONLY_CATEGORIES.includes(category);
}
/** How many cards `DEFENCE_ONLY_CARDS` accounts for — 7: two Facing Point Locks of each kind, two
* Water Columns and one Overpass. */
/**
* How many cards `DEFENCE_ONLY_CARDS` accounts for. Summed from the rows rather than written down:
* which cards qualify is `SimpleCard.answers`, and the total moves whenever one is added.
*/
export const DEFENCE_ONLY_COPIES =
ENHANCEMENT_CARDS.filter((c) => c.answers).reduce((n, c) => n + c.copies, 0) +
MAINLINE_MODIFIER_CARDS.filter((c) => c.answers).reduce((n, c) => n + c.copies, 0);
@@ -1063,17 +1206,19 @@ export function deckComposition(): { category: string; count: number }[] {
/**
* The whole CATALOGUE, including cards not currently dealt. Not the size of any deck in play — see
* `DEALT_DECK_SIZE`, which is what `buildDeck` actually returns.
* `SOLITAIRE_DECK_SIZE` below, which is what `buildDeck` actually deals. (This pointed at a
* `DEALT_DECK_SIZE` that has never existed.)
*/
export const DECK_SIZE = deckComposition().reduce((n, c) => n + c.count, 0);
/**
* The deck actually dealt, in every mode: the catalogue less the 22 opponent-directed cards.
* The deck actually dealt, in every mode: the catalogue less the opponent-directed cards, less the
* defensive cards that exist only to answer them.
*
* Named for solitaire because Q6 dropped them there first, and kept under that name because the
* number is the same either way. They are out of the competitive deck too until they are
* implemented — `checkPlay` answers both categories NOT_IMPLEMENTED, so dealing them would make ~9%
* of draws reject. See `buildDeck`.
* implemented — `checkPlay` answers both categories NOT_IMPLEMENTED, so dealing them would make a
* meaningful share of draws reject outright. See `buildDeck`.
*/
export const SOLITAIRE_DECK_SIZE =
deckComposition()
+45 -10
View File
@@ -19,8 +19,8 @@
* reconstruct the whole board to draw one frame.
*/
import type { CarType, OfficeTier } from './content.ts';
import type { LocalOpsOption } from './intents.ts';
import type { CarType, Direction, OfficeTier } from './content.ts';
import type { ExtraStart, LocalOpsOption } from './intents.ts';
import type { CardId, GridCoord, PlayerIndex, RollingStock, SeatIndex, TrayId } from './state.ts';
export type GameEvent =
@@ -30,7 +30,12 @@ export type GameEvent =
| { type: 'actorChanged'; player: PlayerIndex | null }
// -- local operations
| { type: 'localOpsOptionChosen'; player: PlayerIndex; option: LocalOpsOption }
| { type: 'trayMoved'; trayId: TrayId; from: GridCoord; to: GridCoord; movesRemaining: number; facing?: 'n' | 's' | 'e' | 'w' }
/**
* `via` mirrors the intent's `via` (docs/plans/switching-paths.md) — present only when there was
* more than one legal route to `to`, so the history can say which one ran rather than leaving a
* choice the player made invisible in their own log.
*/
| { type: 'trayMoved'; trayId: TrayId; from: GridCoord; to: GridCoord; movesRemaining: number; facing?: 'n' | 's' | 'e' | 'w'; via?: GridCoord }
| {
type: 'carsCoupled';
trayId: TrayId;
@@ -119,6 +124,13 @@ export type GameEvent =
| { type: 'trainHeld'; trainNumber: number; reason: string }
/** A train whose card pays for standing still (X18 Circus) collected on it. */
| { type: 'trainStoodStill'; trainNumber: number; where: string }
/**
* Q3 — A STATION MASTER FAULT. An expedited train is not to be held anywhere but the station: if
* it is still off the Office square — parked on Secondary Track, say, to clear a switching move —
* when a Mainline Phase begins, that is a failure to keep it ready to highball, and it costs
* Revenue. `where` names the square it was found on. Always followed by a `revenueChanged`.
*/
| { type: 'expediteFault'; player: PlayerIndex; trainNumber: number; where: string }
/**
* `why` is the RULE that let it go now, not a restatement of the move.
*
@@ -129,9 +141,9 @@ export type GameEvent =
*/
| { type: 'trainHighballed'; trainNumber: number; from: string; to: string; why: string }
/**
* `expedited` because it changes what the player must do RIGHT NOW. Q3 — an expedited train
* departs the same Stage it arrives, so there is no Local Operations turn in which to work it;
* every other train stands until the next Mainline Phase and can be switched in between.
* `expedited` flags a train that must not be left standing off the station (Q3) — it may be
* switched normally like any other arrival, but it has to be back on the Office square before the
* next Mainline Phase begins, or `expediteFault` fires.
*/
| { type: 'trainArrived'; trainNumber: number; consist: RollingStock[]; office: string; expedited: boolean }
| { type: 'trainDiverted'; trainNumber: number; to: string; reason: string }
@@ -142,20 +154,43 @@ export type GameEvent =
*/
| { type: 'trainCompleted'; trainNumber: number; isExtra: boolean; side: 'east' | 'west'; consist: RollingStock[] }
/** An Extra took a Crew Tray and started its run — at a Division Point, or at a Control Point. */
| { type: 'extraStarted'; player: PlayerIndex; trainNumber: number; atSeat: SeatIndex | null }
/**
* Carries the RESOLVED start and direction (`resolveExtraStart`), not the raw intent fields, so
* the reducer never re-answers a question `check` already answered — the same shape as
* `passengersBoarded` carrying its tray and coach index.
*/
| {
type: 'extraStarted';
player: PlayerIndex;
trainNumber: number;
at: ExtraStart;
direction: Direction;
}
| { type: 'carPlacedOnTrain'; player: PlayerIndex; trayId: TrayId; stock: RollingStock }
| { type: 'carPassed'; player: PlayerIndex; trayId: TrayId }
| { type: 'dispatchBonusUsed'; key: string; bonus: number; trainNumber: number; againstTrain: number }
| { type: 'clearanceRequested'; trainId: TrayId; occupiedBy: TrayId }
| { type: 'clearanceGiven'; trainId: TrayId; allow: boolean }
// -- load / unload
| { type: 'passengersBoarded'; player: PlayerIndex; at: GridCoord }
| { type: 'passengersDetrained'; player: PlayerIndex; at: GridCoord }
/**
* `trayId` and `coachIndex` name the TRAIN and the COACH the Porter worked, rather than leaving the
* reducer to find them again — the same lesson as `unloadBegan`'s `carIndex` below. Re-deriving
* "the first empty coach on the first train at the Office" is how two trains standing at one
* station both answered to one roster chip (v0.4.9d playtest), and how a coach the player had not
* chosen got filled. Required, not optional: an event is a fact, and a fact that has to be looked
* up against live state cannot render standalone in a replay.
*/
| { type: 'passengersBoarded'; player: PlayerIndex; at: GridCoord; trayId: TrayId; coachIndex: number }
| { type: 'passengersDetrained'; player: PlayerIndex; at: GridCoord; trayId: TrayId; coachIndex: number }
| { type: 'loadStarted'; player: PlayerIndex; at: GridCoord; carType: CarType }
| { type: 'loadAdvanced'; player: PlayerIndex; at: GridCoord; fromBox: number; toBox: number }
| { type: 'unloadCompleted'; player: PlayerIndex; at: GridCoord; carType: CarType }
| { type: 'loadCompleted'; player: PlayerIndex; at: GridCoord; carType: CarType }
| { type: 'unloadBegan'; player: PlayerIndex; at: GridCoord; carType: CarType }
/**
* `carIndex` carries the SPECIFIC car the player picked off the industry track — see the comment
* on `laborer.beginUnload` in `apply.ts` for why the reducer must not re-derive it.
*/
| { type: 'unloadBegan'; player: PlayerIndex; at: GridCoord; carType: CarType; carIndex: number }
// -- consequences
| { type: 'revenueChanged'; player: PlayerIndex; delta: number; total: number; reason: string }
| { type: 'phaseEnded'; player: PlayerIndex; phase: string };
+87 -9
View File
@@ -13,10 +13,28 @@ import type { CardId, GridCoord, PlayerIndex, SeatIndex, TrayId } from './state.
export type LocalOpsOption = 'switch' | 'draw' | 'freightAgent';
/**
* Where an Extra is placed when it is started (§7).
*
* `mainline` names a node index in `division.nodes` and is only ever an Interchange; `office` names
* a SEAT, which is what an Office Area belongs to, and only ever a Control Point.
*/
export type ExtraStart =
| { kind: 'divisionPoint'; side: Direction }
| { kind: 'mainline'; node: number }
| { kind: 'office'; seat: SeatIndex };
export type Intent =
| { type: 'localOps.choose'; option: LocalOpsOption }
// -- switch (§6.1, Appendix A)
| { type: 'switch.move'; trayId: TrayId; to: GridCoord; reverse: boolean }
/**
* `via` names one INTERMEDIATE card on the chosen route, for the rare case where two routes to
* `to` couple different cars (see docs/plans/switching-paths.md) — never the start, never `to`
* itself. Absent, it resolves exactly as it always has: the first route `legal.ts` enumerated to
* `to`. An index into the destination list would do the same job worse — intents are the
* canonical record `undo` replays against, and enumeration order is not a stable thing to save.
*/
| { type: 'switch.move'; trayId: TrayId; to: GridCoord; reverse: boolean; via?: GridCoord }
/**
* Set out a cut. `fromNose` takes it off the FRONT of the train rather than the back — Appendix A's
* worked example does exactly this: "Back up and drop off everything on the nose of your train
@@ -67,12 +85,31 @@ export type Intent =
| { type: 'newTrain.placeCar'; trayId: TrayId; carType: CarType; loaded: boolean }
| { type: 'newTrain.passCar'; trayId: TrayId }
/**
* §7 — "the player who played the card may place the Crew Tray in either division point for
* immediate departure", extended by Jesse: an Extra starts at the Division Point its NUMBER sends
* it to (odd runs west, even east, exactly as a timetabled train), or at any Control Point — any
* Office above a Whistle Post — at the player's choice. `atSeat` null means the Division Point.
* §7 — "the player who played the card may place the Crew Tray at EITHER Division Point for
* immediate departure", plus Jesse's ruling on where else and which way.
*
* The number does not decide an Extra's direction — the START does. Either Division Point may be
* chosen and the train runs away from it (west end runs east, east end runs west, since the other
* reading is a train that leaves the Division having crossed nothing). At an Interchange or a
* Control Point, which are in the middle of the railroad, both ways are real runs and `direction`
* says which; it is required there and ignored at a Division Point.
*
* WHICH STARTS ARE OFFERED is the `extraStart` house rule (content.ts) — Division Points and the
* Interchange always, Offices by setting.
*
* `atSeat` IS LEGACY AND WRITE-ONCE. Saves written before this choice existed carry only that
* field: `null` meant "the Division Point this train's number sends it to" and a seat meant that
* Office, both running in the number's direction. `start` absent is exactly what those saves said,
* so they replay unchanged; everything written from now on carries `start` and `atSeat` is
* omitted. `resolveExtraStart` (apply.ts) is the single place that reads either.
*/
| { type: 'newTrain.startExtra'; trainNumber: number; atSeat: SeatIndex | null }
| {
type: 'newTrain.startExtra';
trainNumber: number;
atSeat?: SeatIndex | null;
start?: ExtraStart;
direction?: Direction;
}
/** Q9 — run a second, identical section behind a train that is due out this Stage. */
| { type: 'newTrain.secondSection'; trainNumber: number }
// -- Mainline Phase (§8.1) — the Superintendent's clearance ruling
@@ -94,8 +131,18 @@ export type Intent =
| { type: 'maneuver.flyingSwitch'; cardId: CardId; trayId: TrayId; count: number; to: GridCoord }
| { type: 'redFlag.play' }
// -- Load/Unload Phase (§9)
| { type: 'porter.board'; at: GridCoord }
| { type: 'porter.detrain'; at: GridCoord }
/**
* `trayId` names the train the Porter works — reported from playtesting v0.4.9d as "operating two
* trains in a station, the select button does not work: regardless of which you pick, it is always
* one train, not the other". It was: neither intent carried a train, so the reducer took the first
* one on the A/D tracks and the roster chip the player had clicked changed nothing but the drawing.
*
* OPTIONAL, like `switch.move`'s `via` and for the same reason: intents are the canonical record
* `undo` and every save replay against, and absent means what it has always meant — the first
* eligible train at the Office.
*/
| { type: 'porter.board'; at: GridCoord; trayId?: TrayId }
| { type: 'porter.detrain'; at: GridCoord; trayId?: TrayId }
/** §9.3 — the first Laborer step: Green Loading Slot -> MEN. */
| { type: 'laborer.startLoad'; at: GridCoord }
| { type: 'laborer.advanceLoad'; at: GridCoord; box: number }
@@ -143,6 +190,11 @@ export type RejectionCode =
| 'ON_RUNNING_TRACK'
/** A card with no east-west road would dead-end the Running Track it was laid in. */
| 'BREAKS_RUNNING_TRACK'
/**
* §2.1 — track, and the Facilities that carry it, stay inside your own Limits at every row. A
* Modifier is not track and is exempt (§9's nine spots), which is why this is not shared with it.
*/
| 'OUTSIDE_LIMITS'
/**
* A turnout may be laid on top of a straight, or of a curve on the same arc as its diverging leg
* — but only those, and only while the square is idle. See `checkTurnoutUpgrade`.
@@ -187,6 +239,17 @@ export type RejectionCode =
* the Laborers can move it out of the box.
*/
| 'NO_EMPTY_CAR_SPOTTED'
/**
* §9 (Jesse's ruling, v0.4.9e) — freight or passengers loaded anywhere in an Office Area may not
* be unloaded anywhere in that same Office Area. The load has to be carried out of the district by
* a train first; a Freight House may not break the load it just made, and passengers may not
* detrain at the platform they boarded from.
*
* Distinct from the other refusals because the car IS loaded, the Laborer IS free and the boxes
* ARE clear: the only thing wrong with it is where it came from, and a player looking at a loaded
* boxcar standing on their own industry track deserves to be told that rather than "wrong car".
*/
| 'LOADED_IN_THIS_DISTRICT'
| 'NO_PORTERS_HERE'
| 'NO_PASSENGERS_WAITING'
| 'NO_EMPTY_COACH'
@@ -196,7 +259,22 @@ export type RejectionCode =
| 'NOT_A_CONTROL_POINT'
| 'NO_EXTRA_PENDING'
| 'NO_FREE_TRAY'
| 'NO_FREE_AD_TRACK';
| 'NO_FREE_AD_TRACK'
// -- §7, where an Extra may be started (`resolveExtraStart`)
| 'NO_SUCH_DIVISION_POINT'
/** Only the Interchange has a yard an Extra can be made up in. */
| 'NOT_AN_INTERCHANGE'
/** In the middle of the railroad both ways are real runs, so the intent has to say which. */
| 'NO_DIRECTION_CHOSEN'
/** The `extraStart` house rule is `divisionPointsOnly`. */
| 'OFFICE_STARTS_NOT_ALLOWED'
/** The `extraStart` house rule is `ownOffice` and this is somebody else's district. */
| 'NOT_YOUR_OFFICE'
/**
* §6.2, Jesse's ruling (Gitea#6) — a train card is never discarded. Hold it as long as you like;
* the only way it leaves your hand is onto the timetable.
*/
| 'TRAINS_ARE_NEVER_DISCARDED';
export type Rejection = { code: RejectionCode; message: string };
+108 -11
View File
@@ -13,13 +13,42 @@
*/
import type { CarType, Hand, TrackGeometry } from './content.ts';
import { enhancementRule } from './content.ts';
import { enhancementRule, mainlineProfile } from './content.ts';
import { check, areaOf, destinationsFor } from './apply.ts';
import type { Intent } from './intents.ts';
import type { GameState, GridCoord, PlayerIndex } from './state.ts';
import { seatOf } from './state.ts';
import { coordKey, seatOf } from './state.ts';
import type { MoveDestination } from './track.ts';
import { variantsFor } from './track.ts';
/**
* A square GridCoord this route passes through that no OTHER route to the same destination does —
* the discriminator `switch.move.via` needs so `selectDestination` (apply.ts) never has to guess
* which of two routes an intent meant. `siblings` is every route the same `destinationsFor` call
* returned at this same square; `route` must be one of them.
*
* Absent when `route` is the only route there (the overwhelmingly common case — `via` need not be
* carried at all), or when the destination is one hop away, which is never ambiguous: the square
* immediately before a given entry port is fixed by geometry, so a zero-length path cannot have a
* sibling.
*/
function distinguishingVia(route: MoveDestination, siblings: readonly MoveDestination[]): GridCoord | undefined {
if (route.path.length === 0) return undefined;
const otherSquares = new Set<string>();
for (const sibling of siblings) {
if (sibling === route) continue;
for (const step of sibling.path) otherSquares.add(coordKey(step.coord));
}
for (const step of route.path) {
if (!otherSquares.has(coordKey(step.coord))) return step.coord;
}
// Every square on this route is shared with some sibling — geometrically possible only if the
// routes fork and rejoin more than once, which `track.ts`'s doc comment says not to rely on not
// happening. Naming the last square before the destination at least matches today's behaviour:
// wrong in the same way a route with no `via` at all would be.
return route.path[route.path.length - 1]!.coord;
}
const CAR_TYPES: readonly CarType[] = ['coach', 'boxcar', 'reefer', 'hopper', 'tank', 'caboose'];
/** Every intent `player` may legally submit right now. */
@@ -86,8 +115,20 @@ function localOpsCandidates(s: GameState, player: PlayerIndex): Intent[] {
if (tray.position.at !== 'grid' || tray.position.seat !== seatOf(s, player)) continue;
const from = tray.position.coord;
for (const reverse of [false, true]) {
for (const d of destinationsFor(s, player, trayId, from, reverse)) {
out.push({ type: 'switch.move', trayId, to: d.coord, reverse });
const dests = destinationsFor(s, player, trayId, from, reverse);
// Grouped by destination square so `distinguishingVia` only ever compares routes that are
// actually racing for the same button — two routes to DIFFERENT squares need no `via` to
// tell apart, `to` already does that.
const byCoord = new Map<string, MoveDestination[]>();
for (const d of dests) {
const k = coordKey(d.coord);
(byCoord.get(k) ?? byCoord.set(k, []).get(k)!).push(d);
}
for (const group of byCoord.values()) {
for (const d of group) {
const via = group.length > 1 ? distinguishingVia(d, group) : undefined;
out.push({ type: 'switch.move', trayId, to: d.coord, reverse, ...(via ? { via } : {}) });
}
}
}
for (let n = 1; n <= tray.consist.length; n++) {
@@ -230,14 +271,28 @@ function newTrainCandidates(s: GameState): Intent[] {
out.push({ type: 'newTrain.secondSection', trainNumber: due });
}
/**
* Where a pending Extra starts: its own Division Point, decided by its number, or any Control
* Point. `check` refuses a Whistle Post and a full Office, so every seat is offered and the rules
* do the filtering — one implementation of "is this a Control Point", not two.
* WHERE A PENDING EXTRA MAY START (§7, Jesse's ruling) — every candidate offered, with `check`
* doing the filtering, so "is this a Control Point" and "does the house rule allow it" have one
* implementation each rather than two.
*
* BOTH Division Points, not the one the number dictates: an Extra's direction comes from where it
* is placed. In the middle of the railroad — an Interchange, a Control Point — both ways are real
* runs, so those are offered twice, once per direction.
*/
for (const trainNumber of s.pendingExtras) {
out.push({ type: 'newTrain.startExtra', trainNumber, atSeat: null });
for (const side of ['west', 'east'] as const) {
out.push({ type: 'newTrain.startExtra', trainNumber, start: { kind: 'divisionPoint', side } });
}
for (const [node, n] of s.division.nodes.entries()) {
if (n.kind !== 'mainline' || !mainlineProfile(n.card).sortsCars) continue;
for (const direction of ['west', 'east'] as const) {
out.push({ type: 'newTrain.startExtra', trainNumber, start: { kind: 'mainline', node }, direction });
}
}
for (const seat of s.officeAreas.keys()) {
out.push({ type: 'newTrain.startExtra', trainNumber, atSeat: seat });
for (const direction of ['west', 'east'] as const) {
out.push({ type: 'newTrain.startExtra', trainNumber, start: { kind: 'office', seat }, direction });
}
}
}
return out;
@@ -247,9 +302,21 @@ function loadUnloadCandidates(s: GameState, player: PlayerIndex): Intent[] {
const out: Intent[] = [];
const area = areaOf(s, player);
/**
* ONE OPTION PER TRAIN STANDING AT THE OFFICE, not one per square.
*
* Reported from playtesting v0.4.9d: "operating two trains in a station, the select button does
* not work — regardless of which you pick, it is always one train, not the other". There was only
* ever ONE `board passengers` button, because the intent carried no train; the roster chip chose
* what the board drew and nothing else. Now each eligible train is its own candidate, and `check`
* filters the ones whose card, consist or passengers rule them out.
*/
const traysHere = area.adOccupancy.filter((id) => s.trays.has(id));
for (const coord of facilityCoords(s, player)) {
out.push({ type: 'porter.board', at: coord });
out.push({ type: 'porter.detrain', at: coord });
for (const trayId of traysHere) {
out.push({ type: 'porter.board', at: coord, trayId });
out.push({ type: 'porter.detrain', at: coord, trayId });
}
const f = area.grid.get(`${coord.row},${coord.col}`)?.facility;
if (f) {
out.push({ type: 'laborer.startLoad', at: coord });
@@ -313,5 +380,35 @@ function placementCandidates(s: GameState, player: PlayerIndex): GridCoord[] {
out.push(c);
}
}
/**
* THE NINE-SPOT MODIFIER NEIGHBOURHOOD (§9), which the four-square walk above cannot reach.
*
* A Modifier goes "adjacent to a Facility, on any of the nine nearby spots" — diagonals included —
* and `check` has always accepted all eight. It was the CANDIDATES that were orthogonal-only, so a
* diagonal square with no orthogonal neighbour was legal and never offered: reported by Jesse as
* being unable to place a Modifier to the south-east of his industry.
*
* Only around a Facility, and only in a second pass. Track has to JOIN, and a diagonal shares no
* edge, so a Modifier is the only card these squares can ever take — generating diagonals around
* every card instead costs 54% more simulation time for candidates `check` then rejects. Appending
* rather than interleaving leaves the existing order untouched, which matters because the bot
* breaks ties by first-best: measured over 200 seeded games, 0 played differently.
*/
for (const [key, card] of area.grid) {
if (!card.facility) continue;
const [row, col] = key.split(',').map(Number);
for (const c of [
{ row: row! + 1, col: col! + 1 },
{ row: row! + 1, col: col! - 1 },
{ row: row! - 1, col: col! + 1 },
{ row: row! - 1, col: col! - 1 },
]) {
const k = `${c.row},${c.col}`;
if (seen.has(k) || area.grid.has(k)) continue;
seen.add(k);
out.push(c);
}
}
return out;
}
+21 -3
View File
@@ -17,7 +17,7 @@ import {
MODIFIER_PROFILES,
OFFICE_PROFILES,
OPENING_DEALS,
MAINLINE_PROFILES,
MAINLINE_DECK,
houseRules,
mainlineProfile,
TRACK_CARDS,
@@ -153,6 +153,7 @@ function buildOfficeArea(seat: SeatIndex): OfficeArea {
geometry: { kind: 'office' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: buildPassengerFacility('whistlePost'),
modifiers: [],
enhancements: [],
@@ -162,6 +163,7 @@ function buildOfficeArea(seat: SeatIndex): OfficeArea {
geometry: { kind: 'limits' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -218,11 +220,27 @@ function buildPassengerFacility(tier: Parameters<typeof officeProfile>[0]): NonN
* placed between each player"), which is what gives the Division its terrain and therefore its
* crossing times.
*/
/**
* THE MAINLINE CARDS ARE DEALT FROM A DECK, NOT ROLLED.
*
* `MAINLINE_PROFILES` is a list of card TYPES and this drew from it uniformly WITH replacement, so
* a Division could be handed two Interchanges or two Tunnels, and Plains — printed twice in the
* deck — carried the same weight as cards printed once. `MAINLINE_DECK` is the printed inventory
* (`docs/StationMaster-Mainline-Deck-v0.4.5.md`, which flagged this as needing correction), and the
* deal is now a deal: take cards out of it and do not put them back.
*
* The Extra-start rules are what forced the issue. "An Extra may start at the Interchange if one is
* on the board" only reads as a rule if the board can hold at most one.
*
* A Division needs `players + 1` cards, so four players draw five from ten and the deck is never
* close to exhausted; the throw is there because a silent short Division would be very hard to see.
*/
function buildDivision(players: number, rng: Rng): DivisionNode[] {
const nodes: DivisionNode[] = [];
const kinds = MAINLINE_PROFILES.map((m) => m.kind);
const deck = [...MAINLINE_DECK];
const mainline = (): DivisionNode => {
const card = kinds[rng.nextInt(kinds.length)]!;
if (deck.length === 0) throw new Error('the Mainline deck ran out — too many players for it');
const card = deck.splice(rng.nextInt(deck.length), 1)[0]!;
const node: DivisionNode = { kind: 'mainline', card, transits: [] };
// The Heavy Grade card says "Player sets orientation", but setup has no decision point yet —
// createGame is synchronous and returns a ready state. Rolled for now so the orientation is at
+103 -30
View File
@@ -56,7 +56,47 @@ export function coordKey(c: GridCoord): string {
// ---------------------------------------------------------------------------
/** §2.2 — a coloured car is loaded, a white car is empty. */
export type RollingStock = { type: CarType; loaded: boolean };
export type RollingStock = {
type: CarType;
loaded: boolean;
/**
* WHICH OFFICE AREA MADE THIS LOAD — the physical game's chip turned upside down in the tray.
*
* Reported from playtesting v0.4.9d as two bugs with one cause: a boxcar loaded at a Freight
* House could be unloaded at that same Freight House on the next Laborer action, and passengers
* who had just boarded could be detrained again before the train turned a wheel. Both paid full
* Revenue at each end for a load that never went anywhere.
*
* Jesse's rule (v0.4.9e): freight or passengers loaded anywhere in an Office Area may not be
* unloaded ANYWHERE in that same Office Area — not at another facility, not in a later Stage.
* They have to be carried by a train to a different Office Area. So the stamp is the SEAT, which
* is what an Office Area belongs to (Employee Rotation moves players between chairs; the district
* stays with the chair), and it never expires.
*
* A SEAT, NOT A PLAYER, and undefined rather than -1 for "no origin": the Division Yard opens with
* loaded cars and loaded coaches that were made up off-Division (`ROLLING_STOCK_SUPPLY`), and
* those are exactly the inbound traffic a solitaire district lives on. A sentinel inside
* `SeatIndex`'s own value range is not a sentinel — see `card.play`'s `node` in intents.ts.
*
* Stripped by `pooled` whenever a car goes back to a yard: the stamp belongs to the LOAD, and a
* car returning to the common supply is carrying nothing.
*/
origin?: SeatIndex;
};
/**
* A car returning to the common pool — the Division or Classification Yard — with its load's origin
* stamp taken off.
*
* Every yard push goes through this. A loaded car CAN reach a yard still loaded (a train retires at
* a Division Point with freight aboard, `advance.ts`), and without this it would carry a stamp from
* a district it left several Days ago into whatever train is made up from it next.
*/
export function pooled(car: RollingStock): RollingStock {
if (car.origin === undefined) return car;
const { origin: _origin, ...rest } = car;
return rest;
}
// ---------------------------------------------------------------------------
// Track and Office Area
@@ -137,9 +177,35 @@ export type TrackCard = {
* WEST-TO-EAST IS THE BOARD'S ORIENTATION, not the train's, which is exactly why it is the right
* one: it is a property of the card, so it does not change when a different train touches it. The
* two conversions are stated once, in `apply.ts`'s `carsDropped` and `carsCoupled` reducers, and
* `CrewTray.standingWest` records where a train standing here sits among them.
* `standingWest` below records where a train standing here sits among them.
*/
standing: RollingStock[];
/**
* HOW MANY OF `standing` LIE WEST OF THE TRAIN(S) STANDING HERE.
*
* `standing` runs west to east and a train sits somewhere IN that row: cars `[0, standingWest)`
* are west of it, cars `[standingWest, end)` are east. A train can set out off both ends on the
* same square — §A.3 lets a cut come off either outer end — so "which side is this cut on" is not
* recoverable from the array alone, and it is the question every remaining rule asks: which cars
* are AHEAD of an engine and which BEHIND (combine with `CrewTray.railFacing`), which cut a
* departing train must couple back up (the one at the end it leaves by), and which side of the
* chip the renderer draws the cut on.
*
* WITH NO TRAIN STANDING HERE, THIS NUMBER MEANS NOTHING: a card's cars are simply a cut with no
* near or far side, and the next train to arrive couples all of them regardless — nothing reads
* `standingWest` in that state, so a stale value left over from a train that has since moved on is
* inert, not wrong. That reasoning is unchanged from when this lived on `CrewTray`.
*
* WHAT MOVED IT TO THE CARD: the Office square is the one place more than one train may stand at
* once, and only one route lets two trays disagree about the same row of cars — a train already
* at the Office sets out a cut in place, without moving, while a second train on another A/D track
* still holds whatever split it arrived with. A cut lies west or east of the WHOLE block of A/D
* tracks, never of one particular track and never between two trains, so there is exactly one
* number for the card to carry and every train standing there reads the same one. Everywhere else
* on the board at most one train ever stands on a card, so the two homes for this field are
* identical in every other case.
*/
standingWest: number;
facility: Facility | null;
modifiers: ModifierKind[];
/** Enhancement cards laid on this card (§7 of implications.md). */
@@ -289,6 +355,23 @@ export type CrewTray = {
/** null while a local crew is switching without a train card. */
trainNumber: number | null;
trainIsExtra: boolean;
/**
* STILL BEING ASSEMBLED, somewhere that is not a Division Point.
*
* `isBeingMadeUp` used to read the position alone — "standing at a Division Point" — which was
* true of every train being built when the only place to build one WAS a Division Point. An Extra
* may now be started at a Control Point or in an Interchange's yard (§7), and those trains could
* not be given a consist at all: they ran empty, and so did every Control Point Extra since that
* option was added. Jesse's report says it plainly — an Extra started at the Interchange "would be
* loaded with cars".
*
* Set when such an Extra is placed and cleared the moment it starts running (`enterMainline`), so
* it names a train that is being made up rather than one that merely happens to be standing
* somewhere. That distinction is load-bearing: a train that ARRIVED at an Office must never be
* fillable from the Division Yard, which is the "cars appearing on a train nobody was making up"
* bug `isBeingMadeUp` was tightened to kill, and an arriving train never carries this.
*/
beingMadeUp?: boolean;
/**
* WHERE THE ENGINE SITS IN THE TRAY, as an index into `consist`.
*
@@ -345,25 +428,6 @@ export type CrewTray = {
* puts the engine on the other end, which is the one thing the arrow exists to show.
*/
railFacing?: 'e' | 'w';
/**
* HOW MANY OF THIS CARD'S STANDING CARS LIE WEST OF THIS TRAIN.
*
* `carsOn(card)` runs west to east and a train standing on the card sits somewhere IN that row:
* cars `[0, standingWest)` are west of the engine, cars `[standingWest, end)` are east of it. A
* train can set out off both ends on the same square — §A.3 lets a cut come off either outer end —
* so "which side is this cut on" is not recoverable from the array alone, and it is the question
* every remaining rule asks.
*
* It answers all three: which cars are AHEAD of the engine and which BEHIND (combine with
* `railFacing`), which cut a departing train must couple back up (the one at the end it leaves
* by), and which side of the chip the renderer draws the cut on.
*
* Kept on the TRAY rather than the card because it describes a relationship, not the card: with no
* train standing there, a card's cars are simply a cut with no near or far side, and the next
* train to arrive couples all of them regardless. Reset to 0 on every move, which is sound because
* coupling is mandatory — a train arrives on a card it has just emptied.
*/
standingWest?: number;
position: NodeRef;
movesUsed: number;
/**
@@ -377,17 +441,12 @@ export type CrewTray = {
* X17 Campaign Train — "one turn at station (speeches) then expedite".
*
* It makes its speech at the first Office it reaches: that arrival is an ordinary stop, and from
* then on the train runs expedited, departing every Office in the Stage it arrives. Recorded on the
* tray for the same reason as `stopPointClaimed` — it is the TRAIN that stops, and an Extra runs
* once, so there is no later visit to hang it on.
* then on the train is expedited — it may be switched normally, but it faults (Q3) if it is left
* off the Office square when a Mainline Phase begins. Recorded on the tray for the same reason as
* `stopPointClaimed` — it is the TRAIN that stops, and an Extra runs once, so there is no later
* visit to hang it on.
*/
speechMade?: boolean;
/**
* Arrived expedited this Stage, so it departs at the END of the Stage rather than laying over to
* the next one (Q3). Set on arrival; cleared when `shiftChange` attempts the departure — after
* Load/Unload, which is what gives the Porters their one Stage with the train.
*/
departsThisStage?: boolean;
};
// ---------------------------------------------------------------------------
@@ -423,6 +482,20 @@ export type DivisionNode =
kind: 'mainline';
card: MainlineKind;
transits: Transit[];
/**
* TRAINS STANDING IN THE INTERCHANGE'S YARD — not out on the running line.
*
* Only an Interchange ever has these. An Extra started there (§7, Jesse's ruling) is made up
* in the yard beside the Mainline, which is why placing it can never be a collision however
* busy the card is: it is not on the road yet. It highballs onto this same card at a later
* Mainline Phase, through the ordinary §8.1 clearance check — held automatically against a
* facing train, put to the Superintendent against a following one — and becomes a `Transit`
* at that moment, exactly like a train leaving a Division Point.
*
* A tray listed here has `position.at === 'mainline'` with this node's index and NO entry in
* `transits`. That pair is what distinguishes standing from crossing.
*/
holding?: TrayId[];
absSignals?: boolean;
/** Brakeman / Airbrakes / Helpers / Realignment laid on this card. */
modifiers?: string[];
+101 -27
View File
@@ -316,15 +316,6 @@ export type MoveContext = {
consistSize: number;
/** The tray making the move, so it does not block itself. */
self: TrayId;
/**
* How many cars on the START card stand west of this train (`CrewTray.standingWest`).
*
* The walk begins at `neighbour(start, initialExit)` and never looked at the start card at all, so
* a train drove straight through the cut it had just set out — in both directions, and without
* counting it against the four-car limit. Coupling is mandatory (§A.4) and a cut on your own
* square is no exception: pulling out through the end it sits at picks it up again.
*/
standingWest?: number;
};
function cardAt(area: OfficeArea, c: GridCoord): TrackCard | undefined {
@@ -383,6 +374,28 @@ export type MoveBlock = { coord: GridCoord; kind: MoveBlockKind; why: string };
* beyond a reachable one whose rails do not meet. Squares the walk never came near are not listed:
* "there is no track between here and there" is not news.
*/
/**
* How many frontier nodes a single `exploreMoves` walk may enqueue before it stops finding new
* routes. A per-path visited set (below) guarantees every individual route terminates, but the
* NUMBER of simple paths through a dense district is worst-case exponential — a real board never
* gets close, but nothing stops a pathological one from being built. BFS order means the queue
* fills shortest-route-first, so hitting the cap loses only the longest, least-likely-to-matter
* routes; it never loses a shorter one in favour of a longer one.
*/
const MAX_ENUMERATED_FRONTIER = 4000;
/**
* The identity of a route's OUTCOME, for dedupe: which square it ends at, which side it entered
* by, and exactly which cars it couples, each tagged with the card it came off. Two routes that
* couple the same car TYPES from DIFFERENT cards are not the same outcome — sweeping the wrong
* card clean is exactly the bug this key exists to avoid — so the origin card rides along with
* every car, not just its type.
*/
function routeOutcomeKey(coord: GridCoord, entry: Port, couples: RollingStock[], origins: string[]): string {
const cars = couples.map((c, idx) => `${origins[idx]}:${c.type}:${c.loaded ? 1 : 0}`).join(',');
return `${coordKey(coord)}|${entry}|${cars}`;
}
export function exploreMoves(
ctx: MoveContext,
start: GridCoord,
@@ -403,9 +416,20 @@ export function exploreMoves(
if (!startCard) return { destinations: results, blocked };
if (!hasPort(startCard, initialExit)) return { destinations: results, blocked };
const seen = new Set<string>();
const resultKeys = new Set<string>();
type Frontier = { coord: GridCoord; entry: Port; path: MoveStep[]; couples: RollingStock[] };
type Frontier = {
coord: GridCoord;
entry: Port;
path: MoveStep[];
couples: RollingStock[];
/** Coord key each entry in `couples` came off, aligned by index — see `routeOutcomeKey`. */
origins: string[];
/** Cards visited on THIS route, start included. A per-path set, not a global one — see the
* module doc comment on `MAX_ENUMERATED_FRONTIER` for why a global one would forbid the very
* routes this walk exists to find. */
visited: Set<string>;
};
// The very first hop is checked here because `start`'s card is not itself enqueued; every later
// hop is checked at the push site below, where both sides of the edge are in hand.
@@ -426,10 +450,19 @@ export function exploreMoves(
*
* Ordered nearest-first like every other card's, so it simply seeds the accumulator.
*/
const ownCut = cutTowards({ standingWest: ctx.standingWest }, carsOn(startCard), initialExit);
const ownCut = cutTowards(startCard, carsOn(startCard), initialExit);
const startKey = coordKey(start);
const queue: Frontier[] = [
{ coord: first, entry: opposite(initialExit), path: [], couples: ownCut },
{
coord: first,
entry: opposite(initialExit),
path: [],
couples: ownCut,
origins: ownCut.map(() => startKey),
visited: new Set([startKey]),
},
];
let enumerated = 1;
while (queue.length > 0) {
const node = queue.shift()!;
@@ -476,6 +509,8 @@ export function exploreMoves(
*/
const met = node.entry === 'e' ? [...carsOn(card)].reverse() : carsOn(card);
const couples = [...node.couples, ...met];
const nodeKey = coordKey(node.coord);
const origins = [...node.origins, ...met.map(() => nodeKey)];
if (ctx.consistSize + couples.length > MAX_CONSIST) {
const own =
ownCut.length > 0
@@ -489,18 +524,24 @@ export function exploreMoves(
continue;
}
const key = `${coordKey(node.coord)}|${node.entry}`;
if (seen.has(key)) continue;
seen.add(key);
if (isOperationalRail(card) && !sameCoord(node.coord, start)) {
results.push({ coord: node.coord, entry: node.entry, path: node.path, couples });
// Dedupe on OUTCOME, not on reaching the square: two routes that end here having coupled
// different cars (or the same cars off different cards) are a real choice, and both are
// offered. Two routes that end here having coupled identically are not a choice — one is
// noise doubling the button list and the bot's branching factor for nothing.
const rkey = routeOutcomeKey(node.coord, node.entry, couples, origins);
if (!resultKeys.has(rkey)) {
resultKeys.add(rkey);
results.push({ coord: node.coord, entry: node.entry, path: node.path, couples });
}
} else if (!sameCoord(node.coord, start)) {
// Reached, crossable, but not somewhere a train may STOP — a turnout carries no wheel icon
// (§A.1). Trains run through one all day; they just cannot finish a Move on it.
block(node.coord, 'noStopping', 'a train may run through here but not stop — this is not Operational Rail (§A.1), so it cannot be the end of a Move');
}
if (enumerated >= MAX_ENUMERATED_FRONTIER) continue;
for (const exit of exitsFrom(card, node.entry)) {
// Slope is a property of the EDGE, not of either card, so it can only be tested with both in
// hand. Enqueueing on `hasPort` alone routed trains across a 45° leg that bent back on itself.
@@ -510,8 +551,18 @@ export function exploreMoves(
if (next) block(to, 'noJoin', 'the rails do not meet — two cards touching is not a join, and on a north or south edge both 45° legs must lie on the same diagonal');
continue;
}
// A card twice on ONE route is a loop, not a longer route (§2.4 travels without changing
// direction; it never says without repeating ground, but a train cannot occupy the same
// track twice at once either). Per-path, not global — a DIFFERENT route may legitimately
// pass through a card this one already used.
const toKey = coordKey(to);
if (node.visited.has(toKey)) continue;
if (enumerated >= MAX_ENUMERATED_FRONTIER) break;
enumerated++;
const step: MoveStep = { coord: node.coord, entry: node.entry, exit };
queue.push({ coord: to, entry: opposite(exit), path: [...node.path, step], couples });
const visited = new Set(node.visited);
visited.add(toKey);
queue.push({ coord: to, entry: opposite(exit), path: [...node.path, step], couples, origins, visited });
}
}
@@ -559,6 +610,31 @@ export function carriesThroughTrack(card: TrackCard): boolean {
* a TURNOUT laid on the Running Track — the Office no longer carries a stub of its own, because no
* office or industry card on the printed sheet does.
*/
/**
* §2.1 — IS THIS SQUARE INSIDE THE DISTRICT AT ALL?
*
* The Limits sign denotes "the limit of your control area", and §3 defines Secondary Track as "all
* tracks IN YOUR LIMITS that are not the Running Track" — so the bound belongs to the district, not
* to the one row the sign happens to stand in. This used to guard the Running Track alone, on the
* reasoning that the rows above and below were unbounded; the consequence was a siding snaking east
* past your own sign, taking industries with it, and a player switching cars on track outside the
* territory §8.1 and §10 reason about. Reported by Jesse: sidings must not be built outside the
* Limits.
*
* INCLUSIVE OF THE SIGN'S OWN COLUMN. The sign stands ON the boundary rather than beyond it, and the
* opening district is signs at ±1 around the Office — so the strict reading would leave exactly one
* buildable column and break §11.3's promise that both Secondary rows, and the nine-spot Modifier
* neighbourhood, are usable from the first Stage.
*
* MODIFIERS ARE NOT SUBJECT TO THIS, and are not track: §9 places one on any of the nine spots
* around a Facility, and a Facility standing at the limit has three of its nine outside them.
* Jesse's call. `check` bars them from the Running Track ROW instead, which is the ground the main
* grows onto.
*/
export function withinLimits(area: OfficeArea, coord: GridCoord): boolean {
return coord.col >= area.limitsWest.col && coord.col <= area.limitsEast.col;
}
export function canPlaceAt(area: OfficeArea, coord: GridCoord, card: TrackCard): boolean {
const existing = cardAt(area, coord);
// A Limits sign on the Running Track is the GROWTH POINT, not an obstacle. Extending means laying
@@ -575,14 +651,12 @@ export function canPlaceAt(area: OfficeArea, coord: GridCoord, card: TrackCard):
// the sign itself is the only growth point. Allowing a placement beyond it built track on the far
// side of the sign and then planted a SECOND sign further out, leaving the board reading
// limits · Whistle Post · limits · straight · limits
// with a Limits card stranded mid-track. The district below the Running Track is unbounded.
if (coord.row === area.runningRow) {
if (coord.col < area.limitsWest.col || coord.col > area.limitsEast.col) return false;
// And it must not BREAK the Running Track. A curve laid here has no east-west road, so the main
// stops dead at it — the bot did exactly this, turning the west end of its own Running Track
// into a stub and cutting the Office off from the Limits.
if (!carriesThroughTrack(card)) return false;
}
// with a Limits card stranded mid-track.
if (!withinLimits(area, coord)) return false;
// And it must not BREAK the Running Track. A curve laid here has no east-west road, so the main
// stops dead at it — the bot did exactly this, turning the west end of its own Running Track
// into a stub and cutting the Office off from the Limits.
if (coord.row === area.runningRow && !carriesThroughTrack(card)) return false;
const ports: Port[] = ['n', 's', 'e', 'w'];
for (const p of ports) {
+188 -42
View File
@@ -51,6 +51,14 @@ export function divisionSvg(nodes: DivisionView[]): string {
const CW = { dp: 118, ml: 152, run: 78 };
const CH = 58;
const GAP = 6;
/**
* ONE FIXED SLOT PER A/D TRACK, so the Office Running Track cell is drawn wide enough to hold
* them without spilling onto its neighbours (docs/plans/switching-paths.md — "The Roster Pass").
* Sized by CAPACITY, not by how many are occupied right now: a cell drawn for the trains it HAS
* holds still as they come and go, where sizing by occupancy moved the East Division Point (and
* everything past it) sideways every time an A/D track filled or cleared.
*/
const CHIP_W = 54;
/**
* Room for the buffer stops. THE LABELS NO LONGER LIVE OUT HERE.
*
@@ -128,7 +136,7 @@ export function divisionSvg(nodes: DivisionView[]): string {
// No regions inside 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,
w: CW.run,
w: isOffice && cap !== null ? Math.max(CW.run, cap * CHIP_W + 12) : CW.run,
});
}
// A crew below the Running Track has no position ON it, so it is reported against the
@@ -143,15 +151,30 @@ export function divisionSvg(nodes: DivisionView[]): string {
continue;
}
const dp = n.kind === 'dp';
/**
* A train in the Interchange's yard is drawn on the card but counted against nothing.
*
* It is not on the running line — that is the whole distinction §7 rests on — so it cannot take
* the card's capacity. It still has to be SEEN: an Extra made up here would otherwise be a train
* the player just placed that appears nowhere on the map.
*/
const inYard = n.yard ?? [];
const onRoad = n.trains.flat();
const free = n.capacity === null ? '' : `${Math.max(0, n.capacity - onRoad.length)} of ${n.capacity} free`;
push({
kind: dp ? 'dp' : 'ml',
label: n.label,
sub: n.capacity === null ? 'no limit — trains queue' : `${Math.max(0, n.capacity - n.trains.flat().length)} of ${n.capacity} free`,
trains: n.trains.flat(),
sub: n.capacity === null
? 'no limit — trains queue'
: [free, inYard.length > 0 ? `${inYard.length} in the yard` : ''].filter(Boolean).join(' · '),
trains: [...onRoad, ...inYard],
cap: n.capacity,
tip: dp
? 'A Division Point — the end of the line. Trains both enter and leave the Division here (odd numbers run west, even run east), and queue without limit'
: `${n.label} — Mainline${n.gradeUp ? `, climbs ${n.gradeUp === 'east' ? 'east' : 'west'}` : ''}${n.modifiers.length ? ` · ${n.modifiers.join(' · ')}` : ''}` +
(inYard.length > 0
? `\n\n${inYard.length} train${inYard.length === 1 ? '' : 's'} standing in the yard, not on the running line — waiting to highball onto this card`
: '') +
// What the card actually DOES. The name alone left Hilly and Uncontrolled Siding as
// words with no gameplay attached — reported exactly that way.
(n.what ? `\n\n${n.what}` : ''),
@@ -301,12 +324,24 @@ export function divisionSvg(nodes: DivisionView[]): string {
const loaded = cars.filter((x) => /^loaded/.test(x) || /caboose/.test(x)).length;
const label = cars.length === 0 ? `${t.label} ${arrow}` : `${t.label} ${arrow}${cars.length}`;
const w = Math.min(c.w - 8, label.length * 6.6 + 12);
/**
* THE OFFICE RUNNING CELL GETS FIXED SLOTS, ONE PER A/D TRACK — never a centre spread.
*
* Centred spreading pushes its outer chips outward as MORE trains arrive, and the cell was
* sized for the cards it holds, not for its trains — so two chips at a Station used to land at
* x 215–267 and 271–316 inside a cell spanning only 230–308, spilling onto the Limits cards
* either side. A fixed slot per A/D track cannot overflow the cell at any occupancy, because
* the cell was sized for exactly that many slots (see `CHIP_W` above).
*/
const isOfficeRun = c.kind === 'run' && c.cap !== null && c.cap > 0;
const slotW = isOfficeRun ? (c.w - 12) / c.cap! : 0;
const w = isOfficeRun ? Math.min(slotW - 4, label.length * 6.6 + 12) : Math.min(c.w - 8, label.length * 6.6 + 12);
// A train on a Mainline card sits in ITS region; anywhere else it just sits on the card.
const inRegion = c.regions > 1 && typeof t.region === 'number';
const slotX = inRegion ? c.x + 6 + RW * (t.region ?? 0) + RW / 2 : c.x + c.w / 2;
const spread = inRegion ? 0 : (k - (c.trains.length - 1) / 2) * (w + 4);
const tx = slotX + spread;
const tx = isOfficeRun
? c.x + 6 + slotW * (k + 0.5)
: (inRegion ? c.x + 6 + RW * (t.region ?? 0) + RW / 2 : c.x + c.w / 2) +
(inRegion ? 0 : (k - (c.trains.length - 1) / 2) * (w + 4));
const dir = t.direction === 'west' ? ' \u25c0 west' : t.direction === 'east' ? ' east \u25b6' : '';
const stages =
typeof t.stagesLeft === 'number'
@@ -383,6 +418,22 @@ export function officeSvg(
* offered without a word. Reported as the Depot lighting up for no visible reason.
*/
legal: { row: number; col: number; label: string }[] = [],
/**
* The columns the Limits signs stand in, drawn as the district's east and west edges.
*
* Omitted by the previews and by the replay viewers' single-card renders, which have no district
* to bound. Where it is given, the boundary is drawn down the WHOLE canvas: track may not be laid
* outside these columns at any row (§2.1), and two signs sitting on one row could not say that —
* a player looking at open ground past a sign had no way to know nothing of his could ever go
* there until the square failed to light up.
*/
limits: { west: number; east: number } | null = null,
/**
* Which train's consist is drawn at the rail, on an Office card holding more than one — the value
* the "Which train are you switching?" picker already carries. Defaults to the first train on the
* card, so every call site that has never heard of this feature keeps working unchanged.
*/
selectedTrayId: string | null = null,
): string {
const W = 166;
const H = 96;
@@ -447,7 +498,15 @@ export function officeSvg(
return { x: W / 2, y: H };
};
let out = `<svg class="bs" viewBox="0 0 ${width} ${height}" preserveAspectRatio="xMinYMin meet">`;
/**
* ROOM FOR THE BOUNDARY. The Limits edge is drawn just outside the sign's own column, and the west
* sign is usually the leftmost card on the canvas — so at x = −1.5 the line lands outside a viewBox
* starting at 0 and is simply not there. The margin is added only when there is a boundary to draw.
*/
const margin = limits ? 3 : 0;
let out =
`<svg class="bs" viewBox="${-margin} 0 ${width + margin * 2} ${height}" ` +
`preserveAspectRatio="xMinYMin meet">`;
for (const cell of cells) {
const x = px(cell.col);
const y = py(cell.row);
@@ -462,10 +521,21 @@ export function officeSvg(
? 'mod'
: 'trk';
// An Office card's roster band (below) takes the y-band the BOARDS + ALIGHTS flow label used to
// print in, so that explanation folds into the card's own tooltip instead of being drawn — it
// prints identically on every Office of every tier and is already implied by the card name and
// the Porter pill, so nothing is lost by reading it on the card rather than beside it.
const isOfficeRoster = cell.adTracks !== null;
const flowFold =
isOfficeRoster && cell.facility
? '\n\nBOARDS + ALIGHTS: passengers only — no freight is handled here. They wait in a green ' +
'box, are boarded onto a coach by Porters, and arrive into a red one.'
: '';
// Addressable so a caller can outline a square as a legal destination without re-rendering.
// The explanation rides on the group as a tooltip rather than being printed: it is reference
// detail, read once, and printing it costs the space the board itself needs.
out += `<g data-cell="${cell.row},${cell.col}" data-tip="${esc(cell.label)} — ${esc(cell.what)}" transform="translate(${x},${y})">`;
out += `<g data-cell="${cell.row},${cell.col}" data-tip="${esc(cell.label)} — ${esc(cell.what)}${esc(flowFold)}" transform="translate(${x},${y})">`;
out += `<rect class="bs-card bs-${kind}${cell.running ? ' bs-run' : ''}" x="0" y="0" width="${W}" height="${H}" rx="4"/>`;
// The rails. A Modifier is not track and deliberately gets none — that is why nothing can be
@@ -497,20 +567,57 @@ export function officeSvg(
out += `<text class="bs-cn" x="6" y="12">${esc(cell.label)}</text>`;
// X,Y — east/west then north/south, not the internal row/col storage order.
out += `<text class="bs-coord" x="${W - 5}" y="12" text-anchor="end">${cell.col},${cell.row}</text>`;
/**
* A/D TRACKS, as pips.
* THE ROSTER, one chip per A/D track — not one per train.
*
* The Office tooltip said "3 A/D tracks" and the card showed nothing — so the number that
* decides whether the next arrival is an automatic collision (§8.3) was invisible on the card it
* belongs to. There is no room to draw more rails, and the count is what matters: one pip per
* track, filled for taken.
* The Office is the one square where more than one train may legally stand at once (its A/D
* tracks, §2.1), and the old single `cell.train` field only ever showed whichever tray
* `s.trays` happened to yield first: a second train at a busy Station was counted in the old
* A/D pips and never drawn at all. `adTracks` of them, always, whether or not a train is
* holding there — the cell is drawn for the tracks it HAS, so a free one reads a dashed,
* dimmed chip saying "free" rather than simply vanishing.
*
* Selected train's chip is lit the same amber the crew strip and action buttons already use,
* and it is the one whose consist is drawn at the rail below. Every occupied chip carries
* `data-crew`, so the play page can wire a click to switch which train that is.
*
* COMPUTED FOR EVERY CARD, NOT JUST THE OFFICE. This used to sit inside the `adTracks !== null`
* branch below, so it was only ever assigned on the Office card — a train standing anywhere else
* in the district (which is everywhere it stands while actually being switched) got no chip at
* all: no label, no engine arrow, and no cars drawn, though the game state never lost it. REPORTED:
* dropping a car at the Freight House made "the train vanish off the face of the earth" — it had
* simply left the one square this code drew a crew on. The Office is the only square that can hold
* more than one train, so `cell.trains[0]` is exactly right everywhere else too.
*/
if (cell.ad) {
for (let i = 0; i < cell.ad.of; i++) {
out += `<circle class="bs-ad${i < cell.ad.used ? ' bs-occ' : ''}" cx="${W - 9 - i * 9}" cy="10" r="3"/>`;
const selectedTrain: CellView['trains'][number] | null =
cell.trains.find((t) => t.trayId === selectedTrayId) ?? cell.trains[0] ?? null;
if (cell.adTracks !== null) {
const adTracks = cell.adTracks;
const gaps = Math.max(0, adTracks - 1);
const chipW = Math.min(52, (W - 12 - 4 * gaps) / adTracks);
for (let i = 0; i < adTracks; i++) {
const train = cell.trains[i] ?? null;
const cx = 6 + i * (chipW + 4);
if (!train) {
out +=
`<g class="bs-adchip mt"><rect x="${cx}" y="20" width="${chipW}" height="14" rx="3"/>` +
`<text x="${cx + chipW / 2}" y="30.5" text-anchor="middle">free</text></g>`;
continue;
}
const arrow = train.facing === 'w' ? '◀' : '▶';
const chipLabel = chipW >= 40 ? `${train.label} ${arrow}${train.cars.length}` : `${train.label}${arrow}`;
const consistWords = train.cars.length === 0 ? 'no cars' : train.cars.join(', ');
const on = train.trayId === selectedTrain?.trayId;
out +=
`<g class="bs-adchip${on ? ' on' : ''}" data-crew="${esc(train.trayId)}" ` +
`data-tip="${esc(`${train.label} — carrying ${consistWords}`)}">` +
`<rect x="${cx}" y="20" width="${chipW}" height="14" rx="3"/>` +
`<text x="${cx + chipW / 2}" y="30.5" text-anchor="middle">${esc(chipLabel)}</text></g>`;
}
}
out += `<text class="bs-coord" x="${W - 5}" y="12" text-anchor="end">${cell.row},${cell.col}</text>`;
/**
* THE LOAD PIPELINE, on the card itself, DRAWN THE WAY IT FLOWS.
@@ -590,15 +697,19 @@ export function officeSvg(
? 'BOARDS + ALIGHTS'
: f.allowsOut && f.allowsIn ? 'SHIPS + RECEIVES' : f.allowsOut ? 'SHIPS OUT' : 'RECEIVES';
const flowCls = passenger || (f.allowsOut && f.allowsIn) ? 'bs-flow-both' : f.allowsOut ? 'bs-flow-out' : 'bs-flow-in';
out += `<text class="bs-flow ${flowCls}" x="${W - 6}" y="26" text-anchor="end" data-tip="${esc(
passenger
? 'Passengers only — no freight is handled here. They wait in a green box, are boarded onto a coach by Porters, and arrive into a red one. There is no MEN | AT | WORK sign because that is a Freight Facility fitting.'
: f.allowsOut && f.allowsIn
? 'This industry both ships and receives, so it has green boxes AND red ones: loads leave it on a car, and loads arrive on one.'
: f.allowsOut
? 'This industry only SHIPS. A load starts in a green box, is worked along MEN | AT | WORK by Laborers, and comes off onto an empty car spotted on its track. It has no red boxes because nothing arrives here.'
: 'This industry only RECEIVES. A loaded car is spotted on its track and Laborers work the load back along WORK | AT | MEN into a red box. It has no green boxes because nothing ships from here.',
)}">${esc(flow)}</text>`;
// An Office card's roster band now occupies this y-band; its tooltip already folded into the
// card's own data-tip above, so the label is not printed twice.
if (!isOfficeRoster) {
out += `<text class="bs-flow ${flowCls}" x="${W - 6}" y="26" text-anchor="end" data-tip="${esc(
passenger
? 'Passengers only — no freight is handled here. They wait in a green box, are boarded onto a coach by Porters, and arrive into a red one. There is no MEN | AT | WORK sign because that is a Freight Facility fitting.'
: f.allowsOut && f.allowsIn
? 'This industry both ships and receives, so it has green boxes AND red ones: loads leave it on a car, and loads arrive on one.'
: f.allowsOut
? 'This industry only SHIPS. A load starts in a green box, is worked along MEN | AT | WORK by Laborers, and comes off onto an empty car spotted on its track. It has no red boxes because nothing arrives here.'
: 'This industry only RECEIVES. A loaded car is spotted on its track and Laborers work the load back along WORK | AT | MEN into a red box. It has no green boxes because nothing ships from here.',
)}">${esc(flow)}</text>`;
}
/**
* THE WORKERS, ON THE CARD.
@@ -654,14 +765,15 @@ export function officeSvg(
* means "ahead" or "behind" is the engine's facing, which the tooltip says in words rather than
* leaving the player to work out from the compass.
*/
const split = cell.train ? Math.max(0, Math.min(cell.cars.length, cell.standingWest ?? 0)) : 0;
const hasTrain = cell.trains.length > 0;
const split = hasTrain ? Math.max(0, Math.min(cell.cars.length, cell.standingWest)) : 0;
const shown = Math.min(cell.cars.length, 4);
for (let i = 0; i < shown; i++) {
// With no train on the card there is no gap to leave, so the whole cut stays left-aligned.
const westOfEngine = cell.train ? i < split : true;
const side = !cell.train
const westOfEngine = hasTrain ? i < split : true;
const side = !selectedTrain
? 'standing here'
: (cell.train.facing === 'e') === westOfEngine
: (selectedTrain.facing === 'e') === westOfEngine
? 'standing BEHIND the engine — it would couple onto the tail backing up'
: 'standing AHEAD of the engine — it would couple onto the nose pulling forward';
const carTip = `${cell.cars[i]} ${side}`;
@@ -722,17 +834,18 @@ export function officeSvg(
(cell.enhancementsWhat ?? []).join(' · '),
)}">${esc(cell.enhancements.join(' · '))}</text>`;
}
if (cell.train) {
if (selectedTrain) {
/**
* THE TRAIN, DRAWN AS IT SITS IN THE TRAY.
* THE SELECTED TRAIN, DRAWN AS IT SITS IN THE TRAY.
*
* The badge used to be a name and nothing more, which makes the switching game unplayable:
* every decision is about car ORDER — which car comes off next, which end a cut couples onto —
* and none of it was on the board. Now the engine and its cars are drawn in sequence, nose
* first, with an arrow for which way the engine points, so "set out the caboose off the back"
* is a thing you can see before you choose it.
* is a thing you can see before you choose it. Where an Office holds more than one train, only
* this one is drawn here — the rest are the roster chips above, each with its own tooltip.
*/
const t = cell.train;
const t = selectedTrain;
const items: { label: string; kind: string; what: string }[] = t.cars.map((c) => ({
label: /caboose/.test(c) ? 'cab' : /hopper/.test(c) ? 'hop' : /boxcar/.test(c) ? 'box'
: /reefer/.test(c) ? 'rfr' : /tank/.test(c) ? 'tnk' : /coach/.test(c) ? 'cch' : '?',
@@ -783,7 +896,7 @@ export function officeSvg(
out += `<g data-ghost="${g.row},${g.col}" transform="translate(${px(g.col)},${py(g.row)})" class="bs-ghost">` +
`<rect x="0" y="0" width="${W}" height="${H}" rx="4"/>` +
`<text x="${W / 2}" y="${H / 2}" text-anchor="middle">place here</text>` +
`<text class="bs-coord" x="${W / 2}" y="${H / 2 + 15}" text-anchor="middle">${g.row},${g.col}</text>` +
`<text class="bs-coord" x="${W / 2}" y="${H / 2 + 15}" text-anchor="middle">${g.col},${g.row}</text>` +
`</g>`;
}
@@ -804,6 +917,22 @@ export function officeSvg(
`<text x="${W / 2}" y="${H - 36}" text-anchor="middle">${esc(l.label)}</text></g>`;
}
/**
* THE LIMITS, AS THE EDGE OF THE BUILDABLE DISTRICT.
*
* Drawn just OUTSIDE the sign's own column, because the sign stands on the boundary rather than
* beyond it: a siding may run under the sign, and the line has to agree with the rule or it
* teaches the wrong one. It moves outward on its own as the Running Track is extended, which is
* the reward for extending made visible.
*/
if (limits) {
const edge = (x: number, side: string): string =>
`<line class="bs-limitline" x1="${x}" y1="0" x2="${x}" y2="${height}"/>` +
`<text class="bs-limitlab" x="${x + (side === 'w' ? 4 : -4)}" y="${height - 4}" ` +
`text-anchor="${side === 'w' ? 'start' : 'end'}">LIMITS</text>`;
out += edge(px(limits.west) - PAD / 2, 'w') + edge(px(limits.east) + W + PAD / 2, 'e');
}
// Mark the Running Track so the spine of the district is unmistakable.
out += `<text class="bs-rowlab" x="2" y="${py(runningRow) + 92}">RUNNING TRACK</text>`;
out += '</svg>';
@@ -874,10 +1003,16 @@ export const BOARD_CSS = `
.bs-tcar.bs-t-mt{fill:#6b5a2e}
.bs-tcar.bs-t-eng{fill:#2b2313;stroke:#e0c060;stroke-width:1.4}
.bs-tcarlab{font:8px ui-monospace,monospace;fill:#2b2313;font-weight:700}
/* One pip per A/D track, filled when a train is holding on it. A full Office is why the next
arrival collides, so this is the count worth seeing without hovering. */
.bs-ad{fill:none;stroke:#4d6fa8;stroke-width:1.2}
.bs-ad.bs-occ{fill:#5aa9e6;stroke:#8fc4ee}
/* One chip per A/D track, not one per train — a full Office is why the next arrival collides, so
the count is worth seeing without hovering, and a free track reads "free" rather than vanishing.
The selected train's chip is lit the same amber the crew strip and action buttons use. */
.bs-adchip rect{fill:#20262e;stroke:#4a5361;stroke-width:1}
.bs-adchip text{fill:#cfd6e0;font:600 8px ui-monospace,monospace}
.bs-adchip.on rect{fill:#8a6d1f;stroke:#e0c060;stroke-width:1.4}
.bs-adchip.on text{fill:#fff4d6}
.bs-adchip.mt rect{fill:none;stroke:#3d4650;stroke-dasharray:3 2}
.bs-adchip.mt text{fill:#6b7480}
.bs-adchip[data-crew]{cursor:pointer}
.bs-t-mt + .bs-tcarlab,.bs-t-eng + .bs-tcarlab{fill:#f0e6cf}
.bs-tlab{fill:#eaf6ec;font:600 11px ui-monospace,monospace}
/* The three letters sit ON the slot, so they invert with it: dark on a loaded car's solid face,
@@ -914,6 +1049,10 @@ export const BOARD_CSS = `
text.bs-mod{fill:#c8a04a}
.bs-enh{fill:#7fb0e6;font:9px ui-monospace,monospace}
.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). */
.bs-limitline{stroke:#5f6b7a;stroke-width:1.5;stroke-dasharray:3 5;opacity:.7}
.bs-limitlab{fill:#5f6b7a;font:600 8px ui-monospace,monospace;letter-spacing:.12em}
.bs-ghost rect{fill:rgba(90,169,230,.07);stroke:#5aa9e6;stroke-width:2;stroke-dasharray:5 4}
.bs-ghost text{fill:#5aa9e6;font:11px ui-monospace,monospace}
/* The caption on a legal square that already carries a card. Same blue as the ghost squares and the
@@ -924,10 +1063,17 @@ text.bs-mod{fill:#c8a04a}
.bs-ghost,g[data-cell].bs-legal{cursor:pointer}
g[data-cell].bs-legal .bs-card{stroke:#5aa9e6;stroke-width:2.5}
g[data-cell].bs-legal:hover .bs-card,.bs-ghost:hover rect{fill:#233246}
/* THE SQUARE THE ACTION UNDER THE CURSOR MEANS. White, and brighter than anything else the board
marks, because it answers a question being asked RIGHT NOW rather than describing a standing
state — and it has to win when it lands on a square that is already legal, focused or blocked. */
g[data-cell].bs-point .bs-card,g[data-ghost].bs-point rect{stroke:#f2f5f8;stroke-width:3.5;stroke-dasharray:none}
g[data-cell].bs-point .bs-card{fill:#2b3b52}
/* WHERE THE CREW CAN GO. Amber, the colour this game spends on "you can do this", so a reachable
card reads the same way an action button does. bs-from is where it is standing now. */
card reads the same way an action button does. bs-from is where it is standing now — marked on
the crew STRIP rather than the whole card, because the Office is the one square where a second
train may share that card: outlining the card would claim it belongs to both. */
g[data-cell].bs-focus .bs-card{stroke:#e0c060;stroke-width:2.5}
g[data-cell].bs-from .bs-card{stroke:#7a6a3a;stroke-width:2;stroke-dasharray:4 3}
.bs-crew.bs-from rect:first-of-type{stroke:#7a6a3a;stroke-width:2;stroke-dasharray:4 3}
/* AND WHERE IT CANNOT. Muted red with a barred face — a card that is refusing traffic, not one that
is merely uninteresting. The reason rides on the card's own tooltip. */
g[data-cell].bs-blocked .bs-card{stroke:#8a5a5a;stroke-width:2;stroke-dasharray:2 3}
+175 -42
View File
@@ -17,8 +17,8 @@
import { MAX_CONSIST } from '../engine/content.ts';
import { adTrackCount, coordKey, seatOf, turnOf } from '../engine/state.ts';
import type { GameState, GridCoord, PlayerIndex, RollingStock, TrayId } from '../engine/state.ts';
import { areaOf, canAdvanceLoad, canStartLoad, facilityCarType, facilityCarTypes, laborersLeft, movesFor, portersLeft } from '../engine/apply.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 type { GameEvent } from '../engine/events.ts';
// ---------------------------------------------------------------------------
@@ -34,11 +34,20 @@ export function clockTime(stage: number): string {
return CLOCK[stage - 1] ?? `Stage ${stage}`;
}
export function carLabel(c: RollingStock): string {
/**
* `homeSeat` is the district the page is being drawn for. Give it, and a load THIS district made
* says so — the printed game's answer is to turn the chip upside down in the tray, and this is the
* screen's. A load may not be broken in the Office Area that made it (state.ts `RollingStock.origin`),
* so "loaded here" is the difference between a boxcar worth switching and one that has to leave the
* district first. Omit it and the label is what it always was, which is what the replay viewers and
* the history lines want: they describe a board, not a seat's view of one.
*/
export function carLabel(c: RollingStock, homeSeat?: SeatIndex): string {
// A caboose carries the crew, not freight, so "loaded caboose" is nonsense on the page even
// though the supply marks every caboose loaded. Name it plainly.
if (c.type === 'caboose') return 'caboose';
return `${c.loaded ? 'loaded' : 'empty'} ${c.type}`;
const label = `${c.loaded ? 'loaded' : 'empty'} ${c.type}`;
return homeSeat !== undefined && c.origin === homeSeat ? `${label} (loaded here)` : label;
}
export function carsLabel(cars: RollingStock[]): string {
@@ -126,10 +135,13 @@ export function narrate(e: GameEvent, ctx: NarrateContext = {}): Narration {
: 'Chose FREIGHT AGENT work — one car moved to or from a facility',
};
case 'trayMoved':
// `via` rides on the event only when there was another legal route to the same square
// (docs/plans/switching-paths.md) — so naming it here says which one the crew actually took,
// rather than leaving a real choice invisible in the crew's own history.
return {
tone: 'plain',
where: e.to,
text: `CREW moved ${at(e.from)} → ${at(e.to)} — ${e.movesRemaining} of 6 Moves left. The crew chip on the grid carries the whole train with it.`,
text: `CREW moved ${at(e.from)} → ${at(e.to)}${e.via ? ` via ${at(e.via)}` : ''} — ${e.movesRemaining} of 6 Moves left. The crew chip on the grid carries the whole train with it.`,
};
case 'carsCoupled': {
/**
@@ -243,14 +255,31 @@ export function narrate(e: GameEvent, ctx: NarrateContext = {}): Narration {
tone: 'bad',
text: `SECOND SECTION ordered on Train ${e.trainNumber} — an identical train will run right behind it, which forces the Superintendent to rule on a following train (§8.1)`,
};
case 'extraStarted':
/**
* WHERE THE PLAYER PUT IT, not where its number would have sent it.
*
* An Extra's direction comes from its start now (§7, Jesse's ruling), so the line that used to
* explain the number's parity would be explaining a rule that no longer applies to this train.
*/
case 'extraStarted': {
const where =
e.at.kind === 'divisionPoint'
? `the ${e.at.side === 'west' ? 'Western' : 'Eastern'} Division Point`
: e.at.kind === 'mainline'
? "the Interchange's yard"
: `the Control Point in seat ${e.at.seat}`;
const why =
e.at.kind === 'divisionPoint'
? 'the end it runs away from — an Extra may start at either, and the end chooses the run'
: e.at.kind === 'mainline'
? 'made up off the running line, so it highballs onto the Mainline once the Subdivision ' +
'is clear and may be held in the yard until it is'
: 'an Extra may begin at any Office above a Whistle Post, and the player chooses the run';
return {
tone: 'good',
text:
e.atSeat === null
? `EXTRA X${e.trainNumber} started at the ${e.trainNumber % 2 === 0 ? 'Western' : 'Eastern'} Division Point, running ${e.trainNumber % 2 === 0 ? 'east' : 'west'} — odd numbers run west and even run east (§2.3), so its number chose the end`
: `EXTRA X${e.trainNumber} started at the Control Point in seat ${e.atSeat}, running ${e.trainNumber % 2 === 0 ? 'east' : 'west'} — an Extra may begin at any Office above a Whistle Post instead of at a Division Point`,
text: `EXTRA X${e.trainNumber} started at ${where}, running ${e.direction} — ${why}`,
};
}
case 'trainMadeUp':
return {
tone: 'good',
@@ -277,25 +306,25 @@ export function narrate(e: GameEvent, ctx: NarrateContext = {}): Narration {
};
case 'trainArrived':
/**
* AN EXPEDITED TRAIN IS NOT COMING BACK ROUND — AND IS NOT GONE YET EITHER.
* AN EXPEDITED ARRIVAL IS AN ORDINARY ARRIVAL, WITH ONE STANDING OBLIGATION.
*
* This said "it will highball again next Mainline Phase" to every arrival, which is backwards
* for an Expedited train. Corrected once to "it leaves again this same Mainline Phase", which
* was ALSO wrong and in a way that cost the player work: the expedited departure was moved to
* Supervisor Shift precisely so the Porters and Laborers get their Stage with the train, so
* Cargo IS available and only Local Operations is not. Telling a player there is "no turn in
* which to work it" talked them out of the one turn they had.
*
* So both branches now name the phases: what you can still do with this train, and when it
* goes. That is the whole of the reported confusion — "some trains seem to be moving before I
* can switch or do other operations on them".
* This used to say the train stands through Cargo and is forced out at the end of the Stage —
* true once, and wrong: Q3 means the train must not be PARKED anywhere but the station, not
* that it is rushed out early. It is switched, worked and released exactly like any other
* arrival; the only difference is what happens if it is left on Secondary Track when the next
* Mainline Phase begins (`expediteFault`).
*/
return {
tone: 'plain',
text: e.expedited
? `Train ${e.trainNumber} ARRIVED at the ${e.office} carrying ${carsLabel(e.consist)} — its card prints EXPEDITE, so it stands through the Cargo phase and departs at the END OF THIS STAGE. Porters and Laborers can work it now; it is normally gone before your next Local Operations turn, so it cannot be switched — unless §8.1 holds it for a ruling, in which case it stays and runs like any other train.`
? `Train ${e.trainNumber} ARRIVED at the ${e.office} carrying ${carsLabel(e.consist)} — its card prints EXPEDITE, so keep it on the Office square: parked anywhere else in the district when the next Mainline Phase begins costs a Revenue point. It works and switches normally in the meantime.`
: `Train ${e.trainNumber} ARRIVED at the ${e.office} carrying ${carsLabel(e.consist)} — it stands here for the rest of this Stage. You can work it in Cargo now, switch it in the NEXT Stage's Local Operations, and it departs in that Stage's Mainline Phase.`,
};
case 'expediteFault':
return {
tone: 'bad',
text: `Train ${e.trainNumber} was left at ${e.where}, off the station, when the Mainline Phase began — an expedited train must be kept ready to highball. Station Master fault.`,
};
case 'trainDiverted':
return {
tone: 'good',
@@ -481,14 +510,124 @@ export type Impediment = { where: string; why: string; severity: 'stuck' | 'wait
* This is the panel that should answer the standing questions: whether facilities jam, whether
* trains are held for want of a crew, whether the Office is about to cause a collision.
*/
/** `coordKey`'s inverse — the grid is keyed by string and the engine predicates take coordinates. */
function uncoordKey(key: string): GridCoord {
const [row, col] = key.split(',').map(Number);
return { row: row ?? 0, col: col ?? 0 };
}
/**
* One of `passengerRefusal`'s codes, in words a player can act on.
*
* `NO_EMPTY_COACH_IN_YARD` gets the longest answer because it is the one that looks like a broken
* game: the Division Yard is visibly full of cars, and the single type that has run out is the one
* §9.2 needs. Where the missing coaches ARE, and the condition that brings them back, is the whole
* of what the player needs to know — §2.2 returns the Classification Yard only when the Division
* Yard is bare, so a yard with fifty freight cars in it will not refill for a long time.
*/
function passengerReason(
s: GameState,
player: PlayerIndex,
at: GridCoord,
dir: 'board' | 'detrain',
): string {
const code = passengerRefusal(s, player, at, dir);
switch (code) {
case 'NO_TRAIN_AT_OFFICE':
return dir === 'board'
? 'passengers waiting, no train at the platform to take them'
: 'no train at the platform';
case 'NOT_A_TERMINAL':
return 'the only train here stops at Terminals only — Porters may not work it at this Office';
case 'NO_PASSENGER_WORK':
return 'the only train here is one its card bars Porters from working';
case 'NO_EMPTY_COACH':
return 'passengers waiting, but every coach on the train is already full';
case 'INBOUND_BOX_FULL':
return 'arrivals aboard, but the red Unloading slots are all occupied';
case 'LOADED_IN_THIS_DISTRICT':
return 'the loaded coaches all boarded here — passengers must be carried to another Office ' +
'Area before they can alight';
case 'NO_EMPTY_COACH_IN_YARD': {
const stuck = s.yards.classificationYard.filter((c) => c.type === 'coach').length;
const total = s.yards.divisionYard.length;
return (
'arrivals aboard, but §9.2 needs a white empty coach from the Division Yard to swap in and ' +
`there is none left${stuck > 0 ? ` — ${stuck} ${stuck === 1 ? 'coach is' : 'coaches are'} in the Classification Yard` : ''}. ` +
`Classification returns only when the Division Yard is bare, and it still holds ${total} cars.`
);
}
default:
return `Porters cannot work here (${code})`;
}
}
export function impediments(s: GameState, player: PlayerIndex = 0): Impediment[] {
const out: Impediment[] = [];
const area = areaOf(s, player);
for (const [key, card] of area.grid) {
const f = card.facility;
if (!f || f.kind !== 'freight') continue;
const name = card.geometry.kind === 'facility' ? card.geometry.facility : 'facility';
if (!f) continue;
/**
* A Freight Facility names itself off its own card; a Passenger Facility does NOT — it rides on
* the `office` card, so `geometry.kind` is `'office'` and it fell through to the literal
* "facility". Every passenger impediment therefore read `facility 0,0`, next to a freight row
* saying `mineTipple 1,-3`. The Office Area's tier is the name it should carry, and there is
* exactly one Office per Area, so `area.tier` is that card's own.
*/
const name =
card.geometry.kind === 'facility'
? card.geometry.facility
: card.geometry.kind === 'office'
? area.tier
: 'facility';
/**
* WHY THE PORTERS ARE STANDING THERE (Gitea#2).
*
* "Note that the sparrow (with two loaded coaches) pulled into the station. There are two
* passengers on the platform. Four porters. My thought was to unload two and load two. I never
* get the chance to load the last two."
*
* The engine was right — §9.2 needs a white coach out of the Division Yard to de-train into,
* §2.2 returns the Classification Yard only when the Division Yard is BARE, and the Division
* Yard was one empty coach short with eight more sitting in Classification unable to come back.
* Jesse's ruling is that the shortage stays: "it is possible to run out — that's part of the
* strategy." What was missing was any way to SEE it. A Porter action that cannot be taken is
* simply absent from the menu, and this panel — the one that answers "why is nothing moving?" —
* covered freight facilities only, so the platform had nothing to say for itself at all.
*
* The reason comes from `passengerRefusal`, the engine's own, so what is on screen is the rule
* that actually refused rather than a second guess at it.
*/
if (f.kind === 'passenger') {
if (portersLeft(f) > 0) {
const coord = uncoordKey(key);
// Passengers standing on the platform with nothing carrying them away.
if (f.outboundBox.some((c) => c.type === 'coach' && c.loaded) && !canBoard(s, player, coord)) {
out.push({
where: `${name} ${key}`,
why: passengerReason(s, player, coord, 'board'),
severity: 'waiting',
});
}
// A coach full of arrivals that cannot be emptied.
const arriving = area.adOccupancy.some((id) =>
s.trays.get(id)?.consist.some((c) => c.type === 'coach' && c.loaded && c.origin !== seatOf(s, player)),
);
if (arriving && !canDetrain(s, player, coord)) {
out.push({
where: `${name} ${key}`,
why: passengerReason(s, player, coord, 'detrain'),
severity: 'stuck',
});
}
}
continue;
}
if (f.kind !== 'freight') continue;
const want = facilityCarType(f);
// A load that cannot move, with Laborers standing by, is the worst state a facility reaches:
@@ -579,7 +718,7 @@ export function impediments(s: GameState, player: PlayerIndex = 0): Impediment[]
// the board says it on the card instead.
if (b.kind === 'noStopping') continue;
out.push({
where: `${tray.trainNumber === null ? 'crew' : `Train ${tray.trainNumber}`} → (${b.coord.row},${b.coord.col})`,
where: `${tray.trainNumber === null ? 'crew' : `Train ${tray.trainNumber}`} → (${b.coord.col},${b.coord.row})`,
why: b.why,
// Not "stuck": these are the shape of the district and of the other trains in it, which is
// the puzzle rather than a fault. Amber, not red.
@@ -599,12 +738,10 @@ export function impediments(s: GameState, player: PlayerIndex = 0): Impediment[]
* said so.
*
* Reported again as "passenger trains arrive at my Office and move on before I can load or unload
* them", which turned out to be three separate silences. This block only looked at trains carrying
* them", which turned out to be two separate silences. This block only looked at trains carrying
* a LOADED coach, so a train arriving to PICK UP said nothing at all. A Whistle Post's Office card
* carries a passenger facility with zero Porters, so the engine answered `RESOURCE_SPENT` — "all
* Porters used" — to a player who had used none. And an expedited train leaves at the end of the
* Stage it arrives, so its one Load/Unload phase is now-or-never and nothing said which trains
* those are.
* Porters used" — to a player who had used none.
*
* §9.2 also requires an empty coach in the DIVISION YARD to swap into the train, which no panel
* mentioned at all.
@@ -617,8 +754,6 @@ export function impediments(s: GameState, player: PlayerIndex = 0): Impediment[]
.filter((t): t is NonNullable<typeof t> => !!t && t.consist.some((c) => c.type === 'coach'));
if (coachTrains.length > 0) {
const label = (t: (typeof coachTrains)[number]): string =>
t.trainNumber === null ? 'the local crew' : `Train ${t.trainIsExtra ? 'X' : ''}${t.trainNumber}`;
const say = (why: string, severity: Impediment['severity'] = 'waiting'): void => {
out.push({ where: 'Office — passengers', why, severity });
};
@@ -655,17 +790,6 @@ export function impediments(s: GameState, player: PlayerIndex = 0): Impediment[]
say('no EMPTY coach in the Division Yard to swap into the train (§9.2 requires one)');
}
}
// NOW OR NEVER. An expedited train leaves at the end of this Stage, so this is the only
// Load/Unload phase it will ever stand for — the exact thing the playtest report was about.
for (const t of coachTrains) {
if (!t.departsThisStage) continue;
say(
`${label(t)} is EXPEDITED — it leaves at the END of this Stage, so this is the only ` +
'Load/Unload phase it will stand for. Work it now or not at all.',
'risk',
);
}
}
}
@@ -745,6 +869,15 @@ export function cuesFor(events: readonly GameEvent[]): string[] {
// A train running the whole length of the Division pays every player, and it is the one event
// nobody made happen on the turn it lands. It should be heard, not found in the log.
if (e.type === 'trainCompleted') out.push('completed');
// A train pulling into an Office. `trainDiverted` (the Yard Office siding) is deliberately not
// included — that one goes straight to a work track without the A/D stop `arrive` depicts.
if (e.type === 'trainArrived') out.push('arrive');
// Only an OFFICE departure, not every highball: a fresh make-up leaving a Division Point already
// sounds `train` ("All aboard"), and a train clearing the whole Division already sounds
// `completed` — this is the one case neither of those covers.
if (e.type === 'trainHighballed' && e.from === 'the Office') out.push('depart');
// §10 — the one event nobody wants to hear and everybody needs to.
if (e.type === 'trainsDestroyed') out.push('crash');
if (e.type === 'stageBegan') {
// A Stage BEGINNING is the previous one ending — except the first, which is the game opening
// and has nothing behind it. A Day boundary rings the bell only: sounding both would collide,
+17 -12
View File
@@ -202,9 +202,9 @@ export function compress(frames: Frame[]): Packed {
// Identity, not equality: `snapshot` pushes the very same FacilityView object into both the
// cell and the frame's `facilities`, so this always resolves.
const fi = c.facility ? f.facilities.indexOf(c.facility) : -1;
// `train` rides whole rather than being interned: it changes almost every frame, so a table
// `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.tray, c.cars, fi, c.train, c.ad, c.enhancementsWhat, c.standingWest];
return [ci, wi, c.enhancements, c.cars, fi, c.trains, c.adTracks, c.enhancementsWhat, c.standingWest];
});
return { ...f, cells } as unknown as Frame;
});
@@ -238,21 +238,26 @@ export function rehydrateCells(
facs: unknown[],
): unknown[] {
return packed.map((row) => {
const p = row as [number, number, string[], string | null, string[], number, unknown, unknown, string[], number];
const p = row as [number, number, string[], string[], number, unknown, unknown, string[], number];
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
// undefined reads as no train at all.
const rawTrains = p[5];
const trains = Array.isArray(rawTrains) ? rawTrains : rawTrains ? [rawTrains] : [];
return {
row: c[0], col: c[1], kind: c[2], label: c[3], running: c[4], links: c[5],
what: whats[p[1]], enhancements: p[2], tray: p[3], cars: p[4],
facility: p[5] < 0 ? null : facs[p[5]],
train: p[6] ?? null,
ad: p[7] ?? null,
what: whats[p[1]], enhancements: p[2], cars: p[3],
facility: p[4] < 0 ? null : facs[p[4]],
trains,
adTracks: (p[6] as number | undefined) ?? null,
// Carried rather than recomputed: this function is emitted into the page by toString() and so
// cannot reach the card catalogue that produced the text.
enhancementsWhat: p[8] ?? [],
// Where the train on this card stands among the cars standing on it, so the replay draws a cut
// ahead of or behind the engine exactly as the live board does. Absent in older recordings,
enhancementsWhat: p[7] ?? [],
// Where the train(s) on this card stand among the cars standing on it, so the replay draws a
// 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[9] ?? 0,
standingWest: p[8] ?? 0,
};
});
}
@@ -499,7 +504,7 @@ function render() {
$('division').innerHTML = divisionSvg(DIV);
// The same office renderer the playable app uses, so replay and game draw one board.
$('grid').innerHTML = officeSvg(CELLS, f.runningRow);
$('grid').innerHTML = officeSvg(CELLS, f.runningRow, [], [], f.limits);
/* Auto-hide: the district is worth its space during the phases that change it, and folded
otherwise. A summary stays, because a panel that vanishes reads as broken. */
+172 -82
View File
@@ -18,7 +18,10 @@ import {
laborersLeft,
movesFor,
ownCutFor,
keepReason,
portersLeft,
resolveExtraStart,
selectDestination,
} from '../engine/apply.ts';
import {
ACTION_CARDS,
@@ -43,7 +46,7 @@ import {
mainlineDescription,
} from '../engine/content.ts';
import type { Intent } from '../engine/intents.ts';
import type { Facility, GameState, PlayerIndex, TrackCard, TurnoutOrientation } from '../engine/state.ts';
import type { Facility, 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 { Port } from '../engine/track.ts';
@@ -70,19 +73,25 @@ export type CellView = {
* `toString()`), so it cannot reach the card catalogue itself.
*/
enhancementsWhat: string[];
tray: string | null;
/**
* THE TRAIN STANDING HERE, in order, with the engine in it and which way it points.
* EVERY TRAIN STANDING HERE, in order, each with the engine in it and which way it points.
*
* The switching game is entirely about car ORDER — which car is next to come off, which end a cut
* couples onto — and the board showed a crew badge with a name and nothing else. A player could
* not plan a move at all: "drop 1 car" tells you nothing when you cannot see what is on the back.
*
* An ARRAY because the Office square is the one place more than one train may legally stand at
* once (docs/plans/switching-paths.md — "The Roster Pass"): the old singular `train` field only
* ever showed whichever tray `s.trays` happened to yield first, so a second train at a busy
* Station was never drawn at all, only counted in the A/D pips. Empty, not absent, when the card
* is bare, so callers never need an `?? []`.
*
* `cars` runs nose first, matching the tray; `engineAt` is where the locomotive sits in it, and
* `facing` is which way the engine points — EAST OR WEST, never north or south, whatever the
* track under it runs. See `railFacingOf` in state.ts for why, and why the type says so.
*/
train: {
trains: {
trayId: string;
label: string;
cars: string[];
engineAt: number;
@@ -95,26 +104,31 @@ export type CellView = {
* standing in front of them — the card is face down in a box somewhere by then.
*/
what: string;
} | null;
}[];
/**
* Office card only: A/D tracks taken and how many the tier has.
* Office card only: how many A/D tracks the tier has — null everywhere else.
*
* The tooltip said "3 A/D tracks" and the card showed nothing, so the number that decides whether
* the next arrival collides was invisible on the card it belongs to. Drawn as pips rather than
* extra rails — there is no room on the card for more track, and the count is what matters.
* Capacity, not occupancy: `board-svg.ts` draws one roster chip per track regardless of how many
* are taken (a free one reads "free"), so occupancy is implicit in how many of `trains` land on
* it. Used to carry `{used, of}` and draw one pip per track; the pips are gone (the roster band
* takes their place) but the count is still needed to know how many chips to lay out.
*/
ad: { used: number; of: number } | null;
adTracks: number | null;
cars: string[];
/**
* Cars in `cars` that stand WEST of the train on this card — 0 when no train is here.
* Cars in `cars` that stand WEST of the train(s) here — 0 when no train is here, and unsplit if
* so: with nobody standing on the card, a cut has no near or far side and the whole row simply
* reads west to east (`board-svg.ts` draws the split only while `trains.length > 0`).
*
* `cars` runs west to east like the state it comes from, and a train standing on the card sits
* somewhere IN that row rather than beside it. Reported from play: "right after dropping my cars I
* need to be able to see if those cars are ahead or behind the train" — and the board drew the
* whole cut in one left-aligned strip at the bottom of the card, which cannot answer that at all.
*
* Combined with `train.facing` it is the answer: for an east-facing engine the cars east of it are
* the ones ahead, and the split is drawn as a gap the chip sits in.
* Combined with a train's `facing` it is the answer: for an east-facing engine the cars east of it
* are the ones ahead. ONE number for the whole card — every train standing here (there is at most
* one, except the Office) reads the same split, taken against the block of A/D tracks rather than
* against any one engine, straight off `TrackCard.standingWest`.
*/
standingWest: number;
facility: FacilityView | null;
@@ -295,6 +309,14 @@ export type DivisionView = {
/** Office nodes only: whose district this is. */
/** Which SEAT's district this is — a position on the Division, not a player. */
seat?: number;
/**
* Interchange only: trains standing in its yard, not out on the running line (state.ts).
*
* Separate from `trains` for the same reason `switching` is separate from an Office's A/D list —
* they are not occupying the thing whose capacity is being counted. An Extra made up here has to
* be VISIBLE, though, or the player who placed it has a train that exists nowhere on the map.
*/
yard?: TrainChip[];
/**
* Office nodes only: crews working BELOW the Running Track.
*
@@ -346,6 +368,15 @@ export type Frame = {
* player order once §4.4's D12 decided who sits where.
*/
players: { index: number; seat: number; name: string; revenue: number; hand: number }[];
/**
* WHICH of those players is the one this Frame was drawn for.
*
* `snapshot` has always taken a `viewer`, and everything viewer-scoped on the Frame — `revenue`,
* `handCount`, `objective`, `blocked` — is already resolved against it. What was missing was the
* INDEX itself, so a panel showing the whole table (the Day-end dialog, Gitea#10) had no way to
* mark which row is yours without assuming the web client's `viewer = 0`.
*/
viewer: number;
/** How many cards the VIEWER holds. Other players' counts are in `players`. */
handCount: number;
lines: { text: string; tone: string }[];
@@ -356,6 +387,15 @@ export type Frame = {
cells: CellView[];
/** Which grid row is the Running Track — the spine the district hangs beneath. */
runningRow: number;
/**
* The columns the Limits signs stand in — the district's east and west edges, at EVERY row.
*
* Track may not be laid outside them (§2.1), so a player looking at open ground beyond a sign is
* looking at ground no card of his will ever go on. Two signs on one row could not say that; the
* board draws the boundary down the whole district instead. Carried on the Frame rather than read
* off the area for the usual reason: a remote client holds no `GameState`.
*/
limits: { west: number; east: number };
/**
* Moves left in this Local Operations turn, or null outside a switching turn.
*
@@ -396,6 +436,25 @@ export type Frame = {
hand: string[];
/** What each hand card does, in the same order — names alone are not a playable hand. */
handWhat: string[];
/**
* Whether each hand card may be DISCARDED, in the same order.
*
* The player has to be told which cards those are, not merely find that a button is missing —
* that silence is the whole of the Gitea#2 complaint, where a blocked platform left the board with
* nothing to click and no reason. Named for the rule rather than for trains, since it answers the
* question the panel is asking.
*/
handDiscardable: boolean[];
/**
* WHY a card may not be discarded, in the same order; `null` where it may.
*
* Carried rather than written on the page because §6.2 now fails for two different reasons
* (Gitea#9): an Extra is never discardable, and a Timetabled train is not discardable only when
* the `discardTimetabled` house rule is off. A panel that hard-codes one sentence tells half the
* players the wrong thing, and a panel that reconstructs the rule is a second implementation of
* it. `keepReason` is the engine's own, so the card says the rule that actually refused.
*/
handKeepWhy: (string | null)[];
deck: number;
/** The face-up card on top of each Department pile — the only one that may be drawn. */
departments: string[];
@@ -487,6 +546,7 @@ const FACILITY_NAMES: Record<string, string> = {
function facilityView(
card: { geometry: { kind: string; facility?: string }; facility: unknown; modifiers?: string[] },
officeName: string,
viewerSeat: SeatIndex,
): FacilityView | null {
const f = (card as { facility: import('../engine/state.ts').Facility | null }).facility;
// Passenger facilities were excluded entirely, so the Office's green and red slots never
@@ -508,7 +568,9 @@ function facilityView(
maw: (f.menAtWork ?? []).map((l) => (l ? `${l.type} ${l.dir === 'out' ? '→' : '←'}` : null)),
red: f.inboundBox.map(carLabel),
redCap: f.capacity.inbound,
track: f.industryTrack.cars.map(carLabel),
// Marked when this district made the load: the spotted car is exactly where a player is looking
// when they ask why the Laborer will not unload it.
track: f.industryTrack.cars.map((c) => carLabel(c, viewerSeat)),
laborers: `${laborersLeft(f)}/${f.laborers}`,
porters: `${portersLeft(f)}/${f.porters}`,
canFinish: canFinishHere(f),
@@ -581,29 +643,33 @@ function baseOf(
* Zero when there is no train, which is also the right answer for a bare cut: with nobody standing
* there, a cut has no near or far side and the whole row simply reads west to east.
*/
function standingWestOn(s: GameState, key: string, cars: number): number {
for (const t of s.trays.values()) {
if (t.position.at !== 'grid') continue;
if (`${t.position.coord.row},${t.position.coord.col}` !== key) continue;
return Math.max(0, Math.min(cars, t.standingWest ?? 0));
}
return 0;
}
function trainOnCard(s: GameState, key: string): CellView['train'] {
/**
* Every train standing on this card, for THIS viewer's seat.
*
* KEYED BY COORDINATE, so it must be filtered by seat first — every district uses the same (row,
* col) origin, so without the seat check a crew standing at (0,1) in one player's Office Area would
* be drawn onto (0,1) of every other player's board too. Collects every match rather than returning
* on the first: the Office square is the one place more than one train may legally stand at once
* (docs/plans/switching-paths.md), and the old singular version silently drew only whichever tray
* `s.trays` happened to yield first.
*/
function trainsOnCard(s: GameState, viewerSeat: SeatIndex, key: string): CellView['trains'] {
const out: CellView['trains'] = [];
for (const [id, t] of s.trays) {
if (t.position.at !== 'grid') continue;
if (t.position.at !== 'grid' || t.position.seat !== viewerSeat) continue;
if (`${t.position.coord.row},${t.position.coord.col}` !== key) continue;
return {
out.push({
trayId: id,
label: t.trainNumber === null ? 'crew' : `T${t.trainIsExtra ? 'X' : ''}${t.trainNumber}`,
cars: t.consist.map(carLabel),
// A coach filled at THIS Office reads "loaded coach (loaded here)" — those passengers may not
// alight in the district that boarded them, and the tray is where a player looks for that.
cars: t.consist.map((c) => carLabel(c, viewerSeat)),
engineAt: Math.max(0, Math.min(t.consist.length, t.engineAt)),
facing: railFacingOf(t),
what: t.trainNumber === null ? 'A local crew — no timetable, no card, no special rules.' : trainRules(t),
};
void id;
});
}
return null;
return out;
}
/** Is a car spotted that a load on WORK could actually come off onto (§9.3)? */
@@ -653,9 +719,15 @@ function sampleDetail(s: GameState, kind: string, list: Intent[]): string {
return shown.join('; ') + (more > 0 ? ` … and ${more} more distinct` : '');
}
/** " onto Train 8", or nothing at all when the intent names no train (an old save, or one train). */
function onto(s: GameState, trayId: string | undefined, joiner: string): string {
return trayId === undefined ? '' : `${joiner}${trainName(s, trayId)}`;
}
/** One readable line for a single intent. */
export function describeIntent(s: GameState, i: Intent): string {
const at = (c: { row: number; col: number }): string => `(${c.row},${c.col})`;
// X,Y — east/west then north/south, not the internal row/col storage order.
const at = (c: { row: number; col: number }): string => `(${c.col},${c.row})`;
// An intent belongs to whoever is acting, so it is described against THEIR district.
// The acting PLAYER, not a seat — `describeIntent` describes an intent against the district of
// whoever is making it. Named `seat` once, and then used as an `officeAreas` key, which is the
@@ -727,9 +799,19 @@ export function describeIntent(s: GameState, i: Intent): string {
const tray = s.trays.get(i.trayId);
const here = tray?.position.at === 'grid' ? tray.position.coord : null;
let picks = '';
let routeNote = '';
if (here) {
const dest = destinationsFor(s, tray!.position.at === 'grid' ? playerAtSeat(s, tray!.position.seat) : 0, i.trayId, here, i.reverse)
.find((d) => d.coord.row === i.to.row && d.coord.col === i.to.col);
const dests = destinationsFor(s, tray!.position.at === 'grid' ? playerAtSeat(s, tray!.position.seat) : 0, i.trayId, here, i.reverse);
const dest = selectDestination(dests, i.to, i.via);
// Two routes to the same square (docs/plans/switching-paths.md) would otherwise print the
// identical button twice — "move to (0,0)" and "move to (0,0)" — and the action list drops
// duplicate labels, silently discarding the second choice. `via` is the one thing that
// differs in the DATA, so it is the one thing safe to print without guessing at scenery
// this function has no other reason to know the name of.
const atSameSquare = dests.filter((d) => d.coord.row === i.to.row && d.coord.col === i.to.col);
if (dest && i.via && atSameSquare.length > 1) {
routeNote = ` via ${at(i.via)}`;
}
if (dest && dest.couples.length > 0) {
/**
* NAME THE CARS THE CREW SET OUT HERE SEPARATELY. They are at the front of `couples` — the
@@ -747,7 +829,7 @@ export function describeIntent(s: GameState, i: Intent): string {
: ` — couples ${carsLabel(dest.couples)} on the way${end}`;
}
}
return `move to ${at(i.to)}${i.reverse ? ' (reverse)' : ''}${picks}`;
return `move to ${at(i.to)}${routeNote}${i.reverse ? ' (reverse)' : ''}${picks}`;
}
case 'switch.dropCars': {
/**
@@ -821,18 +903,39 @@ export function describeIntent(s: GameState, i: Intent): string {
return `advance load in box ${i.box} at ${at(i.at)}`;
case 'laborer.beginUnload':
return `begin unloading car ${i.carIndex} at ${at(i.at)}`;
/**
* NAME THE TRAIN. The action list drops duplicate labels within a crew, and with two trains
* standing at one station "board passengers at (0,0)" describes both — which is half of why the
* v0.4.9d playtest found that picking a train changed nothing. The intent now carries the tray;
* the label has to say so or the second button is thrown away before the menu sees it.
*/
case 'porter.board':
return `board passengers at ${at(i.at)}`;
return `board passengers at ${at(i.at)}${onto(s, i.trayId, ' onto ')}`;
case 'porter.detrain':
return `detrain passengers at ${at(i.at)}`;
return `detrain passengers at ${at(i.at)}${onto(s, i.trayId, ' from ')}`;
/**
* NAME THE PLACE AND THE DIRECTION, because the player is choosing both.
*
* This used to explain why the Extra had no choice — "it runs west, so that is the end it
* starts from". It has one now (§7, Jesse's ruling), and every candidate is on screen at once,
* so each label has to be distinguishable from its three or four siblings at a glance.
*/
case 'newTrain.startExtra': {
const runs = i.trainNumber % 2 === 0 ? 'east' : 'west';
if (i.atSeat === null) {
const end = i.trainNumber % 2 === 0 ? 'Western' : 'Eastern';
return `start Extra X${i.trainNumber} at the ${end} Division Point — it runs ${runs}, so that is the end it starts from`;
const where = resolveExtraStart(s, s.clock.currentActor ?? 0, i);
if (typeof where === 'string') return `start Extra X${i.trainNumber}`;
const { direction } = where;
if (where.at.kind === 'divisionPoint') {
const end = where.at.side === 'west' ? 'Western' : 'Eastern';
return `start Extra X${i.trainNumber} at the ${end} Division Point — it runs ${direction} from there`;
}
const tier = officeProfile(areaAtSeat(s, i.atSeat).tier).name;
return `start Extra X${i.trainNumber} at the ${tier} in seat ${i.atSeat} — a Control Point, so it may begin its ${runs}bound run there instead`;
if (where.at.kind === 'mainline') {
return (
`start Extra X${i.trainNumber} ${direction}bound in the Interchange — it is made up in the ` +
'yard and highballs onto the Mainline once the Subdivision is clear'
);
}
const tier = officeProfile(areaAtSeat(s, where.at.seat).tier).name;
return `start Extra X${i.trainNumber} ${direction}bound at the ${tier} in seat ${where.at.seat} — a Control Point, so it may begin its run there`;
}
case 'newTrain.placeCar':
@@ -955,18 +1058,6 @@ export function snapshot(
): Frame {
const area = areaOf(s, viewer);
const viewerSeat = seatOf(s, viewer);
const trayAt = new Map<string, string>();
for (const [id, tray] of s.trays) {
// KEYED BY COORDINATE, so it must be filtered by seat first. Every district uses the same
// (row, col) origin, so without this a crew standing at (0,1) in one player's Office Area is
// drawn onto (0,1) of every other player's board — the cells come from `area.grid`, which is
// the viewer's, but the train on them came from anybody's.
if (tray.position.at === 'grid' && tray.position.seat === viewerSeat) {
const label = tray.trainNumber === null ? 'crew' : `T${tray.trainIsExtra ? 'X' : ''}${tray.trainNumber}`;
const carrying = tray.consist.length ? ` [${tray.consist.map(carLabel).join(', ')}]` : ' [empty]';
trayAt.set(`${tray.position.coord.row},${tray.position.coord.col}`, label + carrying);
}
}
const cells: CellView[] = [];
const facilities: FacilityView[] = [];
@@ -985,7 +1076,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);
const fv = facilityView(card as never, officeProfile(area.tier).name, viewerSeat);
if (fv) facilities.push(fv);
cells.push({
@@ -998,14 +1089,10 @@ export function snapshot(
links: connectionsFor(card).map(([a, b]) => `${a}${b}`),
enhancements: card.enhancements.map(prettyKey),
enhancementsWhat: card.enhancements.map((k) => enhancementText(k) ?? prettyKey(k)),
tray: trayAt.get(key) ?? null,
train: trainOnCard(s, key),
ad:
card.geometry.kind === 'office'
? { used: area.adOccupancy.length, of: officeProfile(area.tier).adTracks }
: null,
cars: carsOn(card).map(carLabel),
standingWest: standingWestOn(s, key, carsOn(card).length),
trains: trainsOnCard(s, viewerSeat, key),
adTracks: card.geometry.kind === 'office' ? officeProfile(area.tier).adTracks : null,
cars: carsOn(card).map((c) => carLabel(c, viewerSeat)),
standingWest: card.standingWest,
facility: fv,
});
}
@@ -1073,6 +1160,9 @@ export function snapshot(
};
})],
capacity: MAINLINE_PROFILES.find((m) => m.kind === n.card)?.trainsMayPass ? 2 : 1,
// Drawn at the start of the card: the yard is beside the rail, and this is the end the
// train will pull out of. It counts against nothing — see `yard` on DivisionView.
yard: (n.holding ?? []).map((id) => ({ ...trainChip(s, id), region: 0 })),
modifiers: [
...(n.modifiers ?? []).map(prettyKey),
...(n.absSignals ? ['ABS Signals'] : []),
@@ -1161,6 +1251,8 @@ export function snapshot(
*/
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];
@@ -1198,9 +1290,11 @@ export function snapshot(
revenue: p.revenue,
hand: (s.decks.hands.get(p.index) ?? []).length,
})),
viewer,
handCount: (s.decks.hands.get(viewer) ?? []).length,
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),
@@ -1211,7 +1305,7 @@ export function snapshot(
? `${t.position.side} Division Point`
: t.position.at === 'mainline'
? `Mainline card ${t.position.index}`
: `Office Area (${t.position.coord.row},${t.position.coord.col})`,
: `Office Area (${t.position.coord.col},${t.position.coord.row})`,
})),
};
}
@@ -1406,7 +1500,9 @@ export function trainRules(t: {
* DOES rather than that it exists, because the restriction is the whole character of the card: a
* Military train that cannot be worked by Porters plays nothing like a Local.
*/
if (p.rules.noSwitching) parts.push('NO SWITCHING — it runs the Division and does not shunt');
if (p.rules.noSwitching) {
parts.push('NO SWITCHING — may not add or drop cars, but may still be moved clear of the mainline');
}
if (p.rules.terminalsOnly) parts.push('TERMINALS ONLY — Porters may work it at a Terminal and nowhere else');
if (p.rules.coachStaysOnStationTrack) {
// Said "may only be set out at the Office", which reads as a place you can do it. You cannot:
@@ -1422,21 +1518,20 @@ export function trainRules(t: {
}
if (p.rules.noPassengerWork) parts.push('NO PASSENGER WORK — Porters may not board or detrain it');
if (p.rules.dropOnly) parts.push('MAY DROP BUT NOT PICK UP — it cannot couple anything');
if (p.rules.pickUpEmptiesOnly) parts.push('EMPTIES ONLY — it may not couple a loaded car');
if (p.rules.pickUpEmptiesOnly) {
parts.push('EMPTIES ONLY — it may not couple a loaded car. A caboose is not a load.');
}
if (p.rules.stopThenExpedite) {
parts.push('STOPS ONCE FOR SPEECHES, then runs expedited from its next Office onward');
}
if (p.rules.expedite) {
// The single most-asked question in play — "why did that train leave before I could switch it?"
// — so it names the phases rather than the Stage. It stands through Cargo and goes at the end of
// the Stage, which is after the Porters and Laborers but before the next Local Operations.
// 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(
'EXPEDITED — it does not lay over. It stands through the Cargo phase and departs at the END OF ' +
'THE STAGE IT ARRIVES IN, so Porters and Laborers can work it but it is normally gone before ' +
'your next Local Operations turn and cannot be switched. UNLESS §8.1 wants a clearance ruling ' +
'at that moment: there is no Superintendent in Supervisor Shift to give one, so the train ' +
'stays and runs like any other from then on.',
'EXPEDITED — must be kept ready to highball. It works and switches normally, but if it is not ' +
'back on the Office square when the next Mainline Phase begins, that is a Station Master ' +
'fault and costs 1 Revenue.',
);
}
if (p.rules.stopEarnsPoint) parts.push('EARNS A POINT for one Stage spent standing still, once');
@@ -1718,14 +1813,9 @@ function switchingMoves(s: GameState, player: PlayerIndex): Frame['moves'] {
const out: Frame['moves'] = [];
for (const [id, tray] of s.trays) {
if (tray.position.at !== 'grid' || tray.position.seat !== seatOf(s, player)) continue;
/**
* A crew that may not switch is not a crew you can be switching.
*
* `movesFor` is pure track geometry — it answers where a train COULD roll — and six cards print
* "no switching", which `check` enforces and it does not. Offering the Circus Train in a "which
* train are you switching?" row is offering a train whose every move the rules refuse.
*/
if (trainProfile(tray.trainNumber ?? 0, tray.trainIsExtra)?.rules.noSwitching) continue;
// A no-switching train may still be moved clear of the mainline (§7) — only coupling, setting
// out and sorting are refused, and `check` rejects those the same way it rejects a pick-up X13
// (dropOnly) is not allowed to make, so this row is not filtered any differently for either.
const { to, blocked } = movesFor(s, player, id);
out.push({ trayId: id, label: trainName(s, id), from: tray.position.coord, to, blocked });
}
+86 -7
View File
@@ -30,6 +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 { 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,
// which would pull node:fs into a browser bundle.
@@ -53,7 +54,7 @@ import {
import type { Hand, HouseRuleOverrides, TrackGeometry } from '../engine/content.ts';
import type { Port } from '../engine/track.ts';
import { connectionsFor, joins, neighbour, variantsFor } from '../engine/track.ts';
import { areaOf, trainNeedingCars } from '../engine/apply.ts';
import { areaOf, destinationsFor, selectDestination, trainNeedingCars } from '../engine/apply.ts';
import type { Frame } from '../sim/view.ts';
export const SOLO_CONFIG: GameConfig = {
@@ -87,9 +88,65 @@ export type ActionGroup = {
* from the browser, which needs the whole `GameState`. A remote client has no state, so the menu
* carries it. See `docs/architecture/multiplayer.md` §5.
*/
actions: { index: number; label: string; tip?: string }[];
/**
* `coord` is the square the action HAPPENS ON, when it happens on one.
*
* Carried as data rather than left inside the label. Half these buttons are near-identical
* sentences distinguished only by a coordinate — "(1,3)" against "(-1,3)" — and picking the wrong
* one is recoverable in solitaire, where Undo is a click, and a disaster in a multiplayer game
* where it is not. The page hovers the matching square on the board instead of asking the player
* to read the row and column off the button. Reported by Jesse.
*
* Resolved HERE for the same reason `tip` is: a remote client holds no `GameState` and cannot look
* up where a tray is standing. See `docs/architecture/multiplayer.md` §5.
*/
actions: {
index: number;
label: string;
tip?: string;
coord?: { row: number; col: number };
/**
* Every square a `switch.move` runs OVER on its way to `coord`, when there is more than one
* legal route there (docs/plans/switching-paths.md) — so hovering a route lights the whole
* road, not just its destination, which is the only way to tell two buttons reading "move to
* (0,0)" apart before clicking one.
*/
route?: { row: number; col: number }[];
}[];
};
/**
* The square an intent acts on, or null when it acts on none.
*
* Only squares the intent NAMES. A card played out on the Mainline (`node`) is not a district
* coordinate and must not be treated as one — that confusion is exactly why `placement` and `node`
* are separate fields on the intent (see `intents.ts`) — and an action like ending a turn has no
* square at all.
*/
export function coordOf(i: Intent): { row: number; col: number } | null {
if ('at' in i) return i.at;
if ('to' in i) return i.to;
if (i.type === 'card.play' && i.placement) return i.placement;
return null;
}
/**
* Every intermediate square a `switch.move` runs over, resolved the same way `execute` resolves
* `via` — so the squares that light up on hover are exactly the squares the move will actually
* couple cars from. `undefined` for the overwhelming majority of moves, which run in a straight
* line and need nothing beyond the destination `coordOf` already carries.
*/
function routeFor(state: GameState, i: Intent): { row: number; col: number }[] | undefined {
if (i.type !== 'switch.move') return undefined;
const tray = state.trays.get(i.trayId);
if (!tray || tray.position.at !== 'grid') return undefined;
const actor = playerAtSeat(state, tray.position.seat);
const dests = destinationsFor(state, actor, i.trayId, tray.position.coord, i.reverse);
const dest = selectDestination(dests, i.to, i.via);
if (!dest || dest.path.length === 0) return undefined;
return dest.path.map((step) => step.coord);
}
export type Game = {
state: GameState;
seed: number;
@@ -212,7 +269,14 @@ export function actionGroups(game: Game): { options: Intent[]; groups: ActionGro
* to survive every edit to a line nobody would think to check. One stray byte and every crew's
* moves silently collapsed back into a single group. The tray is data; it travels as data.
*/
type Entry = { index: number; label: string; tip?: string; trayId?: string };
type Entry = {
index: number;
label: string;
tip?: string;
trayId?: string;
coord?: { row: number; col: number };
route?: { row: number; col: number }[];
};
const byKind = new Map<string, Entry[]>();
options.forEach((intent, index) => {
const label = describeIntent(game.state, intent);
@@ -227,14 +291,28 @@ export function actionGroups(game: Game): { options: Intent[]; groups: ActionGro
* on the crew as well makes the de-duplication per crew, which is what it always meant.
*/
if (!list.some((a) => a.label === label && a.trayId === trayId)) {
list.push({ index, label, ...(tip ? { tip } : {}), ...(trayId ? { trayId } : {}) });
const coord = coordOf(intent);
const route = routeFor(game.state, intent);
list.push({
index,
label,
...(tip ? { tip } : {}),
...(trayId ? { trayId } : {}),
...(coord ? { coord } : {}),
...(route ? { route } : {}),
});
}
byKind.set(intent.type, list);
});
/** Groups take the plain shape; the crew was only ever needed to split them. */
const plain = (entries: Entry[]): ActionGroup['actions'] =>
entries.map(({ index, label, tip }) => ({ index, label, ...(tip ? { tip } : {}) }));
entries.map(({ index, label, tip, coord }) => ({
index,
label,
...(tip ? { tip } : {}),
...(coord ? { coord } : {}),
}));
const groups: ActionGroup[] = [];
const used = new Set<string>();
@@ -266,7 +344,7 @@ export function actionGroups(game: Game): { options: Intent[]; groups: ActionGro
const tray = game.state.trays.get(trayId);
const where =
tray?.position.at === 'grid'
? `, standing at (${tray.position.coord.row}, ${tray.position.coord.col})`
? `, standing at (${tray.position.coord.col}, ${tray.position.coord.row})`
: '';
groups.push({
kind: prefix,
@@ -592,7 +670,8 @@ function subjectOf(
node?: number;
links: string[];
} | null {
const at = (c: { row: number; col: number }): string => `(${c.row}, ${c.col})`;
// X,Y — east/west then north/south, not the internal row/col storage order.
const at = (c: { row: number; col: number }): string => `(${c.col}, ${c.row})`;
/**
* ABS Signals is placed on a MAINLINE card, which is not in the Office Area at all — so it names
* a Division NODE and carries no coordinate. It used to travel as `{ row: -1, col: node }`, and
+53 -21
View File
@@ -11,18 +11,28 @@ body{margin:0;background:var(--bg);color:var(--fg);
font:15px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:28px}
main{width:100%;max-width:760px}
.hero{display:flex;gap:24px;align-items:flex-start}
.hero-image{width:230px;flex:none;border-radius:9px;overflow:hidden;border:1px solid var(--line);cursor:zoom-in}
.hero-image img{display:block;width:100%;height:auto}
.hero-content{flex:1;min-width:0}
@media(max-width:640px){.hero{flex-direction:column}.hero-image{width:100%;max-width:280px}}
h1{font-size:32px;margin:0 0 2px;letter-spacing:.02em}
.tag{color:var(--dim);margin:0;font-size:14px}
.blurb{color:#c6ccd6;margin:16px 0 26px;max-width:66ch}
.blurb{color:#c6ccd6;margin:16px 0 0;max-width:66ch}
.rule{height:1px;background:var(--line);margin:22px 0}
.doors{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.doors{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;margin-top:26px}
@media(max-width:640px){.doors{grid-template-columns:1fr}}
a.door{display:block;text-decoration:none;color:inherit;background:var(--panel);
.door{display:block;text-decoration:none;color:inherit;background:var(--panel);
border:1px solid var(--line);border-radius:9px;padding:18px 18px 16px;transition:.12s}
a.door:hover{border-color:#4d6fa8;background:#1f2733;transform:translateY(-1px)}
a.door h2{font-size:17px;margin:0 0 5px;color:#9fb6d8}
a.door p{margin:0;color:var(--dim);font-size:13px;line-height:1.5}
a.door .go{display:inline-block;margin-top:11px;font-size:12px;color:#5aa9e6}
.door h2{font-size:17px;margin:0 0 5px;color:#9fb6d8}
.door p{margin:0;color:var(--dim);font-size:13px;line-height:1.5}
.door .go{display:inline-block;margin-top:11px;font-size:12px;color:#5aa9e6}
.door.disabled .go{color:var(--dim)}
.lightbox{position:fixed;inset:0;background:rgba(8,10,13,.92);display:flex;
align-items:center;justify-content:center;padding:32px;z-index:10;cursor:zoom-out}
.lightbox[hidden]{display:none}
.lightbox img{display:block;max-width:90vw;max-height:90vh;border-radius:6px;box-shadow:0 12px 40px rgba(0,0,0,.5)}
/* the rule between title and blurb is drawn as rail, not decorated */
svg.trackline{width:100%;height:24px;display:block;margin:10px 0 0}
.rail{stroke:#4a5361;stroke-width:1.6}
@@ -32,24 +42,41 @@ footer{margin-top:26px;color:var(--dim);font-size:11px;display:flex;gap:18px;fle
</head>
<body>
<main>
<h1>Station Master</h1>
<p class="tag">TimeTable and Train Order (TT&amp;TO) railroading, 1840&ndash;1950.</p>
<div class="hero">
<div class="hero-image" id="hero-image" tabindex="0" role="button" aria-label="View full-size box art">
<img src="./images/station-master-splash.jpg"
alt="Station Master — TimeTable &amp; Train Order Railroading, 1840&ndash;1950. Box art: two trains meet at a junction beside a train order office."
width="560" height="700">
</div>
<div class="hero-content">
<h1>Station Master</h1>
<p class="tag">TimeTable and Train Order (TT&amp;TO) railroading, 1840&ndash;1950.</p>
<svg class="trackline" viewBox="0 0 700 24" preserveAspectRatio="none" aria-hidden="true">
<line class="rail" x1="0" y1="10" x2="700" y2="10"/>
<line class="rail" x1="0" y1="15" x2="700" y2="15"/>
<g id="ties"></g>
</svg>
<svg class="trackline" viewBox="0 0 700 24" preserveAspectRatio="none" aria-hidden="true">
<line class="rail" x1="0" y1="10" x2="700" y2="10"/>
<line class="rail" x1="0" y1="15" x2="700" y2="15"/>
<g id="ties"></g>
</svg>
<p class="blurb">
As Station Master in your line-side office, you manage the town's railroad connection. You are
responsible for all track between your Limits, a district of industries hanging beneath it, and
trains that arrive whether or not you are ready for them. Spot the right cars, work the loads,
and get every train away again &mdash; a train with nowhere to stand is a collision, and a
collision costs more than the freight was worth.
</p>
<p class="blurb">
As Station Master in your line-side office, you manage the town's railroad connection. You are
responsible for all track between your Limits, a district of industries hanging beneath it, and
trains that arrive whether or not you are ready for them. Spot the right cars, work the loads,
and get every train away again &mdash; a train with nowhere to stand is a collision, and a
collision costs more than the freight was worth.
</p>
</div>
</div>
<div class="doors">
<div class="door disabled">
<h2>Play multiplayer</h2>
<p>Play with your friends across the internet. You each run your own office area within the
entire division. You can play a normal game, or choose co-op or cutthroat. This requires
a Station Master server to be running.</p>
<span class="go">Coming soon</span>
</div>
<a class="door" href="./play.html">
<h2>Play solitaire</h2>
<p>Play by yourself and run the entire division for five full days. Your goal is 20 Revenue.
@@ -71,10 +98,15 @@ 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>runs entirely in your browser &mdash; no server code required</span>
<span>solitaire runs entirely in your browser &mdash; no server code required</span>
</footer>
</main>
<div class="lightbox" id="lightbox" hidden>
<img src="./images/station-master-splash.jpg"
alt="Station Master — TimeTable &amp; Train Order Railroading, 1840&ndash;1950. Box art: two trains meet at a junction beside a train order office.">
</div>
<script type="module" src="./web/splash.js"></script>
</body>
</html>
+174 -18
View File
@@ -9,11 +9,11 @@ import { BOARD_CSS, divisionSvg, officeSvg } from '../sim/board-svg.ts';
import { TURNCHART_CSS, turnChartHtml } from '../sim/turnchart.ts';
import type { Frame } from '../sim/view.ts';
import type { Menu, Save } from './game.ts';
import { PANEL_CSS, blockedHtml, facilitiesHtml, pilesHtml, timetableHtml, yardHtml } from './panels.ts';
import { PANEL_CSS, blockedHtml, dayEndHtml, facilitiesHtml, pilesHtml, timetableHtml, yardHtml } from './panels.ts';
import { TOOLTIP_CSS, installTooltips } from './tooltip.ts';
import { playCue } from './sound.ts';
import { MOVES_PER_LOCAL_OPS, STARTING_HAND_LABELS, houseRules } from '../engine/content.ts';
import type { HouseRuleOverrides, HouseRules, RevenueRules, StartingHand } from '../engine/content.ts';
import { EXTRA_START_LABELS, MOVES_PER_LOCAL_OPS, STARTING_HAND_LABELS, houseRules } from '../engine/content.ts';
import type { ExtraStartRule, HouseRuleOverrides, HouseRules, RevenueRules, StartingHand } from '../engine/content.ts';
import type { LocalSession } from './session.ts';
import { createLocalSession } from './session.ts';
@@ -69,6 +69,13 @@ let soundOn = false;
* ended or what happened in between. Reported exactly that way.
*/
let lastPhase: string | null = null;
/**
* The Day the page last drew, so a Day rolling over can be shown as a dialog (Gitea#10).
*
* Null until the first frame: arriving in a game already on Day 3 is not Day 2 ending, and a page
* reloaded mid-game would otherwise announce a rollover that happened before it was watching.
*/
let lastDay: number | null = null;
/**
* WHICH CREW THE BOARD IS DRAWING, when the district holds more than one.
*
@@ -110,8 +117,8 @@ const esc = (s: string): string =>
*/
function piecePreview(links: string[], label: string): string {
const cell = {
row: 0, col: 0, kind: 'trk', label, running: false, enhancements: [],
tray: null, cars: [], facility: null, links, what: '',
row: 0, col: 0, kind: 'trk', label, running: false, enhancements: [], enhancementsWhat: [],
trains: [], adTracks: null, cars: [], standingWest: 0, facility: null, links, what: '',
};
return officeSvg([cell] as never, 99).replace(
/<text class="bs-(coord|rowlab)"[^>]*>[^<]*<\/text>/g,
@@ -169,6 +176,8 @@ function rulesFromUrl(params: URLSearchParams): HouseRuleOverrides {
const rules: HouseRuleOverrides = {};
const hand = params.get('hand');
if (STARTING_HAND_LABELS.some((o) => o.value === hand)) rules.startingHand = hand as StartingHand;
const extra = params.get('extra');
if (EXTRA_START_LABELS.some((o) => o.value === extra)) rules.extraStart = extra as ExtraStartRule;
const revenue: Partial<RevenueRules> = {};
for (const [param, key] of Object.entries(RULE_PARAMS)) {
@@ -185,6 +194,9 @@ function rulesToUrl(rules: HouseRules, seed: string): string {
const params = new URLSearchParams();
if (seed !== '') params.set('seed', seed);
params.set('hand', rules.startingHand);
// The dialog answers reach `start()` through the URL and nowhere else, so a setting missing from
// here is a setting the dialog silently discards.
params.set('extra', rules.extraStart);
for (const [param, key] of Object.entries(RULE_PARAMS)) params.set(param, String(rules.revenue[key]));
return `?${params}`;
}
@@ -228,6 +240,34 @@ function applyCapabilities(): void {
hide('newgame', c.newGame);
}
/**
* THE DAY ROLLING OVER, as a dialog that has to be dismissed (Gitea#10).
*
* "As the game rolls off the end of the day, you get a dialog saying such. Hard to keep track of
* time." Nothing on screen was wrong — the clock, the turn chart and the timetable all said which
* Day it was — but a Day turns over inside the phases that run themselves, so it happens while the
* player is looking at the board waiting for their next turn. The one transient signal the page
* already had, the phase banner, is gone in 2.6 seconds.
*
* Not shown when:
* - this is the first frame (`lastDay === null`) — arriving on Day 3 is not Day 2 ending;
* - the Day went DOWN, which is Undo stepping back across the rollover, not a Day passing;
* - the game finished on that rollover, when the outcome panel is the thing to read instead.
*/
function noteDayEnd(f: Frame): void {
const previous = lastDay;
lastDay = f.day;
if (previous === null || f.day <= previous) return;
if (f.status !== 'active') return;
const dlg = document.getElementById('dayenddlg') as HTMLDialogElement | null;
const body = document.getElementById('dayendbody');
if (!dlg || !body) return;
body.innerHTML = dayEndHtml(f);
// A second rollover cannot happen while this one is open, but a redraw can — `showModal` throws
// on an already-open dialog rather than doing nothing.
if (!dlg.open) dlg.showModal();
}
function render(): void {
const f = session.view();
const menu = session.menu();
@@ -301,7 +341,14 @@ function render(): void {
: 'ATTACH TO THIS CARD';
return [{ row: cell.row, col: cell.col, label }];
});
grid.innerHTML = officeSvg(f.cells, f.runningRow, ghostCoords, legalCaps);
grid.innerHTML = officeSvg(f.cells, f.runningRow, ghostCoords, legalCaps, f.limits, selectedCrew);
// Wire the roster chips: clicking one sets `selectedCrew`, the same value the "Which train are
// you switching?" picker writes, so the board and the action panel drive one value either way.
for (const g of Array.from(grid.querySelectorAll('g[data-crew]'))) {
const trayId = (g as HTMLElement).dataset['crew'];
if (trayId) (g as unknown as HTMLElement).onclick = () => { selectedCrew = trayId; render(); };
}
// Highlighting rides on top of the drawing: outline the legal squares and make them clickable.
for (const [key, list] of spotsAt) {
@@ -337,8 +384,10 @@ function render(): void {
*/
const crew = pickedCrew(f);
if (crew && !forPlay) {
const here = grid.querySelector(`g[data-cell="${crew.from.row},${crew.from.col}"]`);
if (here) here.classList.add('bs-from');
// Marked on the crew strip, not the whole card: the Office is the one square a second train may
// share, and outlining the card would claim it belongs to both.
const strip = grid.querySelector(`g[data-cell="${crew.from.row},${crew.from.col}"] .bs-crew`);
if (strip) strip.classList.add('bs-from');
for (const c of crew.to) {
const g = grid.querySelector(`g[data-cell="${c.row},${c.col}"]`);
if (g) g.classList.add('bs-focus');
@@ -545,6 +594,8 @@ function render(): void {
}
lastPhase = f.phaseKey;
noteDayEnd(f);
/**
* A train completing its run pays every player and nobody took a turn to cause it, so it is said
* out loud rather than left in the log. Drained, so it shows once and does not re-fire on a redraw.
@@ -598,6 +649,9 @@ function renderUndo(): void {
// A phase change is announced by comparing against the last frame drawn. Stepping BACK into a
// different phase is not that event, so the banner is suppressed rather than fired backwards.
lastPhase = null;
// Same for the Day: `noteDayEnd` already ignores a Day going down, but undoing back across a
// rollover and then replaying forward through it would announce the same Day ending twice.
lastDay = null;
};
}
@@ -629,7 +683,9 @@ function renderDistrict(f: Frame): void {
else sec.classList.add('folded');
const cars = f.cells.reduce((n, c) => n + c.cars.length, 0);
const crew = f.cells.filter((c) => c.tray).length;
// Trains, not cards-with-a-crew: the Office is the one card that may hold more than one, and a
// card-count silently read "1 crew on the board" with two trains standing at a busy Station.
const crew = f.cells.reduce((n, c) => n + c.trains.length, 0);
$('districtsummary').textContent =
`${f.cells.length} cards · ${f.facilities.length} facilities · ${cars} cars standing` +
(crew > 0 ? ` · ${crew} crew on the board` : '');
@@ -650,6 +706,59 @@ function renderDistrict(f: Frame): void {
};
}
/**
* The square an action button acts on, as an attribute the board can be matched against.
*
* `null` for the actions that act on no square at all — ending a turn, drawing a card, a train card
* that goes to the timetable — so those buttons carry nothing and highlight nothing.
*/
function cellRef(
coord: { row: number; col: number } | null | undefined,
route?: { row: number; col: number }[],
): string {
const square = coord ? ` data-square="${coord.row},${coord.col}"` : '';
// Only a `switch.move` with more than one legal route carries this (docs/plans/switching-paths.md)
// — every intermediate square the chosen route runs over, so hovering lights the whole road, not
// just where it ends.
const path = route && route.length > 0 ? ` data-route="${route.map((c) => `${c.row},${c.col}`).join(' ')}"` : '';
return square + path;
}
/**
* POINT AT THE SQUARE THE BUTTON MEANS.
*
* The action list is a column of sentences that differ by a coordinate — "(1,3)" against "(-1,3)" —
* and the board is right beside it saying nothing about which one is which. Hovering a button now
* lights its square up, so the check happens with the eye rather than by reading two numbers off a
* button and finding them on a map. Reported by Jesse: recoverable in solitaire, where Undo is a
* click; a disaster in multiplayer, where it is not.
*
* ON FOCUS AS WELL AS HOVER, so tabbing through the list works the same way as pointing at it — the
* keyboard route is not a lesser one.
*
* BOTH KINDS OF SQUARE. A played card is a `data-cell`; a square being placed ONTO is an empty
* `data-ghost` target, which is precisely the case where the player is choosing between coordinates.
* Matching only one of the two would leave the most mistake-prone moment unhelped.
*/
function wirePointing(node: HTMLElement, key: string, routeKeys: readonly string[] = []): void {
const grid = $('grid');
const keys = [key, ...routeKeys];
const marks = (): Element[] =>
keys
.flatMap((k) => [grid.querySelector(`g[data-cell="${k}"]`), grid.querySelector(`g[data-ghost="${k}"]`)])
.filter((g): g is Element => g !== null);
const on = (): void => {
for (const g of marks()) g.classList.add('bs-point');
};
const off = (): void => {
for (const g of marks()) g.classList.remove('bs-point');
};
node.onmouseenter = on;
node.onmouseleave = off;
node.onfocus = on;
node.onblur = off;
}
function renderActions(
menu: Menu,
f: Frame,
@@ -694,14 +803,20 @@ function renderActions(
* the same card in hand explained itself perfectly — reported on "Realignment on Mainline card 3",
* which had neither a name for the card it meant nor a word about what it would do.
*/
const actionButton = (a: { index: number; label: string; tip?: string }): string => {
const actionButton = (a: {
index: number;
label: string;
tip?: string;
coord?: { row: number; col: number };
route?: { row: number; col: number }[];
}): string => {
const { label, index } = a;
const cut = label.indexOf(' — ');
const head = cut > 0 ? label.slice(0, cut) : label;
// The menu resolved the card's description server-side, so the page never needs the state.
const rest = cut > 0 ? label.slice(cut + 3) : (a.tip ?? '');
return (
`<button class="act" data-i="${index}"${rest ? ` data-tip="${esc(rest)}"` : ''}>${esc(head)}</button>`
`<button class="act" data-i="${index}"${cellRef(a.coord, a.route)}${rest ? ` data-tip="${esc(rest)}"` : ''}>${esc(head)}</button>`
);
};
@@ -748,9 +863,9 @@ function renderActions(
f.moves
.map(
(m) =>
`<button class="act crew${m.trayId === chosen?.trayId ? ' on' : ''}" data-crew="${esc(m.trayId)}" ` +
`data-tip="Draw this crew's reachable squares on the board, and show its moves below. ${esc(m.label)} is standing at (${m.from.row}, ${m.from.col}) with ${m.to.length} square${m.to.length === 1 ? '' : 's'} it can reach.">` +
`${esc(m.label)} <span class="dim">(${m.from.row}, ${m.from.col})</span></button>`,
`<button class="act crew${m.trayId === chosen?.trayId ? ' on' : ''}" data-crew="${esc(m.trayId)}"${cellRef(m.from)} ` +
`data-tip="Draw this crew's reachable squares on the board, and show its moves below. ${esc(m.label)} is standing at (${m.from.col}, ${m.from.row}) with ${m.to.length} square${m.to.length === 1 ? '' : 's'} it can reach.">` +
`${esc(m.label)} <span class="dim">(${m.from.col}, ${m.from.row})</span></button>`,
)
.join('') +
`</div>`;
@@ -762,9 +877,19 @@ function renderActions(
* Everything about a card in hand now lives on the card, and everything about making up a train
* lives on the yard chip. What remains is the rest of the turn: the Local Operations choice,
* drawing, switching moves, the Freight Agent, and finishing.
*
* EXCLUDE BY TITLE, NOT BY PREFIX. This used to be `!/^Making up /.test(g.title)`, on the
* assumption only the yard-chip panel's own group is ever titled that way. It is not: "choose
* where Extra X22 starts" is titled by `trainCardTitle`, which also begins "Making up Extra
* X22…", so the regex swallowed it too — and with no tray yet being filled, `menu.makeUp` is
* null, so nothing rendered it anywhere else. REPORTED as the game hanging with the Freight
* House mid-cycle: an Extra came due, the action panel had a legal decision and zero buttons,
* and nothing short of restarting looked like it would ever move again. Matching the exact
* title of the ONE group `menu.makeUp` actually covers leaves every other "Making up …" group,
* however it is titled, on screen where a player can act on it.
*/
html += menu.direct
.filter((g) => !/^(Play|Discard) a card from my hand$/.test(g.title) && !/^Making up /.test(g.title))
.filter((g) => !/^(Play|Discard) a card from my hand$/.test(g.title) && g.title !== menu.makeUp?.title)
.map(
(g) =>
`<div class="grp"><h3>${esc(g.title)}</h3>` +
@@ -847,7 +972,7 @@ function renderActions(
? ` data-tip-html="${esc(piecePreview(sp.links, item.subject))}"`
: '';
return (
`<button class="act" data-i="${sp.index}"${fig}` +
`<button class="act" data-i="${sp.index}"${fig}${cellRef(sp.coord)}` +
` data-tip="${esc(`${item.subject} — ${sp.label}`)}">${esc(sp.label)}</button>`
);
})
@@ -864,9 +989,32 @@ function renderActions(
) {
// The hand being counted is the ACTOR's — they are the one who cannot end the turn.
const hand = f.handCount;
/**
* WHEN NOTHING IN HAND MAY BE DISCARDED, SAY SO AND SAY WHAT TO DO INSTEAD.
*
* §6.2 (Gitea#9) leaves ONE kind of undiscardable card on this line — an Extra, which never
* joins the timetable and so can never be what jams it. A player holding nothing but Extras has
* exactly one way forward: play one. The rule creates that corner deliberately and needs no
* machinery, but it must not be a corner the player has to infer from a discard button that has
* quietly stopped appearing. The reason is the card's own (`handKeepWhy`) rather than a sentence
* written here, so this cannot drift from the rule that actually refused — and main, where
* `discardTimetabled` is a New Game setting and a Timetabled train is the second kind, reads the
* identical code.
*/
const stuck = f.handDiscardable.length > 0 && f.handDiscardable.every((d) => !d);
const why = f.handKeepWhy.find((w) => w !== null) ?? '';
const tip = stuck
? 'You may not end a turn holding more than three cards, and every card you hold is one that ' +
`cannot be thrown away. ${why} The only way on is to play one.`
: 'You may not end a turn holding more than three cards (four with a Red Flag). Play ' +
'one onto the board, or discard one face-up to a Department slot — where a rival may pick ' +
'it up.';
html +=
`<div class="grp"><button class="act blocked" disabled data-tip="§6.2 — you may not end a turn holding more than three cards (four with a Red Flag). Play one onto the board, or discard one face-up to a Department slot.">` +
`End Local Operations — play or discard down to three first (holding ${hand})</button></div>`;
`<div class="grp"><button class="act blocked" disabled data-tip="${tip.replace(/"/g, '&quot;')}">` +
(stuck
? `End Local Operations — play an Extra first, they cannot be discarded (holding ${hand})`
: `End Local Operations — play or discard down to three first (holding ${hand})`) +
`</button></div>`;
}
el.innerHTML = html;
@@ -882,6 +1030,9 @@ function renderActions(
render();
}
: () => apply(Number(node.dataset['i']));
const square = node.dataset['square'];
const route = node.dataset['route'];
if (square) wirePointing(node, square, route ? route.split(' ') : []);
}
}
@@ -983,6 +1134,9 @@ if (newBtn && dlg) {
for (const input of dlg.querySelectorAll<HTMLInputElement>('input[name="ng-hand"]')) {
input.checked = input.value === current.startingHand;
}
for (const input of dlg.querySelectorAll<HTMLInputElement>('input[name="ng-extra"]')) {
input.checked = input.value === current.extraStart;
}
field<HTMLInputElement>('ng-passenger').value = String(current.revenue.passengerPerCoach);
field<HTMLInputElement>('ng-freight').value = String(current.revenue.freightPerLoad);
field<HTMLInputElement>('ng-transit').value = String(current.revenue.trainPerTransit);
@@ -1004,9 +1158,11 @@ if (newBtn && dlg) {
// both mean "surprise me", which is what leaving the box alone plainly asks for.
const seed = asked === '' || !Number.isFinite(Number(asked)) ? '' : String(Math.trunc(Number(asked)));
const picked = dlg.querySelector<HTMLInputElement>('input[name="ng-hand"]:checked')?.value;
const extra = dlg.querySelector<HTMLInputElement>('input[name="ng-extra"]:checked')?.value;
const rules = houseRules({
houseRules: {
...(STARTING_HAND_LABELS.some((o) => o.value === picked) ? { startingHand: picked as StartingHand } : {}),
...(EXTRA_START_LABELS.some((o) => o.value === extra) ? { extraStart: extra as ExtraStartRule } : {}),
revenue: {
passengerPerCoach: Number(field<HTMLInputElement>('ng-passenger').value),
freightPerLoad: Number(field<HTMLInputElement>('ng-freight').value),
+76 -1
View File
@@ -31,8 +31,19 @@ export function cardRow(name: string, why: string, playable: boolean | null): st
}
export function handHtml(f: Frame, canPlay: (boolean | null)[] = []): string {
// §6.2 — say so on the card itself. A player who cannot discard a train needs to read that on the
// train, not deduce it from a button that is not there. The sentence comes off the Frame
// (`handKeepWhy`) rather than being written here: since Gitea#9 the answer depends on the card,
// and this line's rule (an Extra never, a Timetabled train always) is not main's, where it also
// depends on a New Game setting. One panel, whichever rule the game is playing.
return f.hand.length
? f.hand.map((h, i) => cardRow(h, f.handWhat[i] ?? '', canPlay[i] ?? null)).join('')
? f.hand
.map((h, i) => {
const what = f.handWhat[i] ?? '';
const held = f.handKeepWhy[i];
return cardRow(h, held ? [what, held].filter(Boolean).join(' · ') : what, canPlay[i] ?? null);
})
.join('')
: '<span class="dim">empty</span>';
}
@@ -143,6 +154,62 @@ export function timetableHtml(f: Frame, justSet: number | null): string {
return `<div class="tt">${slots}</div>`;
}
/**
* THE DAY THAT JUST ENDED — the body of the dialog `main.ts` puts up at every Day rollover.
*
* Reported as Gitea#10: "as the game rolls off the end of the day, you get a dialog saying such.
* Hard to keep track of time." The clock was on screen the whole time, but a Day turns over inside
* the automatic phases — between one click and the next — and neither the phase banner (2.6s) nor
* the announcement flash (4.2s) survives long enough to be noticed by someone reading the board.
* A modal is the point: it stops, and it waits to be dismissed.
*
* It is written from the FRAME AFTER the rollover, so `f.day` is the Day about to start and the one
* that ended is the Day before it. Standings are in Revenue order rather than seat order: the
* question at the end of a Day is who is ahead.
*
* THE GOAL COMES OFF `f.objective`, WHICH ALREADY RESOLVES IT. This line scores each player against
* a per-player target read from the game LENGTH (`lengthProfile`), and `objectiveOf` has always
* worked out both that target and whether the viewer is keeping up with the clock. Recomputing
* either here would be a second implementation of the same rule, one dialog away from disagreeing
* with the status block that shows it every turn. (Main computes a COMBINED floor instead, from
* dials this line does not have — same dialog, different question, so this half is written per line
* rather than ported.)
*/
export function dayEndHtml(f: Frame): string {
const ended = f.day - 1;
const left = f.objective.daysLeft;
const standings = [...f.players]
.sort((a, b) => b.revenue - a.revenue || a.seat - b.seat)
.map(
(p) =>
`<tr${p.index === f.viewer ? ' class="you"' : ''}><td>${esc(p.name)}` +
`${p.index === f.viewer ? ' <span class="dim">(you)</span>' : ''}</td>` +
`<td class="num">${p.revenue}</td></tr>`,
)
.join('');
// The viewer's own Revenue against the viewer's own target, because that is what `objective` is
// scoped to — `f.revenue` and `f.objective` are drawn for the same player. A target of 0 would be
// a game with no goal, and printing "0" there would read as one already met.
const target =
f.objective.target > 0
? `<p>Revenue <b>${f.revenue}</b> against a target of <b>${f.objective.target}</b> — ` +
`${f.objective.onPace ? 'on pace' : 'behind pace'}.</p>`
: '';
const ahead =
left <= 0
? '<p>That was the last Day on the timetable.</p>'
: `<p><b>Day ${f.day} of ${f.objective.days}</b> begins now — ${left} ${left === 1 ? 'Day' : 'Days'} left to run.</p>`;
return (
`<h3 class="dayend-h">Day ${ended} has ended</h3>` +
ahead +
`<table class="dayend-t"><tbody>${standings}</tbody></table>` +
target
);
}
export function blockedHtml(f: Frame): string {
return f.blocked.length === 0
? '<li class="dim">nothing blocked</li>'
@@ -397,4 +464,12 @@ ul.blocked{margin:0;padding-left:18px}
.fstat.good{background:rgba(40,140,60,.28)}
.fstat.bad{background:rgba(190,50,50,.38);font-weight:700}
.fstat.idle{opacity:.6}
/* THE DAY-END DIALOG (Gitea#10). The dialog chrome is play.html's; these are its contents, here
because dayEndHtml is here — a panel and its styling stay together. */
.dayend-h{font-size:15px;text-transform:none;letter-spacing:0;color:#e6e9ee;margin:0 0 8px}
.dayend-t{border-collapse:collapse;margin:9px 0;min-width:210px}
.dayend-t td{padding:3px 12px 3px 0;border-top:1px solid #2c333d}
.dayend-t tr:first-child td{border-top:0}
.dayend-t .num{text-align:right;font-variant-numeric:tabular-nums;font-weight:700;padding-right:0}
.dayend-t .you td{color:#8fd6a0}
`;
+22
View File
@@ -322,6 +322,15 @@ ul.blocked li{padding:2px 0}
<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>
<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>
<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 of §7. 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" checked>
<span><b>Also any player’s Control Point</b><br><span class="dim">The most permissive, and what the game did before this setting existed.</span></span></label>
<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>
<label class="ng-num"><span>Passenger revenue per coach</span>
@@ -339,6 +348,19 @@ ul.blocked li{padding:2px 0}
</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:
"hard to keep track of time". Filled by `dayEndHtml` and opened from `render()`. -->
<dialog id="dayenddlg" aria-labelledby="de-title">
<form method="dialog">
<div id="dayendbody"></div>
<menu class="ng-buttons">
<button value="ok" id="de-ok" type="submit">Carry on</button>
</menu>
</form>
</dialog>
<script type="module" src="./web/main.js"></script>
</body>
</html>
+1 -1
View File
@@ -122,7 +122,7 @@ function show(i: number): void {
$('vpos').textContent = `${at} / ${steps.length - 1}`;
($('vscrub') as HTMLInputElement).value = String(at);
$('vdivision').innerHTML = divisionSvg(f.division);
$('vgrid').innerHTML = officeSvg(f.cells, f.runningRow);
$('vgrid').innerHTML = officeSvg(f.cells, f.runningRow, [], [], f.limits);
// Auto-hide: the district is worth its space during the phases that change it.
const open = districtMode === 'auto' ? FOCUS_PHASES.has(f.phaseKey) : districtMode === 'open';
+81 -17
View File
@@ -64,6 +64,38 @@ export function playCue(cue: string): void {
osc.stop(at + dur + 0.02);
};
/**
* A burst of filtered noise — the breath of steam behind a whistle, one chuff of a moving
* locomotive, or the boom of an impact. Shared by `stage` (one long burst) and the chuffs in
* `arrive`/`depart` (several short ones), and the wide-open burst under `crash`.
*/
const noiseBurst = (
at: number,
dur: number,
gain: number,
freq: number,
q: number,
type: BiquadFilterType = 'bandpass',
): void => {
const frames = Math.max(1, Math.floor(c.sampleRate * dur));
const buf = c.createBuffer(1, frames, c.sampleRate);
const data = buf.getChannelData(0);
for (let i = 0; i < frames; i++) data[i] = Math.random() * 2 - 1;
const src = c.createBufferSource();
src.buffer = buf;
const filt = c.createBiquadFilter();
filt.type = type;
filt.frequency.value = freq;
filt.Q.value = q;
const amp = c.createGain();
amp.gain.setValueAtTime(0, at);
amp.gain.linearRampToValueAtTime(gain, at + Math.min(0.05, dur / 4));
amp.gain.exponentialRampToValueAtTime(0.0001, at + dur);
src.connect(filt).connect(amp).connect(c.destination);
src.start(at);
src.stop(at + dur + 0.02);
};
const t = c.currentTime + 0.02;
if (cue === 'stage') {
@@ -73,23 +105,55 @@ export function playCue(cue: string): void {
for (const fg of [[392, 0.16], [466, 0.13], [587, 0.1], [784, 0.05]]) {
tone(t, fg[0]!, d, fg[1]!, 'sawtooth', fg[0]! * 0.985);
}
const frames = Math.floor(c.sampleRate * d);
const buf = c.createBuffer(1, Math.max(1, frames), c.sampleRate);
const data = buf.getChannelData(0);
for (let i = 0; i < frames; i++) data[i] = Math.random() * 2 - 1;
const src = c.createBufferSource();
src.buffer = buf;
const band = c.createBiquadFilter();
band.type = 'bandpass';
band.frequency.value = 1400;
band.Q.value = 0.8;
const amp = c.createGain();
amp.gain.setValueAtTime(0, t);
amp.gain.linearRampToValueAtTime(0.05, t + 0.05);
amp.gain.exponentialRampToValueAtTime(0.0001, t + d);
src.connect(band).connect(amp).connect(c.destination);
src.start(t);
src.stop(t + d);
noiseBurst(t, d, 0.05, 1400, 0.8);
return;
}
if (cue === 'arrive') {
/**
* A LOCOMOTIVE SLOWING TO A STOP: chuffs (one per wheel revolution) spaced FARTHER apart as
* road speed drops, then a soft two-partial bell tap as it settles — a lighter cousin of the
* `day` bell, not a repeat of it.
*/
let at = t;
const gaps = [0.13, 0.17, 0.22, 0.28];
for (let i = 0; i < gaps.length; i++) {
noiseBurst(at, 0.07, 0.11 - i * 0.015, 190, 1.1, 'bandpass');
at += gaps[i]!;
}
for (const fg of [[1046, 0.07], [1568, 0.04]]) {
tone(at + 0.12, fg[0]!, 0.3, fg[1]!, 'sine');
}
return;
}
if (cue === 'depart') {
/**
* THE INVERSE OF `arrive`: chuffs starting slow and pulling closer together as the train
* gathers speed, then one falling, fading horn note — a single call, not `completed`'s pair,
* since this train is only leaving the Office, not clearing the whole Division.
*/
let at = t;
const gaps = [0.22, 0.15, 0.1, 0.07, 0.05];
for (let i = 0; i < gaps.length; i++) {
noiseBurst(at, 0.06, 0.06 + i * 0.012, 210, 1.2, 'bandpass');
at += gaps[i]!;
}
tone(at, 349, 0.45, 0.1, 'sawtooth', 300);
return;
}
if (cue === 'crash') {
/**
* IMPACT, NOT MUSIC: two tones bent sharply downward at a DISSONANT (non-harmonic) interval,
* so the ear reads a collision rather than a chord — `couple`'s clank is consonant on purpose,
* and this is its opposite. A wide-open noise boom and a percussive sub-bass thump give it
* weight under the screech.
*/
tone(t, 311, 0.35, 0.16, 'square', 70);
tone(t, 233, 0.4, 0.13, 'sawtooth', 52);
noiseBurst(t, 0.4, 0.16, 900, 0.4, 'lowpass');
tone(t, 45, 0.3, 0.18, 'sine');
return;
}
+19
View File
@@ -7,3 +7,22 @@ if (ties) {
}
ties.innerHTML = out;
}
/** Clicking the box art opens it full size, since the thumbnail is too small to read. */
const heroImage = document.getElementById('hero-image');
const lightbox = document.getElementById('lightbox');
if (heroImage && lightbox) {
const open = () => { lightbox.hidden = false; };
const close = () => { lightbox.hidden = true; };
heroImage.addEventListener('click', open);
heroImage.addEventListener('keydown', (e) => {
if (e instanceof KeyboardEvent && (e.key === 'Enter' || e.key === ' ')) {
e.preventDefault();
open();
}
});
lightbox.addEventListener('click', close);
document.addEventListener('keydown', (e) => {
if (e instanceof KeyboardEvent && e.key === 'Escape') close();
});
}
+343 -79
View File
@@ -8,13 +8,13 @@ import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { advance, pump } from '../src/engine/advance.ts';
import { applyIntent, areaOf, check } from '../src/engine/apply.ts';
import { HAND_LIMIT, STAGES_PER_DAY, lengthProfile, TOTAL_ROLLING_STOCK } from '../src/engine/content.ts';
import { applyIntent, areaOf, check, isBeingMadeUp } from '../src/engine/apply.ts';
import { EXPEDITE_FAULT_PENALTY, HAND_LIMIT, MAX_CONSIST, STAGES_PER_DAY, lengthProfile, TOTAL_ROLLING_STOCK } from '../src/engine/content.ts';
import { legalActions } from '../src/engine/legal.ts';
import { createGame } from '../src/engine/setup.ts';
import { developerBot } from '../src/sim/bot.ts';
import type { CrewTray, GameConfig, GameState } from '../src/engine/state.ts';
import { railFacingOf } from '../src/engine/state.ts';
import type { CrewTray, DivisionNode, GameConfig, GameState } from '../src/engine/state.ts';
import { coordKey, railFacingOf } from '../src/engine/state.ts';
const baseConfig = (over: Partial<GameConfig> = {}): GameConfig => ({
mode: 'solitaire',
@@ -690,9 +690,16 @@ describe('the history says WHY a train moved, and says it truthfully', () => {
* them — it may be the rules are wrong, or it may be my perception."
*
* It was perception, but the log was actively feeding it. Every departure read alike, and the
* arrival line for an Expedited train said there was "no turn in which to work it" — which is
* false and cost the player the Cargo turn they did have. These pin the two claims the log now
* makes, so a phase-order change cannot leave the narration lying about it.
* arrival line for an Expedited train said there was "no turn in which to work it" — which was
* false under the OLD (v0.4.8 and earlier) same-stage-departure reading of Q3, and cost the player
* the Cargo turn they did have.
*
* v0.4.9 CORRECTED Q3 ITSELF, not just the narration: Expedite does not change when a train
* leaves — it is released by the ordinary §8.1 rules exactly like any other train, and may be
* switched normally while it stands. What it means is that the train must not be PARKED anywhere
* but the station; leaving it on Secondary Track when a Mainline Phase begins is a Station Master
* fault (`expediteFault`, `EXPEDITE_FAULT_PENALTY`). These pin that behaviour, so a phase-order
* change cannot silently bring back the old forced departure.
*/
/**
* Drop one named train at the Western Division Point and follow it, counting the DISTINCT phases
@@ -704,11 +711,10 @@ describe('the history says WHY a train moved, and says it truthfully', () => {
const s = game(7, { length: 'standard' });
for (const n of s.division.nodes) if (n.kind === 'mainline') n.card = 'plains';
/**
* A DIVISION WITH NOTHING ELSE ON IT. Expedite is not absolute: §8.1 can still hold the train,
* and `shiftChange` says so — "an expedited train that would need a ruling simply stays, and
* runs normally next Stage". With the bot's own traffic running, Train 6 was held four Stages
* and collected four Local Operations turns, which is correct behaviour and the opposite of what
* this test is trying to pin. Clearing the timetable isolates the rule from the traffic.
* A DIVISION WITH NOTHING ELSE ON IT. §8.1 can still hold any train, Expedited or not, on a
* same-direction meet — with the bot's own traffic running, Train 6 was held four Stages and
* collected four Local Operations turns. Correct behaviour, but it is traffic noise for what
* this test is trying to pin, so clearing the timetable isolates the rule from it.
*/
s.timetable = s.timetable.map(() => null);
const id = 'watched';
@@ -779,40 +785,55 @@ describe('the history says WHY a train moved, and says it truthfully', () => {
assert.equal(r.leftIn, 'mainline', 'an ordinary train should leave in a Mainline Phase');
});
it('gives an Expedited train the Cargo phase but never Local Operations', () => {
// Train 6 The Sparrow — Expedite. The claim the arrival line makes is precisely this pair:
// Porters and Laborers can reach it, a switching turn never comes, and it goes at the end of
// the Stage rather than in a Mainline Phase.
it('gives an Expedited train a Local Operations turn too, exactly like an ordinary one', () => {
// Train 6 The Sparrow — Expedite. v0.4.9 corrected Q3: Expedite no longer forces a same-stage
// departure, so an Expedited train is released by the ordinary §8.1 rule and stands for a
// Local Operations turn the same as Train 12 above.
const r = phasesWith(6);
assert.equal(r.localOps, 0, 'an Expedited train got a Local Operations turn after all');
assert.ok(r.localOps >= 1, `an Expedited train got ${r.localOps} Local Operations turns`);
assert.ok(r.loadUnload >= 1, 'an Expedited train never stood through a Cargo phase');
assert.equal(r.leftIn, 'shiftChange', 'an Expedited train should leave in Supervisor Shift');
assert.equal(r.leftIn, 'mainline', 'an Expedited train should leave in a Mainline Phase, like any other');
});
it('does NOT expedite when §8.1 wants a ruling — it stays and runs normally', () => {
/**
* EXPEDITE IS CONDITIONAL, which is most of why it feels arbitrary at the table.
*
* `shiftChange` says so — "an expedited train that would need a ruling simply stays, and runs
* normally next Stage" — and it happens often: driven by the developer bot this was reached by
* ordinary traffic, and Train 6 collected FOUR Local Operations turns instead of none. Built by
* hand here rather than fished out of a bot game, because whether the bot happens to produce a
* meet depends on the deck, and the deck moves.
*
* So the log and the card must not promise that an Expedited train can never be switched.
*/
it('faults an Expedited train left off the station when a Mainline Phase begins', () => {
// What Expedite actually restricts now: not WHEN the train leaves, but WHERE it may be left
// standing in the meantime. Parked on Secondary Track — cleared there to make way for other
// switching, say — it must not still be there when the next Mainline Phase begins.
const s = game(7, { length: 'standard' });
for (const n of s.division.nodes) if (n.kind === 'mainline') n.card = 'plains';
const area = areaOf(s, 0);
const id = 'expedited';
const secondary = { row: area.officeCoord.row, col: area.officeCoord.col + 1 };
s.trays.set(id, {
id, trainNumber: 6, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'east', facing: 'e',
position: { at: 'grid', seat: 0, coord: secondary }, movesUsed: 0,
});
// Train 6 (Expedite) standing at the Office, having just arrived: this is the state
// `arriveAtOffice` leaves behind when it sets `departsThisStage`.
s.clock.phase = 'mainline';
const before = s.players[0]!.revenue;
const r = advance(s);
assert.ok(
r.events.some((e) => e.type === 'expediteFault' && e.trainNumber === 6),
'no fault was raised for an Expedited train left off the station',
);
assert.equal(
s.players[0]!.revenue,
before - EXPEDITE_FAULT_PENALTY,
'the fault did not cost Revenue',
);
});
it('does not fault an Expedited train legitimately held at the station itself', () => {
// A train sitting on the Office square is not "left" anywhere — including one §8.1 is holding
// for a same-direction meet, which is an ordinary hold, not a Station Master failure.
const s = game(7, { length: 'standard' });
const area = areaOf(s, 0);
const id = 'expedited';
s.trays.set(id, {
id, trainNumber: 6, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'east', facing: 'e',
position: { at: 'grid', seat: 0, coord: area.officeCoord }, movesUsed: 0,
departsThisStage: true,
});
area.adOccupancy.push(id);
@@ -829,41 +850,42 @@ describe('the history says WHY a train moved, and says it truthfully', () => {
node.transits.push({ tray: 'ahead', stagesRemaining: 2, stagesTotal: 2, direction: 'east' });
}
s.clock.phase = 'shiftChange';
s.clock.phase = 'mainline';
const before = s.players[0]!.revenue;
const r = advance(s);
assert.ok(
r.events.some((e) => e.type === 'clearanceRequested' && e.trainId === id),
'the Expedited departure was not put to the Superintendent',
);
assert.equal(
s.trays.get(id)?.position.at,
'grid',
'the Expedited train left despite needing a ruling nobody could give',
'the departure was not put to the Superintendent',
);
assert.ok(
r.events.some((e) => e.type === 'trainHeld' && /EXPEDITES/.test(e.reason)),
'the log does not say why the Expedited train stayed',
!r.events.some((e) => e.type === 'expediteFault'),
'a train properly parked at the station was faulted anyway',
);
assert.equal(
s.trays.get(id)?.departsThisStage,
false,
'it should run as an ordinary train from now on, not retry the expedited departure',
s.players[0]!.revenue,
before,
'Revenue changed for a train legitimately held at the station',
);
});
});
// ---------------------------------------------------------------------------
describe('an Extra starts where its number sends it, or at a Control Point', () => {
describe('an Extra starts where the player puts it (Gitea#4)', () => {
/**
* REPORTED: "Extras should start at Eastern or Western Division point based on their numbers. Even
* trains run to the east (start at western DP), odd run to the west (start at eastern DP). They
* can also start at a control point (any office except whistlepost) at player's choice."
* REPORTED, v0.4.9e: "When extras are played the player doing so may choose where the extra
* starts. They may choose either division point. And if the interchange mainline card has been
* played, they may start the extra on that card and choose the direction from there. If there is
* potential for conflict with other trains in that area the superintendent may hold the extra."
*
* Every Extra used to launch eastbound from the West Division Point, hardcoded, with the
* simplification flagged in a comment — so half the Extras ran the wrong way and the Control Point
* option did not exist at all.
* This SUPERSEDES the earlier ruling these tests used to assert — "the number decides, like
* everything else on the timetable" — for Extras only. The number still decides for a timetabled
* train. The reason the two cannot both hold: an odd (westbound) Extra placed at the WEST end
* would leave the Division on its first move having crossed nothing, and be paid for the run.
*
* So: the start decides the direction. A Division Point runs the train away from itself; in the
* middle of the railroad — an Interchange, a Control Point — the player says which way.
*/
const pending = (trainNumber: number, tier?: 'depot' | 'station'): GameState => {
const s = game(11);
@@ -881,6 +903,14 @@ describe('an Extra starts where its number sends it, or at a Control Point', ()
return tray;
};
/** Turn one Mainline card into an Interchange, and say which node it is. */
const withInterchange = (s: GameState): number => {
const i = s.division.nodes.findIndex((n) => n.kind === 'mainline');
const node = s.division.nodes[i]!;
if (node.kind === 'mainline') node.card = 'interchange';
return i;
};
it('stops for the decision instead of launching the train itself', () => {
const s = pending(17);
assert.equal(s.clock.phase, 'newTrain');
@@ -891,36 +921,46 @@ describe('an Extra starts where its number sends it, or at a Control Point', ()
);
});
it('sends an odd Extra west from the EASTERN Division Point', () => {
// §2.3 — odd runs west. It therefore starts at the end it runs away from.
it('offers BOTH Division Points, not the one the number would dictate', () => {
const s = pending(17);
assert.ok(applyIntent(s, 0, { type: 'newTrain.startExtra', trainNumber: 17, atSeat: null }).ok);
const tray = started(s);
assert.equal(tray.direction, 'west');
assert.equal(tray.position.at === 'divisionPoint' && tray.position.side, 'east');
const sides = legalActions(s, 0)
.filter((i) => i.type === 'newTrain.startExtra' && i.start?.kind === 'divisionPoint')
.map((i) => (i.type === 'newTrain.startExtra' && i.start?.kind === 'divisionPoint' ? i.start.side : ''));
assert.deepEqual([...sides].sort(), ['east', 'west']);
});
it('sends an even Extra east from the WESTERN Division Point', () => {
const s = pending(18);
assert.ok(applyIntent(s, 0, { type: 'newTrain.startExtra', trainNumber: 18, atSeat: null }).ok);
const tray = started(s);
assert.equal(tray.direction, 'east');
assert.equal(tray.position.at === 'divisionPoint' && tray.position.side, 'west');
it('runs an Extra AWAY from the Division Point it was placed at, whatever its number', () => {
// X17 is odd. Under the superseded rule it could only ever start at the East end and run west.
for (const [side, direction] of [['west', 'east'], ['east', 'west']] as const) {
const s = pending(17);
const r = applyIntent(s, 0, {
type: 'newTrain.startExtra', trainNumber: 17, start: { kind: 'divisionPoint', side },
});
assert.ok(r.ok, `the ${side} Division Point was refused: ${r.ok ? '' : r.code}`);
const tray = started(s);
assert.equal(tray.direction, direction, `an Extra at the ${side} end must run ${direction}`);
assert.equal(tray.position.at === 'divisionPoint' && tray.position.side, side);
}
});
it('refuses a Whistle Post, which is not a Control Point', () => {
const s = pending(18);
assert.equal(s.officeAreas.get(0)!.tier, 'whistlePost');
assert.equal(
check(s, 0, { type: 'newTrain.startExtra', trainNumber: 18, atSeat: 0 }),
'NOT_A_CONTROL_POINT',
);
it('refuses a Whistle Post, which is not a Control Point, at every setting of the house rule', () => {
for (const extraStart of ['divisionPointsOnly', 'ownOffice', 'anyOffice'] as const) {
const s = pending(18);
s.config = { ...s.config, houseRules: { ...s.config.houseRules, extraStart } };
assert.equal(s.officeAreas.get(0)!.tier, 'whistlePost');
const code = check(s, 0, {
type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'office', seat: 0 }, direction: 'east',
});
assert.ok(code !== null, `a Whistle Post was allowed under ${extraStart}`);
}
});
it('starts at a Control Point when the player picks one, taking an A/D track', () => {
// Upgrading the Office is what buys this: a Depot is a Control Point, a Whistle Post is not.
const s = pending(18, 'depot');
const r = applyIntent(s, 0, { type: 'newTrain.startExtra', trainNumber: 18, atSeat: 0 });
const r = applyIntent(s, 0, {
type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'office', seat: 0 }, direction: 'west',
});
assert.ok(r.ok, `starting at the Depot was refused: ${r.ok ? '' : r.code}`);
const tray = started(s);
const area = s.officeAreas.get(0)!;
@@ -931,16 +971,240 @@ describe('an Extra starts where its number sends it, or at a Control Point', ()
'the Extra did not start on the Office card',
);
assert.ok(area.adOccupancy.includes(tray.id), 'it did not take an A/D track');
assert.equal(tray.direction, 'east', 'an even Extra still runs east from wherever it starts');
// The point of the change: an EVEN Extra running WEST, because the player said so.
assert.equal(tray.direction, 'west', 'the direction the player chose was not honoured');
});
it('needs a direction anywhere that is not an end of the Division', () => {
const s = pending(18, 'depot');
assert.equal(
check(s, 0, { type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'office', seat: 0 } }),
'NO_DIRECTION_CHOSEN',
);
});
it('honours the extraStart house rule for Office starts, and never for the shared ground', () => {
for (const [extraStart, code] of [
['divisionPointsOnly', 'OFFICE_STARTS_NOT_ALLOWED'],
['anyOffice', null],
] as const) {
const s = pending(18, 'depot');
s.config = { ...s.config, houseRules: { ...s.config.houseRules, extraStart } };
assert.equal(
check(s, 0, {
type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'office', seat: 0 }, direction: 'east',
}),
code,
`office start under ${extraStart}`,
);
// The Division Points belong to nobody, so no setting ever closes them.
assert.equal(
check(s, 0, { type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'divisionPoint', side: 'west' } }),
null,
);
}
});
it('starts at an Interchange in the players yard, not out on the running line', () => {
const s = pending(18);
const node = withInterchange(s);
const r = applyIntent(s, 0, {
type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'mainline', node }, direction: 'east',
});
assert.ok(r.ok, `the Interchange was refused: ${r.ok ? '' : r.code}`);
const tray = started(s);
const card = s.division.nodes[node]!;
assert.equal(tray.direction, 'east');
assert.deepEqual(tray.position, { at: 'mainline', index: node });
assert.ok(card.kind === 'mainline' && card.holding?.includes(tray.id), 'it is not in the yard');
assert.equal(card.kind === 'mainline' && card.transits.length, 0, 'it was put on the running line');
});
it('refuses any Mainline card that is not an Interchange', () => {
const s = pending(18);
const plains = s.division.nodes.findIndex((n) => n.kind === 'mainline');
const node = s.division.nodes[plains]!;
if (node.kind === 'mainline') node.card = 'plains';
assert.equal(
check(s, 0, { type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'mainline', node: plains }, direction: 'east' }),
'NOT_AN_INTERCHANGE',
);
});
it('may be started at an Interchange however busy the card is — the yard forces no collision', () => {
const s = pending(18);
const node = withInterchange(s);
const card = s.division.nodes[node]!;
// Nose to tail with opposing traffic. §7: placing here still must not force a collision.
if (card.kind === 'mainline') {
card.transits.push({ tray: 'tray9', stagesRemaining: 2, stagesTotal: 2, direction: 'west' });
}
assert.equal(
check(s, 0, { type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'mainline', node }, direction: 'east' }),
null,
);
});
/**
* §7's last clause, and the reason the Interchange start is modelled as a yard at all: "If there
* is potential for conflict with other trains in that area the superintendent may hold the extra."
*
* Jesse's split: a GUARANTEED collision holds the train at the Interchange for another Stage and
* it tries again; a POTENTIAL one is the Superintendent's to rule on. Those are exactly §8.1's
* two answers, so the Extra highballs out of the yard through `evaluateClearance` — the same
* check a train leaving a Division Point goes through — rather than through anything new.
*/
describe('highballing out of the Interchange yard', () => {
/** A pending X18 sitting in the yard of an Interchange, with the terrain pinned. */
const inYard = (): { s: GameState; node: number; tray: CrewTray } => {
const s = pending(18);
const node = withInterchange(s);
const r = applyIntent(s, 0, {
type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'mainline', node }, direction: 'east',
});
assert.ok(r.ok, `the Interchange was refused: ${r.ok ? '' : r.code}`);
s.clock.phase = 'mainline';
s.movedThisPhase = new Set();
return { s, node, tray: started(s) };
};
const card = (s: GameState, node: number): Extract<DivisionNode, { kind: 'mainline' }> => {
const n = s.division.nodes[node]!;
assert.equal(n.kind, 'mainline');
return n as Extract<DivisionNode, { kind: 'mainline' }>;
};
it('pulls out onto the card at the next Mainline Phase when the Subdivision is clear', () => {
const { s, node, tray } = inYard();
advance(s);
const n = card(s, node);
assert.deepEqual(n.holding, [], 'it never left the yard');
assert.ok(n.transits.some((t) => t.tray === tray.id), 'it is not on the running line');
});
it('is held in the yard by a facing train, and tries again the next Stage', () => {
const { s, node, tray } = inYard();
// Westbound, against an eastbound Extra: §8.1 calls that an absolute bar, not a judgment call.
card(s, node).transits.push({ tray: 'facing', stagesRemaining: 2, stagesTotal: 2, direction: 'west' });
s.trays.set('facing', {
id: 'facing', trainNumber: 3, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'west', position: { at: 'mainline', index: node }, movesUsed: 0,
});
const r = advance(s);
assert.equal(r.needsInput ?? false, false, 'a guaranteed collision is not a question to ask');
assert.equal(s.clock.pendingDecision, null);
assert.ok(card(s, node).holding?.includes(tray.id), 'it was not held in the yard');
assert.ok(
!card(s, node).transits.some((t) => t.tray === tray.id),
'it pulled out in front of a train coming the other way',
);
assert.ok(s.trays.has(tray.id), 'the Extra was destroyed rather than held');
// AND IT TRIES AGAIN. The Extra waits in the yard, not on the pending list, so once the road
// clears the next Mainline Phase takes it out with no further intervention.
s.trays.delete('facing');
card(s, node).transits = [];
s.clock.phase = 'mainline';
s.movedThisPhase = new Set();
advance(s);
assert.deepEqual(card(s, node).holding, [], 'it did not try again once the road was clear');
assert.ok(card(s, node).transits.some((t) => t.tray === tray.id), 'it never pulled out');
});
it('puts a following train to the Superintendent rather than holding it automatically', () => {
const { s, node, tray } = inYard();
// Same direction: §8.1's judgment call, which is what "may hold the extra" means.
card(s, node).transits.push({ tray: 'ahead', stagesRemaining: 2, stagesTotal: 2, direction: 'east' });
s.trays.set('ahead', {
id: 'ahead', trainNumber: 4, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'east', position: { at: 'mainline', index: node }, movesUsed: 0,
});
const r = advance(s);
assert.equal(r.needsInput, true, 'the phase must stop and ask');
assert.equal(s.clock.pendingDecision?.train, tray.id);
assert.equal(s.clock.pendingDecision?.occupiedBy, 'ahead');
// HOLD keeps it in the yard.
assert.ok(applyIntent(s, s.clock.superintendent, { type: 'mainline.clearance', allow: false }).ok);
advance(s);
assert.ok(card(s, node).holding?.includes(tray.id), 'the Superintendent held it and it left anyway');
});
});
/**
* FOUND BY PLAYING IT, not by the tests above: an Extra started anywhere but a Division Point was
* never offered a car and ran empty.
*
* `isBeingMadeUp` asked only "is this tray standing at a Division Point", which was the whole
* truth while that was the only place to build a train. The Control Point start has therefore
* shipped since it was added with a train that could not be loaded, and the Interchange start
* would have shipped the same way — against Jesse's report, which says an Extra started at the
* Interchange "would be Loaded with cars".
*/
describe('an Extra started away from a Division Point can still be made up', () => {
const fill = (s: GameState): string[] => {
for (let i = 0; i < MAX_CONSIST + 1; i++) {
const options = legalActions(s, s.clock.currentActor ?? 0).filter((a) => a.type === 'newTrain.placeCar');
if (options.length === 0) break;
assert.ok(applyIntent(s, s.clock.currentActor ?? 0, options[0]!).ok);
}
return started(s).consist.map((c) => c.type);
};
it('takes a consist in the Interchange yard', () => {
const s = pending(18);
const node = withInterchange(s);
assert.ok(applyIntent(s, 0, {
type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'mainline', node }, direction: 'east',
}).ok);
assert.ok(fill(s).length > 0, 'the Extra was never offered a car and would have run empty');
});
it('takes a consist at a Control Point', () => {
const s = pending(18, 'depot');
assert.ok(applyIntent(s, 0, {
type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'office', seat: 0 }, direction: 'east',
}).ok);
assert.ok(fill(s).length > 0, 'the Extra was never offered a car and would have run empty');
});
it('stops being made up the moment it starts running', () => {
// Otherwise a train out on the Mainline could be handed cars from the Division Yard — the
// "cars appearing on a train nobody was making up" bug `isBeingMadeUp` exists to prevent.
const s = pending(18);
const node = withInterchange(s);
assert.ok(applyIntent(s, 0, {
type: 'newTrain.startExtra', trainNumber: 18, start: { kind: 'mainline', node }, direction: 'east',
}).ok);
const tray = started(s);
s.clock.phase = 'mainline';
s.movedThisPhase = new Set();
advance(s);
assert.equal(s.trays.get(tray.id)?.beingMadeUp, undefined, 'a running train is still being made up');
assert.equal(isBeingMadeUp(s.trays.get(tray.id)!), false);
});
});
it('replays a save written before the choice existed exactly as it meant it', () => {
/**
* A save is a seed and a list of intents, so an intent whose meaning moves is a save that
* quietly replays as a different game. The legacy shape carried only `atSeat`: null meant the
* Division Point the NUMBER sent it to, running in the number's direction.
*/
const s = pending(17);
assert.ok(applyIntent(s, 0, { type: 'newTrain.startExtra', trainNumber: 17, atSeat: null }).ok);
const tray = started(s);
assert.equal(tray.direction, 'west', 'the legacy intent stopped meaning what it meant');
assert.equal(tray.position.at === 'divisionPoint' && tray.position.side, 'east');
});
it('takes the Extra off the pending list once, whichever end it started from', () => {
const s = pending(17);
assert.ok(applyIntent(s, 0, { type: 'newTrain.startExtra', trainNumber: 17, atSeat: null }).ok);
const at = { type: 'newTrain.startExtra', trainNumber: 17, start: { kind: 'divisionPoint', side: 'east' } } as const;
assert.ok(applyIntent(s, 0, at).ok);
assert.deepEqual(s.pendingExtras, []);
assert.equal(
check(s, 0, { type: 'newTrain.startExtra', trainNumber: 17, atSeat: null }),
'NO_EXTRA_PENDING',
);
assert.equal(check(s, 0, at), 'NO_EXTRA_PENDING');
});
});
+700 -10
View File
@@ -7,6 +7,7 @@ import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { applyIntent, check, areaOf, facilityCarTypes, movesFor, reduce } from '../src/engine/apply.ts';
import { pump } from '../src/engine/advance.ts';
import { HAND_LIMIT, INDUSTRY_PROFILES, MAX_CONSIST, MOVES_PER_LOCAL_OPS, officeProfile } from '../src/engine/content.ts';
import type { Intent } from '../src/engine/intents.ts';
import { legalActions } from '../src/engine/legal.ts';
@@ -56,6 +57,7 @@ const straight = (standing: TrackCard['standing'] = []): TrackCard => ({
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true,
standing,
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -258,6 +260,189 @@ describe('Local Operations: drawing (§6.2)', () => {
assert.equal(check(s, 0, { type: 'draw.end' }), null, 'the turn cannot be ended even at the limit');
});
describe('which train cards may be discarded (Gitea#9, superseding Gitea#6)', () => {
/**
* Gitea#6's ruling, v0.4.9e playtest, was that NO train card may be discarded. Gitea#9 narrows
* it — Jesse, 2026-08-24: "Timetabled trains are at the choice of the player: they can either
* play or discard. If someone else wants to pick it up, they are more than able to. The reason:
* I don't want, if you decide to play a game longer than five days, to decide that maybe there
* are too many trains, the stations are jammed, and the railroad doesn't need any more."
*
* So a Timetabled train is discardable, an EXTRA still is not — it never joins the timetable, so
* it cannot be what jams it — and whether the Timetabled half applies is a New Game setting,
* because the reasoning is about long games and a five-Day game may want Gitea#6's pressure.
*
* Note there is still no FORCING mechanism, and deliberately so: the corner is what the two
* existing rules produce together whenever the setting is off.
*/
const handOf = (s: GameState, kinds: string[]): string[] => {
// Hand-pick cards of the wanted kinds straight out of the catalogue, so the test does not
// depend on what the shuffle happened to deal.
const picked: string[] = [];
for (const want of kinds) {
for (const [id, card] of s.cards) {
if (card.kind.kind !== want || picked.includes(id)) continue;
picked.push(id);
break;
}
}
assert.equal(picked.length, kinds.length, 'the catalogue is missing a card this test needs');
s.decks.hands.set(0, picked);
return picked;
};
/** The same game with the setting turned off — Gitea#6's rule, still reachable. */
const strictGame = (): GameState =>
createGame({
id: 'g',
seed: 77,
config: { ...config, houseRules: { ...(config.houseRules ?? {}), discardTimetabled: false } },
playerNames: ['Jesse'],
});
it('lets a Timetabled train be discarded, and still refuses an Extra', () => {
const s = game();
applyIntent(s, 0, { type: 'localOps.choose', option: 'draw' });
const [timetabled, extra, track] = handOf(s, ['timetabledTrain', 'extraTrain', 'track']);
assert.equal(
check(s, 0, { type: 'card.discard', cardId: timetabled!, toSlot: 0 }),
null,
'Gitea#9 allows this and it was refused',
);
assert.equal(
check(s, 0, { type: 'card.discard', cardId: extra!, toSlot: 0 }),
'TRAINS_ARE_NEVER_DISCARDED',
'an Extra never joins the timetable, so Gitea#9 does not reach it',
);
assert.equal(check(s, 0, { type: 'card.discard', cardId: track!, toSlot: 0 }), null);
});
it('puts the discarded train where a rival can pick it up', () => {
// The other half of the ruling — "if someone else wants to pick it up, they are more than able
// to" — needed no machinery, because a discard already goes face-up onto a Department pile.
const s = game();
applyIntent(s, 0, { type: 'localOps.choose', option: 'draw' });
const [timetabled] = handOf(s, ['timetabledTrain', 'track']);
assert.ok(applyIntent(s, 0, { type: 'card.discard', cardId: timetabled!, toSlot: 1 }).ok);
const pile = s.decks.departments[1]!;
assert.equal(pile[pile.length - 1], timetabled, 'the train is not face-up on the pile');
});
it('offers the discard as a legal action, so the bot can take it', () => {
const s = game();
applyIntent(s, 0, { type: 'localOps.choose', option: 'draw' });
const [timetabled, extra] = handOf(s, ['timetabledTrain', 'extraTrain', 'track']);
const offered = legalActions(s, 0).filter((i) => i.type === 'card.discard');
assert.ok(
offered.some((i) => i.type === 'card.discard' && i.cardId === timetabled),
'a Timetabled train was not offered as a discard',
);
assert.ok(
!offered.some((i) => i.type === 'card.discard' && i.cardId === extra),
'an Extra was offered as a discard',
);
});
it('keeps Gitea#6 reachable when the setting is off', () => {
const s = strictGame();
applyIntent(s, 0, { type: 'localOps.choose', option: 'draw' });
const [timetabled, extra, track] = handOf(s, ['timetabledTrain', 'extraTrain', 'track']);
for (const id of [timetabled!, extra!]) {
assert.equal(
check(s, 0, { type: 'card.discard', cardId: id, toSlot: 0 }),
'TRAINS_ARE_NEVER_DISCARDED',
);
}
assert.equal(check(s, 0, { type: 'card.discard', cardId: track!, toSlot: 0 }), null);
});
it('leaves PLAYING a train as the only way out of a hand of four, setting off', () => {
const s = strictGame();
applyIntent(s, 0, { type: 'localOps.choose', option: 'draw' });
const four = handOf(s, ['timetabledTrain', 'timetabledTrain', 'timetabledTrain', 'extraTrain']);
assert.ok(four.length > HAND_LIMIT, 'this test needs a hand over the limit');
// Over the limit, so the turn cannot be ended...
assert.equal(check(s, 0, { type: 'draw.end' }), 'HAND_LIMIT');
// ...and not one of them may be discarded...
for (const id of four) {
assert.equal(check(s, 0, { type: 'card.discard', cardId: id, toSlot: 0 }), 'TRAINS_ARE_NEVER_DISCARDED');
}
// ...but playing one is always legal, so the player is never actually stuck.
assert.equal(check(s, 0, { type: 'card.play', cardId: four[0]! }), null);
assert.ok(applyIntent(s, 0, { type: 'card.play', cardId: four[0]! }).ok);
assert.equal(s.decks.hands.get(0)!.length, HAND_LIMIT);
assert.equal(check(s, 0, { type: 'draw.end' }), null, 'playing a train did not free the turn');
});
it('a hand of four Extras is the corner that survives Gitea#9 with the setting ON', () => {
// Gitea#9 does not reach an Extra, so the deadlock-that-is-not-a-deadlock is still real in a
// default game — worth pinning, since it is now the ONLY way to reach it.
const s = game();
applyIntent(s, 0, { type: 'localOps.choose', option: 'draw' });
const four = handOf(s, ['extraTrain', 'extraTrain', 'extraTrain', 'extraTrain']);
assert.equal(check(s, 0, { type: 'draw.end' }), 'HAND_LIMIT');
for (const id of four) {
assert.equal(check(s, 0, { type: 'card.discard', cardId: id, toSlot: 0 }), 'TRAINS_ARE_NEVER_DISCARDED');
}
assert.ok(applyIntent(s, 0, { type: 'card.play', cardId: four[0]! }).ok);
assert.equal(check(s, 0, { type: 'draw.end' }), null);
});
it('lets a train be held across Stages and into the next Day', () => {
// "They may keep the card in their hand for multiple stages and even multiple days." Nothing
// sweeps a hand at a Stage or Day boundary, and this is what says so out loud. An Extra is
// used, because it is the card that still cannot be got rid of any other way.
const s = game();
const [extra] = handOf(s, ['extraTrain', 'track']);
const startDay = s.clock.day;
// Play out Stages by taking whatever ends the current turn, until the Day turns over.
for (let guard = 0; guard < 400 && s.clock.day === startDay; guard++) {
pump(s);
const actor = s.clock.currentActor;
if (actor === null) break;
const options = legalActions(s, actor);
const end = options.find((i) => i.type.endsWith('.end')) ?? options[0];
if (!end) break;
applyIntent(s, actor, end);
}
assert.ok(s.clock.day > startDay, `the Day never turned (stopped at ${s.clock.day}/${s.clock.stage})`);
assert.ok(
(s.decks.hands.get(0) ?? []).includes(extra!),
'the train did not survive being held into the next Day',
);
assert.equal(
check(s, 0, { type: 'card.discard', cardId: extra!, toSlot: 0 }),
'TRAINS_ARE_NEVER_DISCARDED',
'a Day boundary made an Extra discardable',
);
});
it('tells the player on the card itself which of the two rules applies', () => {
// The Gitea#2 lesson: a rule the player cannot see is a board with nothing to click and no
// reason given. Since Gitea#9 there are TWO reasons, so the card has to say which.
const s = game();
handOf(s, ['timetabledTrain', 'extraTrain', 'track']);
const f = snapshot(s, [], null);
// `hand` is reversed for display, so compare as a set rather than by position.
assert.deepEqual([...f.handDiscardable].sort(), [false, true, true]);
const said = f.handKeepWhy.filter((w): w is string => w !== null);
assert.equal(said.length, 1, 'exactly one card in this hand may not be discarded');
assert.match(said[0]!, /An Extra is never discarded/);
const strict = strictGame();
handOf(strict, ['timetabledTrain', 'extraTrain', 'track']);
const sf = snapshot(strict, [], null);
assert.deepEqual([...sf.handDiscardable].sort(), [false, false, true]);
assert.ok(
sf.handKeepWhy.some((w) => w !== null && /never discarded in this game/.test(w)),
'the setting being off is not explained on the card',
);
});
});
it('discards face up ON TOP of a chosen Department, burying what was there', () => {
// The choice of WHICH Department is the strategy: a card put on an empty-ish pile is an offer, a
// card put on top of one a rival wants takes that card out of reach. Overwriting the slot — what
@@ -445,6 +630,7 @@ describe('Freight Agent operations (§6.3)', () => {
geometry: { kind: 'facility', facility: 'mineTipple' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: {
kind: 'freight',
subtype: 'mineTipple',
@@ -576,6 +762,7 @@ describe('Load/Unload: the four-action freight pipeline (§9.3)', () => {
geometry: { kind: 'facility', facility: 'mineTipple' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: {
kind: 'freight',
subtype: 'mineTipple',
@@ -682,6 +869,61 @@ describe('Load/Unload: the four-action freight pipeline (§9.3)', () => {
assert.equal(check(s, 0, { type: 'laborer.startLoad', at: coord }), 'NO_EMPTY_CAR_SPOTTED');
});
it('unloads the car the player actually picked, not always the westmost one', () => {
// REPORTED FROM PLAY: three loaded cars stood at a Freight House; asking to unload the EAST
// (index 2) car unloaded the WEST one instead, every time, regardless of which car was picked.
// The reducer for `unloadBegan` used to re-derive the target with
// `industryTrack.cars.findIndex(c => c.loaded)`, which always answers the first loaded car in
// track order no matter which `carIndex` the intent actually named.
const s = game();
const coord = at(-1, 0);
addCard(s, coord, {
geometry: { kind: 'facility', facility: 'freightHouse' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: {
kind: 'freight',
subtype: 'freightHouse',
allows: { outbound: true, inbound: true },
outboundBox: [],
inboundBox: [],
capacity: { outbound: 1, inbound: 1 },
menAtWork: [null, null, null],
industryTrack: {
cars: [
{ type: 'boxcar', loaded: true },
{ type: 'hopper', loaded: true },
{ type: 'tank', loaded: true },
],
},
laborers: 3,
porters: 0,
usedThisStage: { laborers: 0, porters: 0 },
},
modifiers: [],
enhancements: [],
});
s.clock.phase = 'loadUnload';
// An empty replacement of every type standing on the track, so `check` never refuses for a
// reason unrelated to what this test is about.
s.yards.divisionYard.push(
{ type: 'boxcar', loaded: false },
{ type: 'hopper', loaded: false },
{ type: 'tank', loaded: false },
);
const r = applyIntent(s, 0, { type: 'laborer.beginUnload', at: coord, carIndex: 2 });
assert.ok(r.ok, 'unloading the east (index 2) car should be legal');
const f = areaOf(s, 0).grid.get(coordKey(coord))!.facility!;
assert.equal(f.industryTrack.cars[0]!.type, 'boxcar', 'the west car must be untouched');
assert.equal(f.industryTrack.cars[0]!.loaded, true, 'the west car must still be loaded');
assert.equal(f.industryTrack.cars[1]!.type, 'hopper', 'the middle car must be untouched');
assert.equal(f.industryTrack.cars[1]!.loaded, true, 'the middle car must still be loaded');
assert.equal(f.industryTrack.cars[2]!.type, 'tank', 'the east car — the one picked — must still be there');
assert.equal(f.industryTrack.cars[2]!.loaded, false, 'the east car is the one that should be emptied');
});
it('takes four Laborer actions in total for one point', () => {
// The asymmetry the whole economy is calibrated against (card-reference.md §2).
const s = game();
@@ -757,6 +999,7 @@ describe('legalActions shares its rules with apply (component 6)', () => {
geometry: { kind: 'facility', facility: 'mineTipple' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: {
kind: 'freight',
subtype: 'mineTipple',
@@ -930,6 +1173,177 @@ describe('a Modifier only goes beside a host that can use it (regression)', () =
// ---------------------------------------------------------------------------
describe('the Limits bound the district, and the nine spots reach round a Facility', () => {
/**
* A district whose Running Track has been extended one square east, so the sign stands at col 2
* and there is a siding hanging below the main to build on:
*
* row 0: [lim] [office] [turnout, leg south] [lim] <- Running Track, Limits at -1 and 2
* row -1: [curve ne]
*
* Returns the industry-ready square under the sign, at (-1, 2).
*/
function district(s: GameState): GridCoord {
const area = areaOf(s, 0);
const plain = (geometry: object): TrackCard => ({
geometry: geometry as TrackCard['geometry'],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
const col = area.limitsEast.col;
area.grid.set(coordKey(at(area.runningRow, col)), plain({
kind: 'track', geometry: 'turnout', turnout: { stem: 'w', through: 'e', diverge: 's' }, hand: 'left',
}));
area.grid.set(coordKey(at(area.runningRow - 1, col)), plain({
kind: 'track', geometry: 'curved', arc: 'ne', hand: 'left',
}));
area.limitsEast = at(area.runningRow, col + 1);
area.grid.set(coordKey(area.limitsEast), plain({ kind: 'limits' }));
s.clock.phase = 'localOps';
s.clock.currentActor = 0;
turnOf(s, 0).option = 'draw';
return at(area.runningRow - 1, col + 1);
}
const trackInHand = (s: GameState, geometry: string): string => {
for (const [id, card] of s.cards) {
if (card.kind.kind === 'track' && card.kind.geometry === geometry) {
s.decks.hands.set(0, [id]);
return id;
}
}
throw new Error(`no ${geometry} card`);
};
const industryOf = (s: GameState, facility: string): string => {
for (const [id, card] of s.cards) {
if (card.kind.kind === 'freightFacility' && card.kind.facility === facility) {
s.decks.hands.set(0, [id]);
return id;
}
}
throw new Error(`no industry card: ${facility}`);
};
const modifierOf = (s: GameState, modifier: string): string => {
for (const [id, card] of s.cards) {
if (card.kind.kind === 'modifier' && card.kind.modifier === modifier) {
s.decks.hands.set(0, [id]);
return id;
}
}
throw new Error(`no modifier card: ${modifier}`);
};
/** An industry standing on the board, so a Modifier has a host to hang off. */
const buildFacility = (s: GameState, kind: string, coord: GridCoord): void => {
areaOf(s, 0).grid.set(coordKey(coord), {
geometry: { kind: 'facility', facility: kind, axis: 'ew' },
baseOperationalRail: true, standing: [], modifiers: [], enhancements: [],
facility: {
kind: 'freight', subtype: kind,
allows: { outbound: true, inbound: false },
outboundBox: [], inboundBox: [], capacity: { outbound: 1, inbound: 0 },
menAtWork: [null, null, null],
industryTrack: { cars: [] },
laborers: 1, porters: 0, usedThisStage: { laborers: 0, porters: 0 },
},
} as never);
};
it('accepts a siding in the sign\'s own column and refuses one past it', () => {
/**
* REPORTED by Jesse: "sidings should not be allowed to be built outside the limits". §3 defines
* Secondary Track as "all tracks IN YOUR LIMITS that are not the Running Track", so the bound
* belongs to the district rather than to the one row the sign stands in — it used to guard the
* Running Track alone, and a siding could run east past a player's own sign, taking industries
* with it, onto track that §8.1 and §10 do not consider his territory at all.
*
* INCLUSIVE of the sign's column, which is the half that keeps the game playable: the opening
* district is signs at ±1 around the Office, so the strict reading would leave one buildable
* column and break §11.3's promise that both Secondary rows are usable from the first Stage.
*/
const s = game();
const under = district(s);
const cardId = trackInHand(s, 'straight');
assert.equal(
check(s, 0, { type: 'card.play', cardId, placement: under }),
null,
'a siding may run under the Limits sign — the sign stands ON the boundary, not beyond it',
);
assert.equal(
check(s, 0, { type: 'card.play', cardId, placement: at(under.row, under.col + 1) }),
'OUTSIDE_LIMITS',
'a siding was built outside the district it belongs to',
);
});
it('refuses an industry outside the Limits — a Facility carries track', () => {
// §11.2: "Facility cards carry their own rails — placing a Facility places track." So the bound
// is the same one, and said with the same code rather than left to read as NOT_CONNECTED.
const s = game();
const under = district(s);
const cardId = industryOf(s, 'mineTipple');
assert.equal(check(s, 0, { type: 'card.play', cardId, placement: under }), null);
assert.equal(
check(s, 0, { type: 'card.play', cardId, placement: at(under.row, under.col + 1) }),
'OUTSIDE_LIMITS',
);
});
it('offers a Modifier the DIAGONAL spots around its host, not just the four orthogonal ones', () => {
/**
* REPORTED by Jesse: a Modifier could not be placed to the south-east of his industry. §9 places
* one "adjacent to a Facility, on any of the nine nearby spots" and `check` has always accepted
* all eight neighbours — it was `placementCandidates` that walked north, south, east and west
* only, so a diagonal square with no orthogonal neighbour was legal and never offered.
*/
const s = game();
const under = district(s);
buildFacility(s, 'packingSheds', under);
const cardId = modifierOf(s, 'iceHouse');
const offered = legalActions(s, 0)
.filter((i) => i.type === 'card.play' && i.cardId === cardId && i.placement !== undefined)
.map((i) => coordKey((i as { placement: GridCoord }).placement));
// South-east of the host, and orthogonally adjacent to nothing at all.
const southEast = at(under.row - 1, under.col + 1);
assert.ok(
offered.includes(coordKey(southEast)),
`the south-east spot (${southEast.row}, ${southEast.col}) is legal but was never offered — offered: ${offered.join(' ')}`,
);
assert.equal(check(s, 0, { type: 'card.play', cardId, placement: southEast }), null);
});
it('lets a Modifier hang outside the Limits, but never in the Running Track row', () => {
/**
* Jesse's call, both halves. A Modifier is not track (§9), so a host standing at the limit keeps
* all nine of its spots — refusing the outer three would make the card unplayable exactly where
* the district ends. The Running Track ROW is the exception: inside the Limits that row is
* always full, so this bites only beyond the sign, and that is the ground the main grows onto —
* a Modifier parked there would block the player's own sign from moving outward (§2.1).
*/
const s = game();
const under = district(s);
buildFacility(s, 'packingSheds', under);
const cardId = modifierOf(s, 'iceHouse');
const area = areaOf(s, 0);
assert.equal(
check(s, 0, { type: 'card.play', cardId, placement: at(under.row, under.col + 1) }),
null,
'a Modifier beside a host at the limit was refused the spot outside it',
);
assert.equal(
check(s, 0, { type: 'card.play', cardId, placement: at(area.runningRow, under.col + 1) }),
'ON_RUNNING_TRACK',
'a Modifier was allowed to stand in the row the Running Track grows along',
);
});
});
// ---------------------------------------------------------------------------
describe("a Modifier grants only what its host's flow can use", () => {
const withFacility = (kind: string, out: boolean, into: boolean) => ({
geometry: { kind: 'facility', facility: kind, axis: 'ew' },
@@ -1054,9 +1468,11 @@ describe("a Modifier grants only what its host's flow can use", () => {
* and saying so is what the panel is for. Losing it FOREVER was the bug: the upgrade applied
* only the difference between two tiers and knew nothing about what had been discarded.
*
* This used to be written against an Ice House on a Grocer's Warehouse. That case no longer
* suppresses anything, because the Grocer's is a both-direction facility — which was the other
* half of the same report.
* This used to be written against an Ice House on a Grocer's Warehouse, which suppresses again
* now that the Grocer's is inbound-only (v0.4.9e). The Office was chosen instead because the
* suppression there is TEMPORARY — an upgrade can lift it — and losing the grant forever across
* that upgrade was the bug. A Grocer's never ships, so its Ice House is suppressed permanently
* and tests nothing about the upgrade path.
*/
const s = game();
const area = areaOf(s, 0);
@@ -1111,14 +1527,19 @@ describe('Industry cards go on a stub, and lock each other out', () => {
* A district with a siding hanging off the Running Track, which is the only place an industry may
* go. Returns the siding square east of the curve.
*
* row 0: [lim] [office] [turnout, leg south] … <- Running Track
* row 0: [lim] [office] [turnout, leg south] [lim] <- Running Track
* row -1: [curve ne] [siding square]
*
* The turnout is laid ON the east Limits sign, which is how the Running Track grows — so the sign
* MOVES OUT with it (§2.1, Gap 4a), exactly as `extendLimitsIfNeeded` does when the card is played
* rather than written straight into the grid. Without that the siding square would be outside the
* district's own Limits, which is no longer a place track may go.
*/
function withSiding(s: GameState): GridCoord {
const area = areaOf(s, 0);
const plain = (geometry: object): TrackCard => ({
geometry: geometry as TrackCard['geometry'],
baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
const col = area.limitsEast.col;
area.grid.set(coordKey(at(area.runningRow, col)), plain({
@@ -1127,6 +1548,8 @@ describe('Industry cards go on a stub, and lock each other out', () => {
area.grid.set(coordKey(at(area.runningRow - 1, col)), plain({
kind: 'track', geometry: 'curved', arc: 'ne', hand: 'left',
}));
area.limitsEast = at(area.runningRow, col + 1);
area.grid.set(coordKey(area.limitsEast), plain({ kind: 'limits' }));
s.clock.phase = 'localOps';
s.clock.currentActor = 0;
turnOf(s, 0).option = 'draw';
@@ -1148,7 +1571,7 @@ describe('Industry cards go on a stub, and lock each other out', () => {
function build(s: GameState, kind: string, coord: GridCoord): void {
areaOf(s, 0).grid.set(coordKey(coord), {
geometry: { kind: 'facility', facility: kind as never },
baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
}
@@ -1443,8 +1866,9 @@ describe('the engine is drawn pointing east or west, whatever track it is standi
addCard(s, at(0, 0), straight());
reduce(s, moved(id, 's'));
const cell = snapshot(s, [], null).cells.find((c) => c.row === 0 && c.col === 0);
assert.ok(cell?.train, 'the train should be on the card');
assert.ok(cell.train.facing === 'e' || cell.train.facing === 'w', `got ${cell.train.facing}`);
const train = cell?.trains[0];
assert.ok(train, 'the train should be on the card');
assert.ok(train.facing === 'e' || train.facing === 'w', `got ${train.facing}`);
});
});
@@ -1468,6 +1892,7 @@ describe('a train that rounds a curve points where the curve took it', () => {
geometry: { kind: 'track', geometry: 'curved', arc, hand: 'right' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -1604,11 +2029,11 @@ describe('the switching job a player actually does: put a car in a siding, take
*/
const curve = (arc: 'ne' | 'nw' | 'se' | 'sw'): TrackCard => ({
geometry: { kind: 'track', geometry: 'curved', arc, hand: 'right' },
baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
const turnout = (o: { stem: 'n' | 's' | 'e' | 'w'; through: 'n' | 's' | 'e' | 'w'; diverge: 'n' | 's' | 'e' | 'w' }): TrackCard => ({
geometry: { kind: 'track', geometry: 'turnout', turnout: o, hand: 'right' },
baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
it('takes a cut off the Running Track into a siding and sets it out', () => {
@@ -1656,3 +2081,268 @@ describe('the switching job a player actually does: put a car in a siding, take
);
});
});
// ---------------------------------------------------------------------------
/**
* The v0.4.9d playtest, three reports with two causes.
*
* "Freight House: boxcars loaded cannot be immediately unloaded", "passenger stations: passengers
* just boarded cannot be immediately unloaded" — one rule, `RollingStock.origin`. And "operating two
* trains in a station: the select button does not work, regardless of which you pick it is always
* one train, not the other" — the porter intents carrying no tray.
*/
describe('a load may not be broken in the district that made it (v0.4.9e)', () => {
const office = (s: GameState) => areaOf(s, 0).grid.get(coordKey(areaOf(s, 0).officeCoord))!.facility!;
/** An Office that can work passengers, with someone waiting and Porters to hand. */
function platform(s: GameState): void {
const f = office(s);
f.allows = { outbound: true, inbound: true };
f.porters = 4;
f.capacity = { outbound: 2, inbound: 2 };
f.outboundBox = [{ type: 'coach', loaded: true }];
s.yards.divisionYard.push({ type: 'coach', loaded: false });
s.clock.phase = 'loadUnload';
s.clock.currentActor = 0;
}
/** A tray standing on an A/D track at the Office. */
function atOffice(s: GameState, consist: CrewTray['consist']): string {
const id = s.freeTrays.pop()!;
s.trays.set(id, {
id, trainNumber: null, trainIsExtra: false, engineAt: 0, consist,
direction: 'east', position: { at: 'grid', seat: 0, coord: areaOf(s, 0).officeCoord }, movesUsed: 0,
});
areaOf(s, 0).adOccupancy.push(id);
return id;
}
/** A Freight House with a load staged, an empty spotted, and Laborers enough to finish. */
function freightHouse(s: GameState, coord: GridCoord): void {
areaOf(s, 0).grid.set(coordKey(coord), {
geometry: { kind: 'facility', facility: 'freightHouse' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: {
kind: 'freight', subtype: 'freightHouse',
allows: { outbound: true, inbound: true },
outboundBox: [{ type: 'boxcar', loaded: true }],
inboundBox: [],
capacity: { outbound: 1, inbound: 1 },
menAtWork: [null, null, null],
industryTrack: { cars: [{ type: 'boxcar', loaded: false }] },
laborers: 9, porters: 0,
usedThisStage: { laborers: 0, porters: 0 },
},
modifiers: [], enhancements: [],
} as TrackCard);
s.yards.divisionYard.push({ type: 'boxcar', loaded: false }, { type: 'boxcar', loaded: false });
s.clock.phase = 'loadUnload';
s.clock.currentActor = 0;
}
/** Walk a staged load all the way onto the spotted car. */
function finishLoad(s: GameState, coord: GridCoord): void {
applyIntent(s, 0, { type: 'laborer.startLoad', at: coord });
for (const box of [0, 1, 2]) applyIntent(s, 0, { type: 'laborer.advanceLoad', at: coord, box });
}
it('refuses to unload the boxcar the Freight House just loaded', () => {
const s = game();
const coord = at(-1, 0);
freightHouse(s, coord);
finishLoad(s, coord);
const f = areaOf(s, 0).grid.get(coordKey(coord))!.facility!;
assert.deepEqual(f.industryTrack.cars.map((c) => c.loaded), [true], 'the load never reached the car');
assert.equal(f.industryTrack.cars[0]!.origin, 0, 'the load is not stamped with the district that made it');
assert.equal(
check(s, 0, { type: 'laborer.beginUnload', at: coord, carIndex: 0 }),
'LOADED_IN_THIS_DISTRICT',
);
// And it is not merely absent from the menu by accident — the menu agrees with `check`.
assert.ok(
!legalActions(s, 0).some((i) => i.type === 'laborer.beginUnload'),
'the unload was still offered',
);
});
it('unloads a load that came from somewhere else', () => {
// The mirror, and the reason the rule is a stamp rather than a per-facility flag: a car made up
// at a Division Point out of the common supply carries no origin, and is exactly the inbound
// traffic a district lives on.
const s = game();
const coord = at(-1, 0);
freightHouse(s, coord);
const f = areaOf(s, 0).grid.get(coordKey(coord))!.facility!;
f.industryTrack.cars = [{ type: 'boxcar', loaded: true }];
assert.equal(check(s, 0, { type: 'laborer.beginUnload', at: coord, carIndex: 0 }), null);
});
it('refuses to detrain the passengers this Office just put aboard', () => {
const s = game();
platform(s);
const tray = atOffice(s, [{ type: 'coach', loaded: false }]);
assert.ok(applyIntent(s, 0, { type: 'porter.board', at: areaOf(s, 0).officeCoord, trayId: tray }).ok);
const coach = s.trays.get(tray)!.consist[0]!;
assert.equal(coach.loaded, true, 'nobody boarded');
assert.equal(coach.origin, 0, 'the coach is not stamped with the Office that filled it');
assert.equal(
check(s, 0, { type: 'porter.detrain', at: areaOf(s, 0).officeCoord, trayId: tray }),
'LOADED_IN_THIS_DISTRICT',
);
});
it('detrains passengers who boarded somewhere else', () => {
const s = game();
platform(s);
const tray = atOffice(s, [{ type: 'coach', loaded: true }]);
assert.equal(check(s, 0, { type: 'porter.detrain', at: areaOf(s, 0).officeCoord, trayId: tray }), null);
});
it('takes the origin stamp off a coach that reaches the red box', () => {
// The stamp belongs to the LOAD. A coach going into the inbound box has finished its journey and
// heads back to a yard from there; carrying the stamp on would poison the common supply.
const s = game();
platform(s);
const tray = atOffice(s, [{ type: 'coach', loaded: true, origin: 1 }]);
assert.ok(applyIntent(s, 0, { type: 'porter.detrain', at: areaOf(s, 0).officeCoord, trayId: tray }).ok);
assert.equal(office(s).inboundBox[0]!.origin, undefined, 'the stamp survived the red box');
});
});
describe('two trains in one station are told apart (v0.4.9e)', () => {
function twoAtOffice(s: GameState): [string, string] {
const area = areaOf(s, 0);
const f = area.grid.get(coordKey(area.officeCoord))!.facility!;
f.allows = { outbound: true, inbound: true };
f.porters = 4;
f.capacity = { outbound: 2, inbound: 2 };
f.outboundBox = [{ type: 'coach', loaded: true }, { type: 'coach', loaded: true }];
s.clock.phase = 'loadUnload';
s.clock.currentActor = 0;
const ids: string[] = [];
for (let n = 0; n < 2; n++) {
const id = s.freeTrays.pop()!;
s.trays.set(id, {
id, trainNumber: null, trainIsExtra: false, engineAt: 0,
consist: [{ type: 'coach', loaded: false }],
direction: 'east', position: { at: 'grid', seat: 0, coord: area.officeCoord }, movesUsed: 0,
});
area.adOccupancy.push(id);
ids.push(id);
}
return [ids[0]!, ids[1]!];
}
it('offers boarding on each train, not once for the platform', () => {
// REPORTED: "operating two trains in a station, the select button does not work — regardless of
// which you pick, it is always one train, not the other." There was one button, because the
// intent carried no train at all.
const s = game();
const [a, b] = twoAtOffice(s);
const boards = legalActions(s, 0).filter((i) => i.type === 'porter.board');
assert.deepEqual(
boards.map((i) => (i as { trayId?: string }).trayId).sort(),
[a, b].sort(),
'both trains at the platform must be offered',
);
});
it('boards the train the player named, not the first on the A/D tracks', () => {
const s = game();
const [a, b] = twoAtOffice(s);
assert.ok(applyIntent(s, 0, { type: 'porter.board', at: areaOf(s, 0).officeCoord, trayId: b }).ok);
assert.equal(s.trays.get(b)!.consist[0]!.loaded, true, 'the named train did not get the passengers');
assert.equal(s.trays.get(a)!.consist[0]!.loaded, false, 'the other train was filled instead');
});
it('still works for an intent that names no train, so old saves replay', () => {
// `trayId` is optional for the same reason `switch.move`'s `via` is: intents are the canonical
// record every save and every undo replays against.
const s = game();
const [a] = twoAtOffice(s);
assert.ok(applyIntent(s, 0, { type: 'porter.board', at: areaOf(s, 0).officeCoord }).ok);
assert.equal(s.trays.get(a)!.consist[0]!.loaded, true, 'the first eligible train should have taken them');
});
});
/**
* Reported from the v0.4.9d playtest and NOT reproduced: "when I back up to collect standing cars
* and, further down the tracks, the caboose, I get the caboose but the cars remain. I can later
* drive right through them."
*
* Coupling is mandatory (§A.4) and the walk accumulates what it meets card by card, so cars the
* engine can see always couple — which means cars a train can drive through are cars the engine does
* not think are there. Nothing found: `carsOn` is the single answer to "what is standing here" and
* the movement walk, the sweep and every renderer all ask it. These pin the shapes that were tried,
* so if the case is found later it is somewhere none of them cover.
*/
describe('backing up over a cut to something beyond it takes both (v0.4.9d report)', () => {
const boxcar = () => ({ type: 'boxcar' as const, loaded: false });
const caboose = () => ({ type: 'caboose' as const, loaded: false });
/** A Freight House card, with cars spotted on its industry track. */
function industry(cars: TrackCard['standing']): TrackCard {
return {
geometry: { kind: 'facility', facility: 'freightHouse' },
baseOperationalRail: true, standing: [], standingWest: 0,
facility: {
kind: 'freight', subtype: 'freightHouse',
allows: { outbound: true, inbound: true },
outboundBox: [], inboundBox: [], capacity: { outbound: 1, inbound: 1 },
menAtWork: [null, null, null], industryTrack: { cars: [...cars] },
laborers: 1, porters: 0, usedThisStage: { laborers: 0, porters: 0 },
},
modifiers: [], enhancements: [],
} as TrackCard;
}
const empty = (s: GameState, ...coords: GridCoord[]): void => {
for (const c of coords) {
assert.deepEqual(carsOn(areaOf(s, 0).grid.get(coordKey(c))!), [], `cars left standing at (${c.col},${c.row})`);
}
};
it('takes a cut standing on plain track on the way to the caboose', () => {
const s = game();
addCard(s, at(0, 2), straight());
addCard(s, at(0, 1), straight([boxcar(), boxcar()]));
addCard(s, at(0, 0), straight([caboose()]));
const id = placeTray(s, at(0, 2));
applyIntent(s, 0, { type: 'localOps.choose', option: 'switch' });
assert.ok(applyIntent(s, 0, { type: 'switch.move', trayId: id, to: at(0, 0), reverse: true }).ok);
assert.deepEqual(s.trays.get(id)!.consist.map((c) => c.type), ['boxcar', 'boxcar', 'caboose']);
empty(s, at(0, 1), at(0, 0));
});
it('takes cars SPOTTED AT AN INDUSTRY on the way, not just the destination', () => {
// Jesse's best guess at the reported shape. An industry card is plain east-west track carrying a
// facility, and `carsOn` reads its industry track rather than the card — so this is the case
// where the two could have come apart.
const s = game();
addCard(s, at(0, 2), straight());
addCard(s, at(0, 1), industry([boxcar(), boxcar()]));
addCard(s, at(0, 0), straight([caboose()]));
const id = placeTray(s, at(0, 2));
applyIntent(s, 0, { type: 'localOps.choose', option: 'switch' });
assert.ok(applyIntent(s, 0, { type: 'switch.move', trayId: id, to: at(0, 0), reverse: true }).ok);
assert.deepEqual(s.trays.get(id)!.consist.map((c) => c.type), ['boxcar', 'boxcar', 'caboose']);
empty(s, at(0, 1), at(0, 0));
});
it("takes the train's own cut off the square it is standing on as well", () => {
const s = game();
addCard(s, at(0, 1), straight());
addCard(s, at(0, 0), straight([caboose()]));
const id = placeTray(s, at(0, 1), [boxcar(), boxcar()]);
applyIntent(s, 0, { type: 'localOps.choose', option: 'switch' });
// Set the pair out behind the engine, pull forward, then back up past them to the caboose.
assert.ok(applyIntent(s, 0, { type: 'switch.dropCars', trayId: id, count: 2 }).ok);
assert.equal(carsOn(areaOf(s, 0).grid.get(coordKey(at(0, 1)))!).length, 2);
assert.ok(applyIntent(s, 0, { type: 'switch.move', trayId: id, to: at(0, 0), reverse: true }).ok);
assert.deepEqual(s.trays.get(id)!.consist.map((c) => c.type), ['boxcar', 'boxcar', 'caboose']);
empty(s, at(0, 1), at(0, 0));
});
});
+9 -1
View File
@@ -36,6 +36,7 @@ const straight = (standing: RollingStock[] = []): TrackCard => ({
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true,
standing,
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -149,7 +150,14 @@ describe('a cut parks in the same order however many cars come off at once', ()
// Facing east: the nose cut (boxcar) is set out east of the engine, the tail cut (tank) west.
assert.deepEqual(standingAt(s, at(1, 0)), ['tank', 'boxcar']);
assert.equal(s.trays.get(id)!.standingWest, 1, 'the engine should be standing between the two cuts');
// `standingWest` lives on the CARD now, not the tray (docs/plans/switching-paths.md — "The
// Roster Pass"): the Office is the one square more than one train may share, and a cut lies
// west or east of the block of A/D tracks rather than of any one engine.
assert.equal(
areaOf(s, 0).grid.get(coordKey(at(1, 0)))!.standingWest,
1,
'the engine should be standing between the two cuts',
);
});
});
+57 -19
View File
@@ -29,6 +29,7 @@ const straight = (): TrackCard => ({
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -467,9 +468,10 @@ describe('§8.1 — a train that just arrived from the mainline stops for the St
* Nothing states the rule, which makes it exactly the kind of property a later change to the loop
* would break in silence. These pin it.
*
* It is also what gives the printed **Expedite** rule something to do — an Expedited train departs
* at the END of the Stage it arrived, precisely because the general rule forbids it departing at
* all. It stands through Load/Unload first, which is what makes its coaches workable.
* v0.4.9 CORRECTED Q3 so **Expedite is not an exception to this any more**: an Expedited train
* stops for the Stage exactly like any other and may be switched in the Local Operations turn that
* follows. What Expedite restricts is where the train may be left standing afterwards, not when it
* departs — see `advance.test.ts`'s `expediteFault` coverage for that half.
*/
const arriving = (s: GameState, trainNumber: number, isExtra = false): string => {
const id = 'arriving';
@@ -502,12 +504,14 @@ describe('§8.1 — a train that just arrived from the mainline stops for the St
);
});
it('unless its card prints Expedite — but it still stands through Load/Unload first', () => {
it('an Expedite train follows the same rule now — no exception any more', () => {
/**
* Q3, as revised in v0.4.2. An Expedite train leaves the Stage it arrives, but at the END of that
* Stage rather than inside the Mainline Phase. It used to be gone before Load/Unload ran, which
* made the coaches on every coach-carrying express (1/2, 5/6, 19) permanently unworkable —
* measured, Train 2 arrived 32 times in 60 games and stood for Load/Unload in none of them.
* Q3, as CORRECTED in v0.4.9. Before this, an Expedite train left the Stage it arrived — at the
* end of it rather than inside the Mainline Phase (v0.4.2's fix for coaches otherwise never
* reaching Load/Unload) — which made it the one exception to "stops for the Stage". That forced
* departure is gone: Expedite no longer changes WHEN a train leaves, only where it may be left
* standing afterwards (`expediteFault`, pinned in `advance.test.ts`). So it stops for the Stage
* exactly like Train 9 above.
*/
const s = game();
assert.equal(trainProfile(3, false)?.rules.expedite, true, 'train 3 should be an Expedite train');
@@ -517,19 +521,9 @@ describe('§8.1 — a train that just arrived from the mainline stops for the St
assert.equal(
s.trays.get(id)!.position.at, 'grid',
'an Expedite train left inside the Mainline Phase, before Load/Unload could reach it',
'an Expedite train departed again in the same Stage it arrived from a mainline card',
);
assert.equal(s.trays.get(id)!.departsThisStage, true, 'it is not flagged to leave at the end of the Stage');
assert.ok(areaOf(s, 0).adOccupancy.includes(id), 'it is not standing on an A/D track');
// Run the end of the Stage directly. Load/Unload waits on the player, and the thing under test
// is the departure pass that follows it — not that phase's own input handling.
s.clock.phase = 'shiftChange';
advance(s);
assert.notEqual(
s.trays.get(id)?.position.at, 'grid',
'an Expedite train should be gone by the end of the Stage it arrived',
);
});
});
@@ -665,6 +659,50 @@ describe('Telegraph, Telephone and Radio dispatch meets', () => {
assert.deepEqual(s.trays.get('mine')!.position, { at: 'divisionPoint', side: 'west' });
});
it('holds against an uncleared facing train even if a same-direction one is checked first', () => {
// Reproduces a playtest report: the Superintendent was asked to rule on a same-direction train
// instead of being automatically held against an opposite-direction one also occupying the
// card. Root cause — `evaluateClearance` returned on whichever occupant it examined first, in
// `node.transits` insertion order, rather than checking every occupant. Only visible once a
// card can hold two trains at once, which the Telegraph/Telephone/Radio exception is exactly
// what creates: a facing train dispatched past another sits on the same card as it.
const s = game();
const ml = s.division.nodes[1];
assert.equal(ml?.kind, 'mainline');
if (ml?.kind === 'mainline') {
ml.card = 'plains';
// SAME direction, entered the transit list FIRST — what the old code asked about.
s.trays.set('sameDir', {
id: 'sameDir', trainNumber: 3, trainIsExtra: false, engineAt: 0,
consist: [], direction: 'east', position: { at: 'mainline', index: 1 }, movesUsed: 0,
});
ml.transits.push({ tray: 'sameDir', stagesRemaining: 2, stagesTotal: 2, direction: 'east' });
// OPPOSITE direction, entered SECOND, no dispatch device on the board — an absolute bar.
s.trays.set('facing', {
id: 'facing', trainNumber: 5, trainIsExtra: false, engineAt: 0,
consist: [], direction: 'west', position: { at: 'mainline', index: 1 }, movesUsed: 0,
});
ml.transits.push({ tray: 'facing', stagesRemaining: 2, stagesTotal: 2, direction: 'west' });
}
s.trays.set('mine', {
id: 'mine', trainNumber: 9, trainIsExtra: false, engineAt: 0,
consist: [], direction: 'east', position: { at: 'divisionPoint', side: 'west' }, movesUsed: 0,
});
s.clock.phase = 'mainline';
s.movedThisPhase = new Set();
const r = advance(s);
assert.equal(
s.trays.get('mine')!.position.at, 'divisionPoint',
'the train entered despite an uncleared opposite-direction occupant on the card',
);
assert.ok(
!r.events.some((e) => e.type === 'clearanceRequested'),
'the Superintendent was asked to rule on the same-direction occupant instead of an automatic hold',
);
});
it('lets a junior train win the meet with a Telegraph', () => {
// Train 9 against Train 3: +4 makes the other count as 7 — still senior. Radio's +12 wins.
const s = game();
+1
View File
@@ -46,6 +46,7 @@ const KNOWN_UNREDUCED = [
'carPassed',
'clearanceRequested',
'dispatchBonusUsed',
'expediteFault',
'phaseBegan',
'stageBegan',
'trainArrived',
+1
View File
@@ -313,6 +313,7 @@ describe('Flying Switch rolls a cut into an industry', () => {
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
+3 -3
View File
@@ -450,7 +450,7 @@ describe('the view shows one seat at a time', () => {
for (let n = 0; n < p; n++) {
area.grid.set(coordKey({ row: area.runningRow - 1, col: n }), {
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
}
s.decks.hands.set(p, source.slice(0, p + 1));
@@ -527,7 +527,7 @@ describe('the view shows one seat at a time', () => {
readyToLeave(s, 1, 'crew-1', 'east');
const withTray = (p: PlayerIndex): number =>
snapshot(s, [], null, null, null, false, p).cells.filter((c) => c.tray != null).length;
snapshot(s, [], null, null, null, false, p).cells.filter((c) => c.trains.length > 0).length;
assert.equal(withTray(1), 1, "the crew is not on its own seat's board");
assert.deepEqual([withTray(0), withTray(2)], [0, 0], "a crew was drawn onto another seat's board");
});
@@ -594,7 +594,7 @@ describe('scoring lands on the right seat', () => {
const sizeBefore = areaAtSeat(s, 2).grid.size;
mine.grid.set(coordKey({ row: mine.runningRow - 1, col: 0 }), {
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
assert.equal(areaAtSeat(s, 2).grid.size, sizeBefore, "one seat's track appeared in another's district");
assert.notEqual(areaAtSeat(s, 1), areaAtSeat(s, 2), 'two seats share one Office Area object');
+126 -4
View File
@@ -10,8 +10,10 @@ import assert from 'node:assert/strict';
import { pump } from '../src/engine/advance.ts';
import type { GameEvent } from '../src/engine/events.ts';
import { areaOf } from '../src/engine/apply.ts';
import { createGame } from '../src/engine/setup.ts';
import type { GameConfig } from '../src/engine/state.ts';
import { coordKey } from '../src/engine/state.ts';
import type { GameConfig, GameState } 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';
@@ -52,13 +54,13 @@ const SAMPLES: GameEvent[] = [
{ type: 'carPassed', player: 0, trayId: 't0' },
{ type: 'clearanceRequested', trainId: 't1', occupiedBy: 't0' },
{ type: 'clearanceGiven', trainId: 't1', allow: false },
{ type: 'passengersBoarded', player: 0, at: { row: 0, col: 0 } },
{ type: 'passengersDetrained', player: 0, at: { row: 0, col: 0 } },
{ type: 'passengersBoarded', player: 0, at: { row: 0, col: 0 }, trayId: 't0', coachIndex: 0 },
{ type: 'passengersDetrained', player: 0, at: { row: 0, col: 0 }, trayId: 't0', coachIndex: 0 },
{ type: 'loadStarted', player: 0, at: { row: 1, col: 0 }, carType: 'hopper' },
{ type: 'loadAdvanced', player: 0, at: { row: 1, col: 0 }, fromBox: 0, toBox: 1 },
{ type: 'unloadCompleted', player: 0, at: { row: 1, col: 0 }, carType: 'hopper' },
{ type: 'loadCompleted', player: 0, at: { row: 1, col: 0 }, carType: 'hopper' },
{ type: 'unloadBegan', player: 0, at: { row: 1, col: 0 }, carType: 'hopper' },
{ type: 'unloadBegan', player: 0, at: { row: 1, col: 0 }, carType: 'hopper', carIndex: 0 },
{ type: 'revenueChanged', player: 0, delta: 1, total: 3, reason: 'freightLoad' },
{ type: 'phaseEnded', player: 0, phase: 'localOps' },
];
@@ -133,6 +135,91 @@ describe('impediments', () => {
});
});
/**
* Gitea#2 — "four porters, two passengers on the platform, and I never get the chance to work them."
*
* The engine was faithful at every step; what was missing was any way to SEE why. A Porter action
* that cannot be taken is simply absent from the menu, and this panel — the one that answers "why is
* nothing moving?" — opened with `f.kind !== 'freight'`, so a platform had never had anything to say
* for itself at all.
*/
describe('a blocked platform says why (Gitea#2)', () => {
/** Raise the Whistle Post to a working Terminal: the tier's printed numbers, applied directly. */
function platform(s: GameState) {
const area = areaOf(s, 0);
area.tier = 'terminal';
const card = area.grid.get(coordKey(area.officeCoord))!;
const f = card.facility!;
f.allows = { outbound: true, inbound: true };
f.porters = 3;
f.capacity = { outbound: 3, inbound: 3 };
return { area, f };
}
/** A tray standing on an A/D track at the Office, carrying whatever it is given. */
function atOffice(s: GameState, consist: { type: 'coach'; loaded: boolean; origin?: number }[]): void {
const area = areaOf(s, 0);
const id = s.freeTrays.pop()!;
s.trays.set(id, {
id, trainNumber: null, trainIsExtra: false, engineAt: 0, consist,
direction: 'east', position: { at: 'grid', seat: 0, coord: area.officeCoord }, movesUsed: 0,
});
area.adOccupancy.push(id);
}
it('reports passengers standing on a platform with no train to take them', () => {
// The whole of the bug's second half: before this, `impediments` returned an EMPTY list here.
const s = createGame({ id: 'g', seed: 5, config, playerNames: ['p'] });
const { f } = platform(s);
f.outboundBox = [{ type: 'coach', loaded: true }];
const found = impediments(s, 0);
const platformRow = found.find((b) => /platform/.test(b.why));
assert.ok(platformRow, `nothing reported for the platform:\n${JSON.stringify(found, null, 2)}`);
assert.match(platformRow.why, /passengers waiting, no train at the platform/);
assert.equal(platformRow.severity, 'waiting');
});
it('names the Office by its tier rather than the word "facility"', () => {
// A Passenger Facility rides on the `office` card, so the freight branch's `geometry.facility`
// is not there to read and every passenger row read `facility 0,0` next to `mineTipple 1,-3`.
const s = createGame({ id: 'g', seed: 5, config, playerNames: ['p'] });
const { f } = platform(s);
f.outboundBox = [{ type: 'coach', loaded: true }];
const row = impediments(s, 0).find((b) => /platform/.test(b.why))!;
assert.match(row.where, /^terminal /, `the Office is unnamed: ${row.where}`);
});
it('explains the coach shortage that made the game look broken', () => {
// The reported state: a train in with passengers to set down, red slots free, four porters —
// and §9.2 needs a white coach out of the Division Yard to swap in. There was none, with eight
// more sitting in the Classification Yard that §2.2 returns only when the Division Yard is BARE.
const s = createGame({ id: 'g', seed: 5, config, playerNames: ['p'] });
const { f } = platform(s);
atOffice(s, [{ type: 'coach', loaded: true, origin: 1 }]);
s.yards.divisionYard = s.yards.divisionYard.filter((c) => !(c.type === 'coach' && !c.loaded));
s.yards.classificationYard = [
{ type: 'coach', loaded: false },
{ type: 'coach', loaded: false },
];
const row = impediments(s, 0).find((b) => /§9\.2/.test(b.why));
assert.ok(row, `the coach shortage was not explained:\n${JSON.stringify(impediments(s, 0), null, 2)}`);
assert.equal(row.severity, 'stuck', 'a train that cannot be emptied is stuck, not merely waiting');
assert.match(row.why, /2 coaches are in the Classification Yard/, `where the coaches are is not said: ${row.why}`);
assert.match(row.why, /Classification returns only when the Division Yard is bare/);
assert.ok(f.inboundBox.length === 0, 'the red slots were free — the shortage is the only cause');
});
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'] });
const { f } = platform(s);
f.outboundBox = [{ type: 'coach', loaded: true }];
atOffice(s, [{ type: 'coach', loaded: false }]);
const found = impediments(s, 0).filter((b) => /platform|§9\.2|Porters/.test(b.why));
assert.deepEqual(found, [], `a working platform reported an impediment:\n${JSON.stringify(found, null, 2)}`);
});
});
describe('replay recording', () => {
const rec = record(1234, 'standard');
@@ -368,6 +455,34 @@ describe('the replay wire format is lossless (regression)', () => {
assert.ok(checked > 100, `only ${checked} frames checked`);
});
it("tolerates an older recording's singular train at the trains slot", () => {
// Before "The Roster Pass" (docs/plans/switching-paths.md), the trains slot held one train
// object or null — `rehydrateCells` has to make sense of that shape too, with no version flag
// anywhere in a packed row to key off.
const cards: unknown[] = [[0, 0, 'office', 'Whistle Post', true, ['ew']]];
const whats = ['a station'];
const facs: unknown[] = [];
const oldTrain = { trayId: 'crew', label: 'crew', cars: [], engineAt: 0, facing: 'e', what: '' };
const [withObject] = rehydrateCells([[0, 0, [], [], -1, oldTrain, 1, [], 0]], cards, whats, facs) as {
trains: unknown[];
}[];
assert.deepEqual(withObject!.trains, [oldTrain], 'a lone train object should wrap into a one-train roster');
const [withNull] = rehydrateCells([[0, 0, [], [], -1, null, 1, [], 0]], cards, whats, facs) as {
trains: unknown[];
}[];
assert.deepEqual(withNull!.trains, [], 'a null train slot should read as no train at all');
const [withArray] = rehydrateCells(
[[0, 0, [], [], -1, [oldTrain, oldTrain], 1, [], 0]],
cards,
whats,
facs,
) as { trains: unknown[] }[];
assert.equal(withArray!.trains.length, 2, 'an array should ride through as-is');
});
it('writes each distinct card and description once, not once per frame', () => {
const rec = record(880009, 'standard', 4000);
const packed = compress(rec.frames);
@@ -418,6 +533,13 @@ describe('the replay behaves like the game it is replaying', () => {
assert.ok(kinds.has('couple'), 'coupling a cut never made a sound');
assert.ok(kinds.has('drop'), 'setting cars out never made a sound');
assert.ok(kinds.has('schedule'), 'the 1D12 that sets a train\'s departure Stage landed silently');
assert.ok(kinds.has('arrive'), 'a train pulling into an Office never made a sound');
assert.ok(kinds.has('depart'), 'a train highballing out of an Office never made a sound');
// Collisions are rare — measured 2 in 40 games — so this is the one cue this pool is not
// guaranteed to contain on every stride; it happens to (seeds 96028 and 159380) at the current
// stride and seed count. If this starts failing after either changes, widen the pool rather than
// deleting the assertion — §10 is the one event a player most needs to hear.
assert.ok(kinds.has('crash'), 'a collision never made a sound');
// One CLOCK cue per Stage boundary, the bell replacing the whistle at a Day — the same
// accounting the live game is held to. The switching cues are counted separately: they follow
+56 -12
View File
@@ -22,6 +22,7 @@ import {
deckComposition,
isFreightHouse,
lengthProfile,
MAINLINE_DECK,
mainlineCardCount,
nextOfficeTier,
officeProfile,
@@ -181,23 +182,30 @@ describe('card catalogue (component 1)', () => {
}
});
it('identifies the both-direction industries the card reference names', () => {
it('names the Freight House and nothing else as the two-way industry', () => {
/**
* `card-reference.md`: "'Freight House' is not a card. It is the collective term for a freight
* facility that loads *and* unloads — the Grocer's Warehouse and the Oil Refinery." The table
* agrees: both are "Both", and only the Power Plant is inbound-only.
* §9.3 — "Passenger Facilities and Freight Houses permit cars to move each direction". ONE card
* answers to that.
*
* The engine had the Refinery as outbound-only and the Grocer's as inbound-only, so §9.3's
* "Passenger Facilities and Freight Houses permit cars to move each direction" named neither of
* them — and every Modifier grant on the missing direction was silently dropped, which is how
* "grocer's warehouse didn't get extra outbound slot for truck dock" was reported.
* This briefly asserted three. `card-reference.md` reads "'Freight House' is not a card. It is
* the collective term for a freight facility that loads *and* unloads — the Grocer's Warehouse
* and the Oil Refinery", and on that premise the Refinery and the Grocer's were both made
* `flow: 'both'`. The premise is dead: `glossary.md` and `rules-v0.2.md` corrected the Freight
* House to a card of its own, dealt like any other industry, so §9.3 names it and the table's
* "Both" column loses its only argument.
*
* `freightHouse` is still in this list because the engine deals it as a CARD, which the rules say
* it is not. That is a deck-composition question, recorded in TODO.md, not something to quietly
* delete six cards over.
* Reported from playtesting v0.4.9d and confirmed by Jesse: the Refinery only ships tanks out,
* the Grocer's Warehouse only receives. `StationMaster-Home-Deck-v0.4.5.md` prints both that way,
* and so does the modifier set — all three Refinery modifiers grant outbound.
*/
const houses = FREIGHT_PROFILES.filter(isFreightHouse).map((f) => f.kind);
assert.deepEqual(houses.sort(), ['freightHouse', 'grocersWarehouse', 'refinery']);
assert.deepEqual(houses.sort(), ['freightHouse']);
const refinery = FREIGHT_PROFILES.find((f) => f.kind === 'refinery')!;
assert.equal(refinery.flow, 'outbound');
assert.deepEqual([refinery.baseOut, refinery.baseIn], [1, 0]);
const grocers = FREIGHT_PROFILES.find((f) => f.kind === 'grocersWarehouse')!;
assert.equal(grocers.flow, 'inbound');
assert.deepEqual([grocers.baseOut, grocers.baseIn], [0, 1]);
});
it('starts every industry at one car out and one loader', () => {
@@ -400,6 +408,42 @@ describe('game setup (component 2)', () => {
}
});
it('deals the Mainline cards from the printed deck, without replacement', () => {
/**
* `buildDivision` drew uniformly from the nine card TYPES with replacement, so a Division could
* be dealt two Interchanges (or two Tunnels), and Plains — printed twice in the deck — carried
* the same weight as cards printed once. That became a rules question rather than a flavour one
* when an Extra gained the right to start "at the Interchange if one is on the board" (§7): the
* board has to hold at most one for that to mean anything.
*
* Swept over many seeds because a single deal cannot tell a deck from a die.
*/
const seen = new Map<string, number>();
for (let seed = 0; seed < 400; seed++) {
for (const players of [1, 2, 3, 4]) {
const g = createGame({
id: 'deck', seed,
config: players === 1 ? solitaireConfig : { ...solitaireConfig, mode: 'competitive' },
playerNames: Array.from({ length: players }, (_, i) => `P${i}`),
});
const cards = g.division.nodes.flatMap((n) => (n.kind === 'mainline' ? [n.card] : []));
assert.equal(cards.length, mainlineCardCount(players));
const counts = new Map<string, number>();
for (const c of cards) {
const n = (counts.get(c) ?? 0) + 1;
counts.set(c, n);
seen.set(c, (seen.get(c) ?? 0) + 1);
// Plains is the one card printed twice; nothing else may be dealt twice at all.
assert.ok(n <= (c === 'plains' ? 2 : 1), `${c} dealt ${n} times at seed ${seed}`);
}
}
}
// Every card in the deck reachable, so the deal is not quietly missing one.
for (const kind of new Set(MAINLINE_DECK)) {
assert.ok((seen.get(kind) ?? 0) > 0, `${kind} was never dealt in 400 seeds`);
}
});
it('opens with the whole railroad as one Subdivision', () => {
// §8 — every Office is a Whistle Post, which is not a Control Point.
const g = newSolitaireGame();
+28 -16
View File
@@ -345,8 +345,8 @@ describe('end-of-game statistics', () => {
* BOT no longer gets a crew next to an industry: it builds shallow districts and places 2.2
* facilities a game, down from 3.8 when industries could sit on the main.
*
* That is the bot's district-building weakness, which is the top item in TODO.md, not a rule
* that has become unreachable. Exempted by name so the other forty-odd event checks stay live,
* That is the bot's district-building weakness, tracked in TODO.md under Bot Performance, not a
* rule that has become unreachable. Exempted by name so the other forty-odd event checks stay live,
* and so removing this line is what proves the bot has been fixed.
*/
const KNOWN_UNREACHABLE_BY_THE_BOT = ['event flyingSwitch'];
@@ -386,13 +386,22 @@ describe('switching accomplishes something (regression)', () => {
// no switching at all (§9.2 works coaches straight off the A/D track), so an entire Local
// Operations action was wasted.
/**
* ACROSS SEEDS, because one game cannot tell a fixed bug from a lucky deal. Measured over these
* 16: thirteen show no oscillation at all and three reach a run of five, so the shuttling is a
* minority behaviour rather than the every-game waste this test was written to catch. The bar is
* therefore a RATE — most games clean — plus a ceiling on how bad the worst may get. The residual
* is recorded in TODO.md with the rest of the bot work.
* ACROSS SEEDS, because one game cannot tell a fixed bug from a lucky deal — and the sample has
* to be big enough that it cannot tell a lucky DEAL from a fixed bug either.
*
* It was 16 hand-picked seeds against a bar of 70% clean, on a measurement of 13/16. Dealing the
* Mainline cards from the printed deck instead of rolling them (`buildDivision`) re-dealt every
* one of those boards and the same 16 came back 11/16, which read as a regression and was not
* one: re-measured over 80 seeds the rate is **70.0% clean, worst run 5** — the identical
* behaviour, and 13/16 was the lucky draw. A bar sitting exactly on the true rate fails half the
* time it is moved.
*
* So: a wider sweep, and a bar well below the measured rate. What the test is really guarding is
* the every-game waste it was written for, which shows up as a rate near ZERO, not as a few
* points of drift. The ceiling on the worst run is the sharp half of the assertion and is
* unchanged. The residual is recorded in TODO.md with the rest of the bot work.
*/
const seeds = [1234, 5, 77, 430, 202, 999, 21, 555, 4321, 31337, 60606, 7777, 123456, 888, 31, 42];
const seeds = Array.from({ length: 48 }, (_, i) => i + 1);
let clean = 0;
let worstAnywhere = 0;
for (const seed of seeds) {
@@ -424,7 +433,7 @@ describe('switching accomplishes something (regression)', () => {
}
assert.ok(
clean >= seeds.length * 0.7,
clean >= seeds.length * 0.55,
`only ${clean}/${seeds.length} games were free of aimless shuttling`,
);
assert.ok(worstAnywhere <= 5, `a crew oscillated ${worstAnywhere + 1} times without doing any work`);
@@ -474,8 +483,10 @@ describe('switching accomplishes something (regression)', () => {
* grew faster, which is traffic rather than aimlessness, and there are two new sources of it:
* Extras now start at the Division Point their NUMBER sends them to, so westbound Extras exist
* at all (measured 32 west / 29 east across 60 deals, against every single one launching
* eastbound from the West Division Point before); and the Grocer's Warehouse ships as well as
* receives, so there is more switching worth doing.
* eastbound from the West Division Point before); and the Grocer's Warehouse briefly shipped as
* well as received, which was more switching worth doing. That second source is gone again in
* v0.4.9e — the Grocer's is inbound-only, as it always was on the sheet — and the ratio still
* clears the floor, so the figure is left where it is rather than re-tuned to one release.
*
* A crew that shuttles for its own sake would show this ratio climbing while `work` stood still.
* Logged in TODO.md with the rest of the bot drift rather than quietly absorbed.
@@ -1070,12 +1081,13 @@ describe('the freight figures count both halves (regression)', () => {
// that on: an unload needs an inbound industry built, reachable, and a loaded car spotted at it,
// and whether the bot manages all three on a given deal is luck, not the thing under test.
/**
* FORTY DEALS, up from twelve, and the reason is a rules correction rather than flakiness.
* FORTY DEALS, up from twelve, and the reason was a rules correction rather than flakiness.
*
* The Grocer's Warehouse is a BOTH-direction facility now — `card-reference.md` always said so —
* where the engine had it inbound-only. So the bot can ship from it as well as receive, and it
* often does: deals producing at least one completed unload went from 12 in 40 to 6 in 40, while
* unloads themselves are unharmed (30 completed across the 40 measured after the change).
* The Grocer's Warehouse was briefly a both-direction facility, so the bot shipped from it as
* well as receiving and deals producing at least one completed unload fell from 12 in 40 to 6 in
* 40. v0.4.9e put it back to inbound-only, which is what the sheet always printed. The wider
* sample is kept: the precondition it protects — that some deal in the batch actually completes
* an unload — is worth having whichever way the rule goes.
*
* The subject here is the INSTRUMENT — does `freightUnload` count Revenue earned rather than
* unloads started — and `unloads > 0` is only the precondition that makes the comparison mean
+151 -6
View File
@@ -18,6 +18,8 @@ import type {
import { coordKey, isOperationalRail, turnOf } from '../src/engine/state.ts';
import { createGame } from '../src/engine/setup.ts';
import { applyIntent, areaOf } from '../src/engine/apply.ts';
import { legalActions } from '../src/engine/legal.ts';
import type { Intent } from '../src/engine/intents.ts';
import type { MoveContext, Occupancy, Port } from '../src/engine/track.ts';
import {
allReachable,
@@ -46,6 +48,7 @@ const straight = (standing: RollingStock[] = []): TrackCard => ({
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true,
standing,
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -60,6 +63,7 @@ const curve = (arc: TrackArc, standing: RollingStock[] = []): TrackCard => ({
geometry: { kind: 'track', geometry: 'curved', arc },
baseOperationalRail: true,
standing,
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -71,6 +75,7 @@ const turnout = (o?: TurnoutOrientation): TrackCard => ({
: { kind: 'track', geometry: 'turnout' },
baseOperationalRail: false, // no wheel icon — a train may pass through but not stop (§A.1)
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -80,6 +85,7 @@ const officeCard = (): TrackCard => ({
geometry: { kind: 'office' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -89,6 +95,7 @@ const lockedFacility = (): TrackCard => ({
geometry: { kind: 'facility', facility: 'mineTipple' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
// A load sitting on MEN|AT|WORK locks the industry track down (§9.3).
facility: {
kind: 'freight',
@@ -112,7 +119,7 @@ const car = (): RollingStock => ({ type: 'boxcar', loaded: false });
function straightCard(): TrackCard {
return {
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
};
}
@@ -208,6 +215,7 @@ describe('ports and geometry', () => {
geometry: { kind: 'track', geometry: 'curved', hand: 'left' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -627,7 +635,7 @@ describe('placement and drop-off', () => {
describe('curves are arcs, and arcs make sidings possible', () => {
const arcCard = (arc: 'ne' | 'nw' | 'se' | 'sw', geometry: 'curved' | 'sharpCurved' = 'curved'): TrackCard => ({
geometry: { kind: 'track', geometry, arc },
baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
it('joins exactly two adjacent edges, with no through track', () => {
@@ -645,7 +653,7 @@ describe('curves are arcs, and arcs make sidings possible', () => {
c.map((p) => [...p].sort().join('')).sort().join(' ');
const turnout: TrackCard = {
geometry: { kind: 'track', geometry: 'turnout', turnout: { stem: 'w', through: 'e', diverge: 's' } },
baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
};
for (const arc of ['ne', 'nw', 'se', 'sw'] as const) {
assert.notEqual(norm(connectionsFor(arcCard(arc))), norm(connectionsFor(turnout)),
@@ -688,11 +696,11 @@ describe('curves are arcs, and arcs make sidings possible', () => {
const ew = (): TrackCard => straightCard();
const grid: Record<string, TrackCard> = {
'0,-2': ew(),
'0,-1': { geometry: { kind: 'track', geometry: 'turnout', turnout: { stem: 'w', through: 'e', diverge: 's' }, hand: 'right' }, baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [] },
'0,-1': { geometry: { kind: 'track', geometry: 'turnout', turnout: { stem: 'w', through: 'e', diverge: 's' }, hand: 'right' }, baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [] },
'-1,-1': arcCard('ne'),
'-1,0': ew(),
'-1,1': arcCard('nw'),
'0,1': { geometry: { kind: 'track', geometry: 'turnout', turnout: { stem: 'e', through: 'w', diverge: 's' }, hand: 'left' }, baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [] },
'0,1': { geometry: { kind: 'track', geometry: 'turnout', turnout: { stem: 'e', through: 'w', diverge: 's' }, hand: 'left' }, baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [] },
'0,0': ew(),
};
const area = areaFrom(grid, { row: 0, col: 0 });
@@ -776,6 +784,7 @@ describe('Operational Rail — where a train may stop and leave cars (Appendix A
geometry: { kind: 'facility', facility: 'mineTipple' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: {
kind: 'freight', subtype: 'mineTipple',
allows: { outbound: true, inbound: false },
@@ -917,7 +926,7 @@ describe('a turnout may be laid to face another, making a crossover', () => {
/** A turnout stated the way the cards read: who may come in, and where they may go. */
const facing = (stem: Port, through: Port, diverge: Port, hand: 'left' | 'right'): TrackCard => ({
geometry: { kind: 'track', geometry: 'turnout', turnout: { stem, through, diverge }, hand },
baseOperationalRail: false, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: false, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
it('joins a south-diverging turnout to the north-diverging one beneath it', () => {
@@ -1025,6 +1034,7 @@ describe('why a square is NOT offered (the same walk, keeping its rejections)',
geometry: { kind: 'facility', facility: 'mineTipple' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: {
kind: 'freight', subtype: 'mineTipple',
allows: { outbound: true, inbound: false },
@@ -1110,3 +1120,138 @@ describe('why a square is NOT offered (the same walk, keeping its rejections)',
}
});
});
// ---------------------------------------------------------------------------
// docs/plans/switching-paths.md — two routes to the same square
// ---------------------------------------------------------------------------
describe('two routes to one square', () => {
const limitsCard = (): TrackCard => ({
geometry: { kind: 'limits' },
baseOperationalRail: true,
standing: [],
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
});
/**
* A passing loop: a turnout diverges off the Running Track, curves down to an industry, and
* curves back up to rejoin the main two columns west. Both routes from (0,4) to (0,0) are legal
* under §2.4 (neither ever leaves a card by the port it entered); they differ in what they
* couple. This is the fixture in the plan's §1, verified identical on v0.4.7 and v0.4.8.
*/
function loopArea(midCard: (col: number) => TrackCard = () => straight()): OfficeArea {
return areaFrom(
{
[coordKey(at(0, 0))]: straight(),
[coordKey(at(0, 1))]: turnout({ stem: 'w', through: 'e', diverge: 's' }),
[coordKey(at(0, 2))]: midCard(2),
[coordKey(at(0, 3))]: turnout({ stem: 'e', through: 'w', diverge: 's' }),
[coordKey(at(0, 4))]: limitsCard(),
[coordKey(at(-1, 1))]: curve('ne'),
[coordKey(at(-1, 2))]: midCard(-1),
[coordKey(at(-1, 3))]: curve('nw'),
},
at(9, 9), // office coord, deliberately away from the fixture
);
}
const tanker: RollingStock = { type: 'tank', loaded: false };
it('offers both routes, and only one couples the tanker on the spur', () => {
const area = loopArea((col) => (col === -1 ? straight([tanker]) : straight()));
const dests = reachableDestinations(ctxFor(area), at(0, 4), 'w');
const atZero = dests.filter((d) => d.coord.row === 0 && d.coord.col === 0);
assert.equal(atZero.length, 2, `expected two distinct routes to (0,0), got ${atZero.length}`);
const withTanker = atZero.filter((d) => d.couples.some((c) => c.type === 'tank'));
const without = atZero.filter((d) => d.couples.length === 0);
assert.equal(withTanker.length, 1, 'exactly one route should couple the tanker');
assert.equal(without.length, 1, 'exactly one route should couple nothing');
});
it('offers two routes coupling the SAME car type off DIFFERENT cards, and neither is dropped', () => {
// The dedupe key must include the origin card, not just the car type (plan §3) — two boxcars,
// one on the bypass and one on the main, must not collapse into one destination.
const area = loopArea(() => straight([{ type: 'boxcar', loaded: false }]));
const dests = reachableDestinations(ctxFor(area), at(0, 4), 'w');
const atZero = dests.filter((d) => d.coord.row === 0 && d.coord.col === 0);
assert.equal(atZero.length, 2, `expected two distinct routes to (0,0), got ${atZero.length}`);
for (const d of atZero) {
assert.deepEqual(d.couples.map((c) => c.type), ['boxcar'], 'each route should couple its own boxcar');
}
});
it('a `via`-qualified switch.move resolves to the route it names', () => {
function freshGame(): GameState {
const s = gameWith(loopArea((col) => (col === -1 ? straight([tanker]) : straight())));
s.trays.set('crew', {
id: 'crew', trainNumber: null, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'west', facing: 'w', position: { at: 'grid', seat: 0, coord: at(0, 4) }, movesUsed: 0,
});
s.clock.phase = 'localOps';
s.clock.currentActor = 0;
turnOf(s, 0).option = 'switch';
turnOf(s, 0).movesRemaining = 6;
return s;
}
const probe = freshGame();
const options = legalActions(probe, 0).filter(
(i): i is Extract<Intent, { type: 'switch.move' }> =>
i.type === 'switch.move' && i.to.row === 0 && i.to.col === 0,
);
assert.equal(options.length, 2, 'expected two distinct switch.move intents to (0,0)');
assert.ok(options.every((i) => i.via !== undefined), 'an ambiguous route must carry a distinguishing via');
const vias = new Set(options.map((i) => `${i.via!.row},${i.via!.col}`));
assert.equal(vias.size, 2, 'the two routes must carry DIFFERENT via');
const outcomes = options.map((intent) => {
const s = freshGame();
const r = applyIntent(s, 0, intent);
assert.ok(r.ok, 'a via-qualified move to a square the engine offered must be legal');
return s.trays.get('crew')!.consist.map((c) => c.type);
});
assert.ok(outcomes.some((c) => c.includes('tank')), 'one via should have coupled the tanker');
assert.ok(outcomes.some((c) => c.length === 0), 'the other via should have coupled nothing');
// `via` absent still resolves — the first route enumerated, exactly as before this feature.
const s = freshGame();
const r = applyIntent(s, 0, { type: 'switch.move', trayId: 'crew', to: at(0, 0), reverse: false });
assert.ok(r.ok, 'a plain move with no via must still resolve to SOME legal route');
});
it('a dense district terminates and stays bounded, preferring the routes BFS finds first', () => {
// Chained passing loops: each one independently offers "through" or "detour", so N of them
// offer 2^N routes to the far end with no global memo to stop it — exactly the exponential case
// the cap exists for (plan §3). 15 segments is 32,768 routes; the cap is 4,000 frontier nodes.
const segments = 15;
const start = 3 * segments;
const grid: Record<string, TrackCard> = { [coordKey(at(0, start + 1))]: limitsCard() };
for (let k = 0; k < segments; k++) {
const divergeCol = start - 3 * k;
const midCol = divergeCol - 1;
const mergeCol = divergeCol - 2;
grid[coordKey(at(0, divergeCol))] = turnout({ stem: 'e', through: 'w', diverge: 's' });
grid[coordKey(at(0, midCol))] = straight();
grid[coordKey(at(0, mergeCol))] = turnout({ stem: 'w', through: 'e', diverge: 's' });
grid[coordKey(at(-1, divergeCol))] = curve('nw');
grid[coordKey(at(-1, midCol))] = straight();
grid[coordKey(at(-1, mergeCol))] = curve('ne');
}
grid[coordKey(at(0, 0))] = straight();
const area = areaFrom(grid, at(9, 9));
const startedAt = Date.now();
const dests = reachableDestinations(ctxFor(area), at(0, start + 1), 'w');
const elapsed = Date.now() - startedAt;
assert.ok(elapsed < 5000, `exploreMoves took ${elapsed}ms — the cap should keep this fast`);
assert.ok(dests.length > 0, 'the cap must not eliminate every route');
assert.ok(
dests.length < 2 ** segments,
`${dests.length} destinations found — the cap should have cut off full 2^${segments} enumeration`,
);
});
});
+33 -3
View File
@@ -30,6 +30,7 @@ const straight = (standing: RollingStock[] = []): TrackCard => ({
geometry: { kind: 'track', geometry: 'straight' },
baseOperationalRail: true,
standing,
standingWest: 0,
facility: null,
modifiers: [],
enhancements: [],
@@ -70,18 +71,30 @@ const west = (s: GameState, n = 2): GridCoord => {
};
const boxcar = (loaded = false): RollingStock => ({ type: 'boxcar', loaded });
/** As `ROLLING_STOCK_SUPPLY` mints them: there is no empty caboose in the game. */
const caboose = (): RollingStock => ({ type: 'caboose', loaded: true });
const coach = (loaded = false): RollingStock => ({ type: 'coach', loaded });
// ---------------------------------------------------------------------------
describe('§7 — no switching', () => {
it('refuses every switching act to a train whose card forbids it', () => {
it('still allows a plain move — "no switching" means no adding or dropping cars', () => {
// Six cards print it: both expresses, the Light Engine, Campaign, Circus and Military trains.
// Moving, setting out and sorting are all switching, so all three are refused.
// A train held at the Office may still need to clear onto Secondary Track ahead of other
// traffic, so a move that couples nothing is legal.
const s = game();
switching(s, 1, false, [boxcar()]);
assert.equal(check(s, 0, { type: 'switch.move', trayId: 't', to: west(s), reverse: false }), null);
});
assert.equal(check(s, 0, { type: 'switch.move', trayId: 't', to: west(s), reverse: false }), 'NO_SWITCHING');
it('refuses a move that would couple a car, and refuses dropping and sorting outright', () => {
const s = game();
switching(s, 1, false, [boxcar()], [boxcar()]);
assert.equal(
check(s, 0, { type: 'switch.move', trayId: 't', to: west(s), reverse: false }),
'PICKUP_NOT_ALLOWED',
);
assert.equal(check(s, 0, { type: 'switch.dropCars', trayId: 't', count: 1 }), 'NO_SWITCHING');
assert.equal(check(s, 0, { type: 'switch.sortConsist', trayId: 't', order: [0] }), 'NO_SWITCHING');
});
@@ -127,6 +140,23 @@ describe('§7 — what a train may couple', () => {
'EMPTIES_ONLY',
);
});
it('X22 Pee-Dee may still couple a caboose, which is not a load (Gitea#8)', () => {
// Every caboose in the game is minted `loaded: true` because the supply table's loaded/empty
// split doubles as a piece count. Taken literally that left the per-diem train unable to pick
// up ANY caboose, its own included: set it out at the end of a sweep and it was stranded there.
const s = game();
switching(s, 22, true, [], [caboose()]);
assert.equal(check(s, 0, { type: 'switch.move', trayId: 't', to: west(s), reverse: false }), null);
// The restriction itself is untouched — a loaded car alongside the caboose still refuses.
const withLoad = game();
switching(withLoad, 22, true, [], [caboose(), boxcar(true)]);
assert.equal(
check(withLoad, 0, { type: 'switch.move', trayId: 't', to: west(withLoad), reverse: false }),
'EMPTIES_ONLY',
);
});
});
describe('§7 — one freight car per location (trains 3/4)', () => {
+500 -29
View File
@@ -22,8 +22,10 @@ import { cardDescription, cardName, describeIntent, variantLabel } from '../src/
import { variantsFor } from '../src/engine/track.ts';
import { divisionSvg, officeSvg } from '../src/sim/board-svg.ts';
import { ENHANCEMENT_RULES } from '../src/engine/content.ts';
import { facilitiesHtml, timetableHtml } from '../src/web/panels.ts';
import { dayEndHtml, facilitiesHtml, timetableHtml } from '../src/web/panels.ts';
import { record, renderHtml } from '../src/sim/replay.ts';
import type { Frame } from '../src/sim/view.ts';
import type { GameLength } from '../src/engine/content.ts';
import { snapshot } from '../src/sim/view.ts';
import { createGame as createEngineGame } from '../src/engine/setup.ts';
import {
@@ -598,6 +600,54 @@ describe('the board shows freight work happening', () => {
assert.ok(y > 48, `the caption at y=${y} prints over the rail`);
});
it('draws the Limits as the edge of the buildable district, at every row', () => {
/**
* Track may not be laid outside the Limits at ANY row now (§2.1), and two signs sitting on the
* Running Track could not say that: a player looking at open ground beyond a sign had no way to
* know nothing of his would ever go there until the square failed to light up.
*
* Just OUTSIDE the sign's own column, because the sign stands ON the boundary — a siding may run
* under it — so a line drawn inside the sign would teach the opposite of the rule.
*/
const game = newGame(555);
const area = game.state.officeAreas.get(0)!;
const f = view(game);
assert.deepEqual(
f.limits,
{ west: area.limitsWest.col, east: area.limitsEast.col },
'the Frame does not carry the district edges a remote client cannot look up',
);
const svg = officeSvg(f.cells, f.runningRow, [], [], f.limits);
const xs = [...svg.matchAll(/class="bs-limitline" x1="(-?[\d.]+)"/g)].map((m) => Number(m[1]));
assert.equal(xs.length, 2, 'the district was drawn without both of its edges');
// The sign cards themselves must fall INSIDE the two lines.
const signX = [...svg.matchAll(/data-cell="(-?\d+),(-?\d+)"[^>]*transform="translate\((-?[\d.]+)/g)]
.filter((m) => Number(m[2]) === area.limitsWest.col || Number(m[2]) === area.limitsEast.col)
.map((m) => Number(m[3]));
assert.ok(signX.length > 0, 'no Limits sign was drawn to check the boundary against');
for (const x of signX) {
assert.ok(
x >= Math.min(...xs) && x <= Math.max(...xs),
`a Limits sign at x=${x} sits outside its own boundary (${xs.join(', ')})`,
);
}
assert.match(svg, /bs-limitlab/, 'the boundary is drawn but never named');
// AND ON THE CANVAS. The west sign is the leftmost card, so a line drawn outside its column sits
// at a negative x — off a viewBox that starts at 0, which is a boundary nobody can see.
const vb = /viewBox="(-?[\d.]+) (-?[\d.]+) ([\d.]+) ([\d.]+)"/.exec(svg);
assert.ok(vb, 'the board produced no viewBox');
const x0 = Number(vb![1]);
for (const x of xs) {
assert.ok(
x >= x0 && x <= x0 + Number(vb![3]),
`the boundary at x=${x} is drawn outside the canvas (${x0} to ${x0 + Number(vb![3])})`,
);
}
});
it('says on the card which way an industry runs, and how many workers it has', () => {
/**
* TWO REPORTS, ONE CARD.
@@ -708,8 +758,8 @@ describe('the board draws the printed card (docs/tracks.png)', () => {
/** One card, alone, so the measurements are in card coordinates. */
const draw = (links: string[]): { x1: number; y1: number; x2: number; y2: number }[] => {
const cell = {
row: 0, col: 0, kind: 'trk', label: 'x', running: true, enhancements: [],
tray: null, cars: [], facility: null, links, what: '',
row: 0, col: 0, kind: 'trk', label: 'x', running: true, enhancements: [], enhancementsWhat: [],
trains: [], adTracks: null, cars: [], standingWest: 0, facility: null, links, what: '',
};
const svg = officeSvg([cell] as never, 0);
return [...svg.matchAll(/<line class="bs-rail" x1="([-\d.]+)" y1="([-\d.]+)" x2="([-\d.]+)" y2="([-\d.]+)"\/>/g)]
@@ -793,7 +843,7 @@ describe('board highlighting', () => {
}
assert.equal(typeof sp.coord.row, 'number', `${it.subject} has a spot with no coordinate`);
assert.equal(typeof sp.coord.col, 'number', `${it.subject} has a spot with no coordinate`);
assert.ok(sp.label.includes(`(${sp.coord.row}, ${sp.coord.col})`), 'label and coord disagree');
assert.ok(sp.label.includes(`(${sp.coord.col}, ${sp.coord.row})`), 'label and coord disagree');
}
}
});
@@ -883,7 +933,7 @@ describe('the page explains itself', () => {
const area = game.state.officeAreas.get(0)!;
area.grid.set('-1,0', {
geometry: { kind: 'track', geometry: 'turnout', turnout: { stem: 'e', through: 'w', diverge: 's' } },
baseOperationalRail: true, standing: [], facility: null, modifiers: [], enhancements: [],
baseOperationalRail: true, standing: [], standingWest: 0, facility: null, modifiers: [], enhancements: [],
});
const cell = view(game).cells.find((c) => c.row === -1 && c.col === 0)!;
// Said the way a player would ask it: if my train comes in from over there, where can it go?
@@ -1314,7 +1364,7 @@ describe('the static build', () => {
}
});
it('renders clickable highlights on the board when a card is picked', async () => {
it('renders clickable highlights on the board, and points at the square an action names', async () => {
// The real check: load the EMITTED bundle with a DOM stub, click a card, and confirm the board
// came back with highlighted squares wired to handlers. Asserting the data has coordinates says
// nothing about whether the page draws them.
@@ -1366,7 +1416,12 @@ describe('the static build', () => {
const classes = new Set<string>();
found.set(key, {
onclick: null,
classList: { add: (c: string) => void classes.add(c), has: (c: string) => classes.has(c) },
classList: {
add: (c: string) => void classes.add(c),
// Pointing at a square is a HOVER: it has to come off again when the cursor leaves.
remove: (c: string) => void classes.delete(c),
has: (c: string) => classes.has(c),
},
classes,
});
}
@@ -1493,6 +1548,37 @@ describe('the static build', () => {
const lit = (grid['highlighted'] as () => unknown[])();
const ghosts = /data-ghost="/.test(html);
assert.ok(lit.length > 0 || ghosts, 'picking a card highlighted nothing on the board');
/**
* POINTING AT THE SQUARE A BUTTON MEANS — wired on the emitted bundle, not asserted off the menu.
*
* The menu carrying a coordinate proves nothing about whether the page draws it, which is the
* same reason the highlight check above loads the real bundle. Reported by Jesse: the action list
* is a column of near-identical sentences separated by "(1,3)" against "(-1,3)", and picking the
* wrong one is a click to undo in solitaire and unrecoverable in a multiplayer game.
*/
const withSquare = (
(actions['querySelectorAll'] as (s: string) => Record<string, unknown>[])
.call(actions, 'button.act')
.filter((n) => (n['dataset'] as Record<string, string>)['square'])
);
assert.ok(withSquare.length > 0, 'no action button carries the square it acts on');
const btn = withSquare[0]!;
const key = (btn['dataset'] as Record<string, string>)['square']!;
assert.match(key, /^-?\d+,-?\d+$/, `"${key}" is not a grid coordinate`);
(btn['onmouseenter'] as (() => void) | null)?.();
const pointed = (grid['highlighted'] as () => Record<string, unknown>[])().filter((g) =>
(g['classes'] as Set<string>).has('bs-point'),
);
assert.equal(pointed.length, 1, `hovering the action for (${key}) marked ${pointed.length} squares`);
(btn['onmouseleave'] as (() => void) | null)?.();
assert.equal(
(grid['highlighted'] as () => Record<string, unknown>[])().filter((g) =>
(g['classes'] as Set<string>).has('bs-point'),
).length,
0,
'the square stayed lit after the cursor left the button',
);
});
it('busts the cache on every module, so a deploy cannot half-load', () => {
@@ -1703,7 +1789,19 @@ describe('the static build', () => {
// click-through happens to visit.
const reachable = (menu: ReturnType<typeof actionMenu>): Set<number> => {
const out = new Set<number>();
for (const g of menu.direct) for (const a of g.actions) out.add(a.index);
/**
* THE SAME EXCLUSION `renderActions()` (main.ts) APPLIES, not the raw menu.
*
* `menu.direct` alone is what the ENGINE offers; `renderActions()` then drops any group whose
* title matches the one `menu.makeUp` already covers, so a group counted here but filtered
* there is exactly the gap that stranded a pending Extra with `menu.makeUp` null and its own
* "Making up Extra X22…" title caught by the OLD broader regex this once was. Mirroring the
* real filter is what makes this test the one that would have caught that.
*/
const onScreen = menu.direct.filter(
(g) => !/^(Play|Discard) a card from my hand$/.test(g.title) && g.title !== menu.makeUp?.title,
);
for (const g of onScreen) for (const a of g.actions) out.add(a.index);
for (const g of menu.placeable) for (const it of g.items) for (const sp of it.spots) out.add(sp.index);
for (const h of menu.hand) {
if (h.playNow !== null) out.add(h.playNow);
@@ -1733,6 +1831,37 @@ describe('the static build', () => {
}
});
it('offers "where does this Extra start" on screen, not just in the menu', () => {
// REPORTED: the game "hung" mid-Freight-House-work with nothing to click. `newTrain.startExtra`
// was legal and present in `menu.direct` — the engine was never stuck — but its group is titled
// by `trainCardTitle`, which begins "Making up Extra X22…" exactly like the yard-chip panel's
// OWN group. `renderActions()` used to drop every group titled that way, on the assumption only
// the yard-chip panel used the prefix; with no tray yet being filled (`menu.makeUp` is null,
// since the Extra has not chosen where it starts yet), that group was the only thing offered and
// it vanished from the page — a legal decision with zero buttons.
const game = newGame(430);
game.state.pendingExtras.push(22); // Extra X22 "Pee-Dee" — one caboose, per-diem.
game.state.clock.phase = 'newTrain';
game.state.clock.currentActor = 0;
assert.equal(currentActor(game), 0, 'a decision should be waiting');
const menu = actionMenu(game);
assert.equal(menu.makeUp, null, 'no tray is being filled — the Extra has not started yet');
const extraGroup = menu.direct.find((g) => g.actions.some((a) => menu.options[a.index]?.type === 'newTrain.startExtra'));
assert.ok(extraGroup, 'newTrain.startExtra should appear in some menu.direct group');
assert.match(extraGroup!.title, /^Making up /, 'this is exactly the title shape that used to collide');
// The actual filter `renderActions()` applies (main.ts) — reproduced here for the reason given
// on `reachable()` above: there is no DOM harness in this suite to call the real renderer.
const onScreen = menu.direct.filter(
(g) => !/^(Play|Discard) a card from my hand$/.test(g.title) && g.title !== menu.makeUp?.title,
);
assert.ok(
onScreen.includes(extraGroup!),
'the Extra\'s "choose where it starts" group was filtered out along with the yard-chip panel',
);
});
it('renders every part of the menu it is given', () => {
// THE CHECK THAT WOULD HAVE CAUGHT THE SOFTLOCK ABOVE. The option was in the menu all along —
// `makeUp.pass` was computed correctly and simply never rendered, so the invariant on the menu
@@ -1876,10 +2005,11 @@ describe('the static build', () => {
} as never);
const cell = view(game).cells.find((c) => c.row === area.runningRow && c.col === 0)!;
assert.ok(cell.train, 'the card carries no train');
assert.deepEqual(cell.train!.cars, ['loaded tank', 'loaded boxcar', 'caboose'], 'car order is lost');
assert.equal(cell.train!.engineAt, 0, 'the engine has no place in the train');
assert.equal(cell.train!.facing, 'e', 'which way it points is not carried');
const train = cell.trains[0];
assert.ok(train, 'the card carries no train');
assert.deepEqual(train!.cars, ['loaded tank', 'loaded boxcar', 'caboose'], 'car order is lost');
assert.equal(train!.engineAt, 0, 'the engine has no place in the train');
assert.equal(train!.facing, 'e', 'which way it points is not carried');
const svg = officeSvg([cell], area.runningRow);
assert.match(svg, /bs-t-eng/, 'the engine is not drawn');
@@ -1922,16 +2052,118 @@ describe('the static build', () => {
assert.deepEqual(order('e'), ['cab', 'hop', 'hop', '▶'], 'an eastbound train is not turned round');
});
it('shows A/D tracks on the Office card, taken and total', () => {
it('shows A/D tracks on the Office card, one chip per track', () => {
// REPORTED: the tooltip said "3 A/D tracks" and the card showed nothing — the number that
// decides whether the next arrival is an automatic collision (§8.3).
// decides whether the next arrival is an automatic collision (§8.3). The Roster Pass replaced
// the pips with one roster chip per A/D track (docs/plans/switching-paths.md), free or occupied.
const game = newGame(555);
const area = game.state.officeAreas.get(0)!;
const cell = view(game).cells.find((c) => c.kind === 'office')!;
assert.ok(cell.ad, 'the Office card carries no A/D count');
assert.equal(cell.ad!.of, 1, 'a Whistle Post has one A/D track');
assert.equal(cell.ad!.used, 0);
assert.match(officeSvg([cell], area.runningRow), /bs-ad/, 'no A/D pips are drawn');
assert.equal(cell.adTracks, 1, 'a Whistle Post has one A/D track');
assert.equal(cell.trains.length, 0, 'no train is standing yet');
const svg = officeSvg([cell], area.runningRow);
assert.match(svg, /bs-adchip/, 'no roster chip is drawn');
assert.match(svg, />free</, 'the one A/D track should read free with nothing standing on it');
});
it('draws every train standing at a busy Office, not just one', () => {
// REPORTED (docs/plans/switching-paths.md — "The Roster Pass"): the old single `train` field on
// a cell showed only whichever tray `s.trays` happened to yield first, so a second train holding
// at a Station was counted in the old A/D pips and never drawn at all.
const game = newGame(555);
const area = game.state.officeAreas.get(0)!;
area.tier = 'terminal'; // 4 A/D tracks — room for every train this test parks
const at = area.officeCoord;
const trainNumbers = [10, 12, 14, 16];
for (const n of trainNumbers) {
const id = `t${n}`;
game.state.trays.set(id, {
id, trainNumber: n, trainIsExtra: false, engineAt: 0,
consist: [{ type: 'boxcar', loaded: false }],
direction: 'east', facing: 'e',
position: { at: 'grid', seat: 0, coord: at }, movesUsed: 0,
} as never);
area.adOccupancy.push(id);
}
const cell = view(game).cells.find((c) => c.row === at.row && c.col === at.col)!;
assert.equal(cell.trains.length, 4, 'all four trains should be on the Office card');
assert.equal(cell.adTracks, 4, 'a Terminal has four A/D tracks');
const svg = officeSvg([cell], area.runningRow);
const chipCount = [...svg.matchAll(/class="bs-adchip/g)].length;
assert.equal(chipCount, 4, `expected 4 roster chips at a full Terminal, got ${chipCount}`);
assert.doesNotMatch(svg, />free</, 'every track is taken, so nothing should read free');
for (const n of trainNumbers) {
assert.match(svg, new RegExp(`data-crew="t${n}"`), `T${n} has no roster chip to click`);
}
});
it('draws the crew chip on a train standing away from the Office', () => {
// REPORTED: dropping a loaded boxcar off the back of Train 3 at the Freight House made "the
// train vanish off the face of the earth". The game state was never wrong — `selectedTrain` was
// only ever assigned inside the `cell.adTracks !== null` branch, so a train standing on any card
// OTHER than the Office (which is every card it stands on while actually being switched) got no
// badge at all: no label, no engine arrow, no cars. This is the Freight House from that report —
// an ordinary facility card, `adTracks: null`, one train parked on it mid-switch.
const cell = {
row: 1, col: 0, kind: 'facility', label: 'Freight House', running: false,
enhancements: [], enhancementsWhat: [], adTracks: null,
trains: [{
trayId: 'tray3', label: 'T3', cars: ['empty boxcar'], engineAt: 0, facing: 'w' as const,
what: 'Train 3 "Express"',
}],
cars: [], standingWest: 0, facility: null, links: ['ew'], what: '',
};
const svg = officeSvg([cell as never], 0);
assert.match(svg, /class="bs-crew"/, 'the crew badge is not drawn off the Office square');
assert.match(svg, />T3</, 'the train\'s own label is missing from the board');
});
it('draws a bare cut left-aligned, whatever the card\'s stored standingWest says', () => {
// "Settled questions" in docs/plans/switching-paths.md — the split only ever predicts something
// while a train stands on the card, and an earlier draft of the plan had this backwards. A stale
// standingWest surviving on an emptied card must not draw a gap nobody would recouple.
const cell = {
row: 0, col: 0, kind: 'trk', label: 'x', running: true, enhancements: [], enhancementsWhat: [],
trains: [], adTracks: null,
cars: ['boxcar', 'loaded hopper', 'reefer'],
standingWest: 2, // stale — as if a train had once stood here and left
facility: null, links: ['ew'], what: '',
};
const svg = officeSvg([cell as never], 0);
const xs = [...svg.matchAll(/class="bs-slot[^"]*" x="([-\d.]+)"/g)].map((m) => Number(m[1]));
assert.equal(xs.length, 3, 'all three cars should be drawn');
const sorted = [...xs].sort((a, b) => a - b);
// Left-aligned means each slot sits exactly 30px past the one before it — no gap anywhere in
// the row for an engine that is not there.
for (let i = 1; i < sorted.length; i++) {
assert.equal(sorted[i]! - sorted[i - 1]!, 30, `a gap survived at index ${i} with no train present`);
}
});
it('reads one split off the shared card, not one per train', () => {
// The whole justification for moving `standingWest` onto the card rather than the tray
// (docs/plans/switching-paths.md): two trays holding at one Office must not be able to disagree
// about the same row of cars, because there is only one number for them to read.
const game = newGame(555);
const area = game.state.officeAreas.get(0)!;
area.tier = 'station'; // 3 A/D tracks
const at = area.officeCoord;
const card = area.grid.get(`${at.row},${at.col}`)!;
card.standing = [{ type: 'boxcar', loaded: false }, { type: 'hopper', loaded: false }];
card.standingWest = 1;
for (const n of [10, 12]) {
const id = `t${n}`;
game.state.trays.set(id, {
id, trainNumber: n, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'east', facing: 'e',
position: { at: 'grid', seat: 0, coord: at }, movesUsed: 0,
} as never);
}
const cell = view(game).cells.find((c) => c.row === at.row && c.col === at.col)!;
assert.equal(cell.trains.length, 2, 'both trains should be on the Office card');
assert.equal(cell.standingWest, 1, "the card's split is one number, not one per train");
});
it('names the cars a drop would set out, and which end they come off', () => {
@@ -2150,6 +2382,49 @@ describe('the Division map shows the whole route', () => {
}
});
it('keeps every roster chip inside the Office cell it belongs to, at any occupancy', () => {
// "Two Trains, One Card": sizing the cell by OCCUPANCY moved the East Division Point sideways
// every time an A/D track filled or cleared. Sizing by CAPACITY (docs/plans/switching-paths.md)
// holds the map still, and every chip has to actually fit inside the cell that capacity bought.
const s = createEngineGame({
id: 'div-chips', seed: 7,
config: {
mode: 'solitaire', victory: 'highestAfterDays', length: 'standard',
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
},
playerNames: ['Solitaire'],
});
const area = areaOf(s, 0);
area.tier = 'terminal'; // 4 A/D tracks
for (const n of [10, 12, 14, 16]) {
const id = `t${n}`;
s.trays.set(id, {
id, trainNumber: n, trainIsExtra: false, engineAt: 0,
consist: [{ type: 'boxcar', loaded: false }],
direction: 'east', facing: 'e',
position: { at: 'grid', seat: 0, coord: area.officeCoord }, movesUsed: 0,
} as never);
area.adOccupancy.push(id);
}
const svg = divisionSvg(snapshot(s, [], null).division);
const cells = [...svg.matchAll(/class="bs-dcell bs-drun[^"]*"[^>]*><rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)"/g)]
.map((m) => ({ x: +m[1]!, w: +m[3]! }));
assert.ok(cells.length > 0, 'no Running Track cell drawn');
const office = cells.reduce((a, b) => (b.w > a.w ? b : a));
assert.ok(office.w > 78, `the Office cell did not widen for its 4 A/D tracks: ${office.w}`);
const chips = [...svg.matchAll(/class="bs-train"[^>]*><rect x="([-\d.]+)" y="[-\d.]+" width="([\d.]+)"/g)]
.map((m) => ({ x: +m[1]!, w: +m[2]! }));
assert.equal(chips.length, 4, `expected 4 train chips, got ${chips.length}`);
for (const c of chips) {
assert.ok(
c.x >= office.x - 0.01 && c.x + c.w <= office.x + office.w + 0.01,
`a chip at x=${c.x} w=${c.w} spills outside the Office cell [${office.x}, ${office.x + office.w}]`,
);
}
});
it('draws the Division as a line with two ends, never as a loop', () => {
// Seating players around a table invites exactly one misreading: that the route joins up. It
// does not. Both ends are labelled as ends, not as an entrance and an exit: odd trains run west
@@ -2409,6 +2684,88 @@ describe('the three places a game is drawn stay in step', () => {
});
});
describe('the Day rolling over says so (Gitea#10)', () => {
// "As the game rolls off the end of the day, you get a dialog saying such. Hard to keep track of
// time." A Day turns inside the phases that run themselves, so it passes between one click and
// the next — the phase banner is gone in 2.6 seconds.
//
// The goal half is written against `f.objective`, which on this line resolves a PER-PLAYER target
// from the game length: `standard` is 20 Revenue over 5 Days. (Main asks a different question of
// the same dialog — a combined floor off the victory dials — so that half is not a shared port.)
const frameAt = (day: number, length: GameLength = 'standard'): Frame => {
const s = createEngineGame({
id: 'dayend',
seed: 4021,
config: {
mode: 'solitaire',
victory: 'firstToTarget',
length,
optionalRules: { reducedVisibility: false, sisterTrains: false, employeeRotation: false, emergencyToolbox: false },
},
playerNames: ['Solitaire'],
});
s.clock.day = day;
return snapshot(s, [], null);
};
it('names the Day that ENDED, not the one starting', () => {
// Written from the frame after the rollover, so an off-by-one here would congratulate a player
// on finishing a Day they have not played yet.
const html = dayEndHtml(frameAt(3));
assert.ok(html.includes('Day 2 has ended'), `wrong Day named:\n${html}`);
assert.ok(html.includes('Day 3 of 5'), 'the Day now beginning is not named');
assert.ok(html.includes('3 Days left'), `the Days remaining are wrong:\n${html}`);
});
it('counts the last Day as the last Day rather than promising more', () => {
const html = dayEndHtml(frameAt(6));
assert.ok(html.includes('Day 5 has ended'), 'the final Day is misnamed');
assert.ok(html.includes('last Day on the timetable'), `still offering Days to run:\n${html}`);
assert.ok(!html.includes('Days left'), 'promises more Days after the last one');
});
it('reads the goal and the pace off the objective rather than working them out again', () => {
// One implementation of "what is the target and am I keeping up" — `objectiveOf`. A dialog that
// recomputed either would be one release away from disagreeing with the status block that shows
// the same numbers every turn.
const f = frameAt(3);
const html = dayEndHtml(f);
assert.ok(html.includes(`<b>${f.objective.target}</b>`), `the target is not shown:\n${html}`);
assert.ok(html.includes(`<b>${f.revenue}</b>`), "the viewer's Revenue is not shown");
// Nothing earned by Day 3 of 5 is behind a 20-Revenue pace, and the dialog says so in words.
assert.equal(f.objective.onPace, false, 'the fixture is no longer behind pace');
assert.ok(html.includes('behind pace'), 'the pace is not reported');
// A campaign game is a different target, and the dialog must not have 20 baked into it.
const long = frameAt(3, 'campaign');
assert.ok(dayEndHtml(long).includes('<b>45</b>'), 'the target does not follow the game length');
assert.ok(dayEndHtml(long).includes('Day 3 of 10'), 'the Day count does not follow the length');
});
it('puts the leader at the top and marks which row is yours', () => {
// The question at the end of a Day is who is ahead, which is not the order the seats are in.
const f = frameAt(2);
f.players = [
{ index: 0, seat: 0, name: 'Ada', revenue: 4, hand: 3 },
{ index: 1, seat: 1, name: 'Bo', revenue: 7, hand: 2 },
];
f.viewer = 0;
const html = dayEndHtml(f);
assert.ok(html.indexOf('Bo') < html.indexOf('Ada'), 'the standings are not in Revenue order');
assert.ok(html.includes('(you)'), 'the viewer is not marked in the standings');
// Marked from `f.viewer`, not from an assumed seat 0 — so moving the viewer moves the mark.
f.viewer = 1;
const moved = dayEndHtml(f);
assert.ok(moved.indexOf('(you)') < moved.indexOf('Ada'), 'the mark did not follow the viewer');
});
it('gives the page the dialog to fill', () => {
const html = readFileSync(join(dist, 'play.html'), 'utf8');
for (const id of ['dayenddlg', 'dayendbody']) {
assert.ok(html.includes(`id="${id}"`), `play.html has no #${id}`);
}
});
});
describe('every file the build needs is actually in the repo (regression)', () => {
it('does not gitignore a source page', () => {
// REGRESSION. `.gitignore` carried `replay*.html` to catch the throwaway files generated at the
@@ -2545,12 +2902,17 @@ describe('the New Game dialog', () => {
value,
checked: false,
}));
const extraRadios = ['divisionPointsOnly', 'ownOffice', 'anyOffice'].map((value) => ({
value,
checked: value === 'anyOffice',
}));
let html = '';
const node: Record<string, unknown> = {
id, value: '', textContent: '', title: '', returnValue: '', open: false,
style: {}, dataset: {}, onclick: null, scrollTop: 0, scrollHeight: 0,
classList: { add: () => {}, remove: () => {}, contains: () => false, toggle: () => {} },
radios,
extraRadios,
addEventListener: (type: string, fn: () => void) =>
void listeners.set(type, [...(listeners.get(type) ?? []), fn]),
showModal: () => void ((node as { open: boolean }).open = true),
@@ -2560,9 +2922,18 @@ describe('the New Game dialog', () => {
},
// Only the radio-group selectors the dialog actually uses; anything else is not this
// element's business and answering it with a guess would hide a typo in the real selector.
querySelectorAll: (sel: string) => (sel === 'input[name="ng-hand"]' ? radios : []),
querySelectorAll: (sel: string) =>
sel === 'input[name="ng-hand"]'
? radios
: sel === 'input[name="ng-extra"]'
? extraRadios
: [],
querySelector: (sel: string) =>
sel === 'input[name="ng-hand"]:checked' ? (radios.find((r) => r.checked) ?? null) : null,
sel === 'input[name="ng-hand"]:checked'
? (radios.find((r) => r.checked) ?? null)
: sel === 'input[name="ng-extra"]:checked'
? (extraRadios.find((r) => r.checked) ?? null)
: null,
};
Object.defineProperty(node, 'innerHTML', { get: () => html, set: (v: string) => void (html = v) });
return node;
@@ -2628,7 +2999,7 @@ describe('the New Game dialog', () => {
dlg['returnValue'] = 'deal';
(dlg['close'] as () => void)();
assert.equal(nav.search, '?seed=99&hand=threeTrackThreeOther&passenger=5&freight=0&transit=2');
assert.equal(nav.search, '?seed=99&hand=threeTrackThreeOther&extra=anyOffice&passenger=5&freight=0&transit=2');
});
it('deals nothing on cancel, and nothing on Esc', async () => {
@@ -2648,7 +3019,7 @@ describe('the New Game dialog', () => {
it('reloads when the answers are the URL the page already has, so a re-deal is not a no-op', async () => {
// Dealing a random seed, disliking it and dealing again at the same settings produces the same
// search string — and assigning `location.search` the value it already holds does nothing.
const url = '?hand=threeRandom&passenger=1&freight=1&transit=0';
const url = '?hand=threeRandom&extra=anyOffice&passenger=1&freight=1&transit=0';
const { els, nav } = await load(url);
(els.get('newgame')!['onclick'] as () => void)();
const dlg = els.get('newgamedlg')!;
@@ -2677,7 +3048,7 @@ describe('the New Game dialog', () => {
dlg['returnValue'] = 'deal';
(dlg['close'] as () => void)();
assert.equal(nav.search, '?hand=threeRandom&passenger=1&freight=1&transit=0', 'a bad seed was carried into the URL');
assert.equal(nav.search, '?hand=threeRandom&extra=anyOffice&passenger=1&freight=1&transit=0', 'a bad seed was carried into the URL');
});
});
@@ -2904,18 +3275,118 @@ describe('two crews switching are told apart', () => {
assert.notDeepEqual(f.moves[0]!.from, f.moves[1]!.from);
});
it('leaves out a train the rules will not let switch at all', () => {
// `movesFor` is pure track geometry; six cards print "no switching" and `check` enforces it.
// Offering the Circus Train in a "which train are you switching?" row offers a train whose
// every move is refused.
it('still offers a no-switching train as a crew to switch — it may be moved, just not worked', () => {
// v0.4.9 — six cards print "no switching", which means may not couple, set out or sort, not
// "may never be touched": a train held at the Office may still need to clear onto Secondary
// Track ahead of other traffic. `check` refuses the coupling itself, not the move, so this row
// is not filtered any differently for a no-switching train than for any other.
const game = twoCrews();
const s = game.state;
const circus = [...s.trays.values()][0]!;
circus.trainNumber = 18;
circus.trainIsExtra = true; // X18 Circus Train — noSwitching
const f = view(game);
assert.equal(f.moves.length, 1, 'a no-switching train was offered as a crew to switch');
assert.equal(f.moves[0]!.label, 'Train 12');
assert.equal(f.moves.length, 2, 'a no-switching train was left out of the crews offered to switch');
assert.deepEqual(f.moves.map((m) => m.label).sort(), ['Train 12', 'Train X18']);
});
});
describe('two trains at one platform are told apart (v0.4.9e)', () => {
/**
* REPORTED from the v0.4.9d playtest: "operating two trains in a station — the select button does
* not work. Regardless of which you pick, it is always one train, not the other."
*
* `porter.board` and `porter.detrain` carried no tray, so there was ONE button per platform however
* many trains were standing at it, and the reducer filled whichever tray came first out of
* `adOccupancy`. Clicking a roster chip changed what the board drew and nothing else — which is
* exactly what "the select button does not work" describes.
*
* Driven through `actionMenu` rather than `legalActions` because the second half of the failure was
* at this layer: the menu collapses identical labels within a crew, and "board passengers at (0,0)"
* describes both trains.
*/
const twoAtPlatform = (): { game: Game; trays: string[] } => {
const game = newGame(4242);
const s = game.state;
const area = areaOf(s, 0);
const f = area.grid.get(`${area.officeCoord.row},${area.officeCoord.col}`)!.facility!;
// A Station's worth of platform: Porters, slots, and two fares waiting.
f.allows = { outbound: true, inbound: true };
f.porters = 4;
f.capacity = { outbound: 2, inbound: 2 };
f.outboundBox = [{ type: 'coach', loaded: true }, { type: 'coach', loaded: true }];
const trays: string[] = [];
for (const trainNumber of [7, 9]) {
const id = s.freeTrays.pop()!;
s.trays.set(id, {
id, trainNumber, trainIsExtra: false, engineAt: 0,
consist: [{ type: 'coach', loaded: false }],
direction: 'east', facing: 'e',
position: { at: 'grid', seat: 0, coord: area.officeCoord },
movesUsed: 0,
} as never);
area.adOccupancy.push(id);
trays.push(id);
}
s.clock.phase = 'loadUnload';
s.clock.currentActor = 0;
return { game, trays };
};
it('offers boarding once per train, with the train named on the button', () => {
const { game } = twoAtPlatform();
const labels = actionMenu(game)
.direct.flatMap((g) => g.actions)
.map((a) => a.label)
.filter((l) => /^board passengers/.test(l));
assert.equal(labels.length, 2, `expected one button per train, got ${JSON.stringify(labels)}`);
assert.ok(labels.some((l) => /Train 7/.test(l)), `no button names Train 7: ${JSON.stringify(labels)}`);
assert.ok(labels.some((l) => /Train 9/.test(l)), `no button names Train 9: ${JSON.stringify(labels)}`);
});
it('boards the train whose button was pressed', () => {
const { game, trays } = twoAtPlatform();
const { options } = actionGroups(game);
const nine = options.findIndex(
(o) => o.type === 'porter.board' && (o as { trayId?: string }).trayId === trays[1],
);
assert.ok(nine >= 0, 'no boarding option names the second train');
submit(game, options[nine]!);
assert.equal(game.state.trays.get(trays[1]!)!.consist[0]!.loaded, true, 'Train 9 did not get them');
assert.equal(game.state.trays.get(trays[0]!)!.consist[0]!.loaded, false, 'Train 7 was filled instead');
});
it('will not detrain the passengers it has just put aboard', () => {
// The other half of the same playtest: "passenger stations — passengers just boarded cannot be
// immediately unloaded." They could, for a Porter action and full Revenue, without the train
// moving an inch.
const { game, trays } = twoAtPlatform();
const board = actionGroups(game).options.find(
(o) => o.type === 'porter.board' && (o as { trayId?: string }).trayId === trays[0],
)!;
submit(game, board);
const detrains = actionGroups(game).options.filter((o) => o.type === 'porter.detrain');
assert.equal(detrains.length, 0, 'detraining was still offered for passengers who boarded here');
assert.equal(
check(game.state, 0, { type: 'porter.detrain', at: areaOf(game.state, 0).officeCoord, trayId: trays[0]! }),
'LOADED_IN_THIS_DISTRICT',
);
});
it('says on the coach that it was loaded here', () => {
// The printed game turns the chip upside down in the tray; this is the screen's version of that.
const { game, trays } = twoAtPlatform();
submit(game, actionGroups(game).options.find(
(o) => o.type === 'porter.board' && (o as { trayId?: string }).trayId === trays[0],
)!);
const f = view(game);
const office = f.cells.find((c) => c.kind === 'office')!;
const train = office.trains.find((t) => t.trayId === trays[0]);
assert.ok(train, 'the boarded train is not on the Office card');
assert.ok(
train!.cars.some((c) => /loaded here/.test(c)),
`the coach does not say where it was loaded: ${JSON.stringify(train!.cars)}`,
);
});
});