v0.4.7 — the switching game: track order, the cut on your own card, and four rules

Eight play reports and one design that had been written up and not built. The
through-line is switching: what a card can hold, which end of a train a cut comes
off, which way a train meets cars standing on the line, and what the board and the
log say about all of it.

TRACK ORDER FOR STANDING CARS, AND THE CUT ON YOUR OWN CARD

Two reports turned out to be one root cause. `TrackCard.standing` claimed "in track
order (§A.3)" and had no defined orientation at all, while `CrewTray.consist` does
(nose first, relative to facing) — so every transfer between them was a conversion
nothing performed. §A.3 says what it should be: cars occupy the track "in the same
order they originally held, left-to-right". Left-to-right is west-to-east, and that
is now the defined orientation of `standing` and of an industry track through
`carsOn`. It is the board's orientation, not the train's, so it does not change when
a different train touches the card.

  - Setting out is batch-invariant. Four cars at once, four singles and two pairs
    parked three different orders, one of them physically impossible. Successive
    cuts off the same end stack up towards the engine, so the insertion point is the
    train's own place in the row.
  - Approaching a cut from either end now mirrors. `couples` is built nearest-first
    along the direction of travel and reverses onto the nose, so the farthest car met
    ends up nose-most — which is what makes a run-around worth its Move.
  - A train no longer drives through its own cut. The walk began at the neighbour of
    the start square and never read the start card, so a crew could set cars out and
    pull straight away from them. Coupling is mandatory (§A.4) and your own square is
    no exception; the cut counts against the four-car limit. Setting out off the end
    you are not leaving by still works.

`CrewTray.standingWest` records where a train stands among the cars on its card — a
train may set out off both ends on one square, so which side a cut is on is not
recoverable from the array alone.

On the board, the cut is drawn split at the train — west cars left, east cars right,
engine in the gap — and each car's tooltip says whether it stands ahead of or behind
the engine. The history says which end a cut came off, and a move's button separates
"takes your own boxcar back off this card" from cars found standing on the line.

Decided: taking your own cut back on the square you are standing on is UNDOING the
drop. It is exempt from trains 3/4's per-location freight budget, X13's "drop but not
pick up" and X22's "empties only", and it refunds the budget the drop spent.
Otherwise a legal-looking drop becomes silently one-way.

Measured, 200 paired seeds, developer bot: -0.55 revenue (t = -3.63), freight revenue
1.11 -> 0.56. That cost is the bot's, not the rule's — its trains run engine-first,
so at a stub industry it sets a car out between itself and the only way out, and the
correct play is §A.5's facing-point move, which is the cross-turn planning TODO.md
already records as out of reach of any bot. Filtering self-recoupling moves out of its
options took recoupling from 625 of 1,029 set-outs to 101 of 677, and all 101 that
remain are that case. Read the number as a bot measurement, not a balance one.

THE SUPERINTENDENT'S RULING NAMES THE TRAINS IT IS ABOUT

Reported: the Superintendent could not tell which train he was clearing. The heading
asks the question now — "may Train 6 follow Train 4 onto the same Mainline card?" —
and the trains moved to the FRONT of each button, because the button splits its label
at the first em-dash and showed only the head.

AN INDUSTRY TRACK HOLDS FOUR CARS, LIKE EVERY OTHER CARD

Reported at undo 188: "we wanted to drop two cars, but were only allowed to drop one."
An industry track was built as long as its box count, so a one-box industry had room
for one car. Box count is how much WORK an industry can hold, not how much RAIL it
has. Ordinary track was the other exception, unbounded; both are gone and every card
holds four.

THE FREIGHT AGENT MAY STAGE A LOAD BEFORE THE CAR IS THERE

§6.3 asks nothing of the industry track — the empty car belongs to §9.3's Load the
car, which is the Laborer's action. The gate now lives only there, so cargo can wait
on the dock while the car to ship it in is still being switched in. Nothing can jam:
a load in a green box is waiting, not stuck.

THE TRUCK DOCK UNLOADS, AND BRINGS NOBODY

+1 inbound, no Laborer. It printed +1 outbound and +1 Laborer, which made it a
longer-host-list copy of Forklifts. Beside Packing Sheds it now does nothing at all,
and the hand tooltip says so before it is played.

Also in this release, from the days before: Mainline card tooltips computed from the
crossing rule; an Extra starts from the Division Point its number sends it to; a
modifier's suppressed grant comes back when a Whistle Post is upgraded; the Oil
Refinery and the Grocer's Warehouse ship as well as receive, per the card reference;
and the dormant defences name the attack they answer. `.claude/` is now gitignored —
it holds Claude Code's worktrees, i.e. a second checkout of this repository.

570 tests, typecheck clean. The three published replays were re-recorded twice —
legality changed, so bot play changed. Full detail in CHANGELOG.md.
This commit is contained in:
Jesse
2026-08-19 12:12:30 -04:00
parent 08339effba
commit 9f3b92d08e
44 changed files with 9739 additions and 4130 deletions
+50 -22
View File
@@ -151,7 +151,10 @@ export function divisionSvg(nodes: DivisionView[]): string {
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(' · ')}` : ''}`,
: `${n.label} — Mainline${n.gradeUp ? `, climbs ${n.gradeUp === 'east' ? 'east' : 'west'}` : ''}${n.modifiers.length ? ` · ${n.modifiers.join(' · ')}` : ''}` +
// 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}` : ''),
seat: null,
// A Division Point is one region — the queue trains enter and leave the Division through.
regions: dp ? 1 : (n.regions ?? 0),
@@ -563,7 +566,7 @@ export function officeSvg(
}
}
// MEN | AT | WORK — one physical sign, worked left to right loading and right to left
// unloading. The spotted car sits past WORK, on the siding drawn below.
// unloading. The spotted car sits past WORK, standing on the card itself.
for (let i = 0; i < f.maw.length; i++) {
out += box(bx, by, f.maw[i] !== null, 'bs-maw', ['M', 'A', 'W'][i]);
bx += cellW + 2;
@@ -623,21 +626,45 @@ export function officeSvg(
}
}
// Standing room, drawn as the printed squares: filled means occupied.
//
// `Math.max(1, …)` applies only to an industry, whose track is at least one car long. A Passenger
// Facility has NO industry track — passengers board straight off the platform — so a Depot was
// being drawn a siding slot it cannot spot a car on.
const spots = cell.facility
? cell.facility.kind === 'passenger'
? cell.facility.trackCap
: Math.max(1, cell.facility.trackCap)
: cell.cars.length;
for (let i = 0; i < Math.min(spots, 4); i++) {
const filled = i < cell.cars.length;
const carTip = filled
? `${cell.cars[i]} standing here`
: 'an empty space on this track — a car may be spotted here';
/**
* THE CARS STANDING HERE — NO PRINTED SIDING BEHIND THEM.
*
* An industry card used to draw one empty square per unit of its capacity, which read as a
* siding of a particular length printed on the card. No industry card prints one. Worse, the
* length came from the box count, so a one-box industry drew a single square and looked like it
* could only ever hold one car — which is exactly what the engine was wrongly enforcing.
*
* Every card, industry or not, now draws what is actually standing on it and nothing more. Four
* is the ceiling everywhere (`MAX_CONSIST`), so the row cannot overflow the card.
*
* The 4 is written out rather than imported: this function's SOURCE is serialized into the
* standalone replay page, where module imports are not in scope. Referencing the constant threw
* `MAX_CONSIST is not defined` in the rendered HTML while typechecking perfectly here.
*/
/**
* WHICH SIDE OF THE ENGINE THE CUT IS ON.
*
* Reported from play: "right after dropping my cars I need to be able to see if those cars are
* ahead or behind the train." They were drawn as one strip starting at the left edge whether a
* train was on the card or not, so the picture could not say.
*
* `cars` runs WEST TO EAST and `standingWest` is how many of them are west of the train, so the
* row is split there: the west cars stay left-aligned, the east cars are pushed over to the
* right-hand end, and the gap between them is where the engine is standing. Whether that gap
* 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 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
? 'standing here'
: (cell.train.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}`;
/**
* WHICH CAR IS STANDING HERE, not just that one is.
*
@@ -666,7 +693,7 @@ export function officeSvg(
// A caboose is never "loaded" in the freight sense (carLabel says so), so it is drawn solid:
// it is a car that is doing its job, not an empty waiting for one.
const loaded = /^loaded/.test(car) || /caboose/.test(car);
const cls = filled ? ` bs-occ bs-car-${type}${loaded ? ' bs-loaded' : ' bs-mt'}` : '';
const cls = ` bs-occ bs-car-${type}${loaded ? ' bs-loaded' : ' bs-mt'}`;
/**
* LOADED OR EMPTY, TOLD THE SAME WAY THE TRAY TELLS IT.
*
@@ -678,10 +705,11 @@ export function officeSvg(
* Now the card matches the tray — solid face for loaded, hollow for empty — and every slot
* carries the car's own words as a tooltip, so "loaded hopper" is one hover away.
*/
out += `<rect class="bs-slot${cls}" x="${8 + i * 30}" y="${H - 26}" width="26" height="15" rx="2" data-tip="${esc(carTip)}"/>`;
if (filled) {
out += `<text class="bs-carlab${loaded ? ' bs-lab-ld' : ''}" x="${21 + i * 30}" y="${H - 15}" text-anchor="middle" data-tip="${esc(carTip)}">${esc(type)}</text>`;
}
// West cars run rightwards from the left edge; east cars run leftwards from the right edge, so
// the engine's place in the row is the gap left between them.
const sx = westOfEngine ? 8 + i * 30 : W - 34 - (shown - 1 - i) * 30;
out += `<rect class="bs-slot${cls}" x="${sx}" y="${H - 26}" width="26" height="15" rx="2" data-tip="${esc(carTip)}"/>`;
out += `<text class="bs-carlab${loaded ? ' bs-lab-ld' : ''}" x="${sx + 13}" y="${H - 15}" text-anchor="middle" data-tip="${esc(carTip)}">${esc(type)}</text>`;
}
if (cell.enhancements.length > 0) {
+110 -15
View File
@@ -19,9 +19,17 @@
* complete at all.
*/
import { applyIntent, areaOf, canAdvanceLoad, destinationsFor, facilityCarTypes, laborersLeft } from '../engine/apply.ts';
import {
applyIntent,
areaOf,
canAdvanceLoad,
destinationsFor,
facilityCarTypes,
laborersLeft,
ownCutFor,
} from '../engine/apply.ts';
import { MAX_CONSIST, nextOfficeTier, officeProfile } from '../engine/content.ts';
import type { Hand, TrackGeometry } from '../engine/content.ts';
import type { CarType, Hand, TrackGeometry } from '../engine/content.ts';
import type { GameEvent } from '../engine/events.ts';
import type { Intent } from '../engine/intents.ts';
import { legalActions } from '../engine/legal.ts';
@@ -364,8 +372,10 @@ function chooseLocalOption(
return because('the crew is away from the Office and can never depart from where it stands', can('switch')!);
}
// 3. Stock a green box only when the load can actually finish — an empty car of the right type
// is already spotted. Stocking without one just fills the box.
// 3. Stock a green box when the load can actually be worked — an empty car of the right type is
// already spotted. Staging ahead of the car is legal (§6.3) and cannot jam anything, but it
// spends the Stage's one Freight Agent action on a load no Laborer can touch yet, so it is not
// worth CHOOSING the option for; it is taken only as a fallback once the option is chosen.
if (can('freightAgent') && canStockProductively(s, player)) {
return because('a green box can be stocked with a load that can actually finish', can('freightAgent')!);
}
@@ -463,9 +473,13 @@ function isTrainCard(s: GameState, cardId: string): boolean {
/**
* A facility with room in its green box AND an empty car OF ITS OWN TYPE already spotted.
*
* The type match matters: a load that reaches WORK with no matching car to go onto is stuck, and a
* stuck load strips the industry track of Operational Rail status (§9.3), so no car can be brought
* in to rescue it. Stocking speculatively jams the facility.
* A PRIORITY TEST, NOT A LEGALITY TEST — the engine stocks either way (§6.3). What it decides is
* whether stocking is worth the Local Operations action THIS Stage: with a car spotted the load
* moves next Stage, without one it sits.
*
* The type match matters when it does move: a load that reaches WORK with no matching car to go
* onto is stuck, and a stuck load strips the industry track of Operational Rail status (§9.3), so
* no car can be brought in to rescue it. `loadCanFinish` keeps the Laborers off such a load.
*/
function canStockProductively(s: GameState, player: PlayerIndex): boolean {
for (const card of areaOf(s, player).grid.values()) {
@@ -1036,6 +1050,25 @@ function loadReason(i: Intent): string {
}
}
/**
* Would a load stocked here be workable straight away — is there a spotted empty car of that type
* not already promised to a load in the box or on the sign?
*
* A PREFERENCE, NOT A RULE. §6.3 stocking has no car requirement; this only ranks one legal stock
* above another, so the Stage's single Freight Agent action goes where a Laborer can use it.
*/
function stockCanBeWorked(s: GameState, player: PlayerIndex, at: GridCoord, carType: CarType): boolean {
const f = areaOf(s, player).grid.get(coordKey(at))?.facility;
if (!f) return false;
// Passengers board off the platform with no car spotted at all (§9.2), so a stocked coach is
// always immediately workable.
if (f.kind !== 'freight') return true;
const spotted = f.industryTrack.cars.filter((c) => !c.loaded && c.type === carType).length;
const staged = f.outboundBox.filter((c) => c.type === carType).length;
const working = (f.menAtWork ?? []).filter((l) => l?.dir === 'out' && l.type === carType).length;
return spotted - staged - working > 0;
}
/**
* Is there already an empty car of the right type spotted to receive this load (§9.3)? Without one
* the load can be started and walked across MEN|AT|WORK but can never come off.
@@ -1077,10 +1110,30 @@ function consistAfterMove(
(d) => d.coord.row === move.to.row && d.coord.col === move.to.col,
);
if (!dest) return null;
// Forward means the engine leads and meets the cars head-on (§A.3).
return move.reverse ? [...tray.consist, ...dest.couples] : [...dest.couples, ...tray.consist];
/**
* Forward means the engine leads and meets the cars head-on (§A.3), and `couples` is ordered
* NEAREST FIRST — so the last car met ends up nose-most and the cut reverses on its way into the
* tray. Predicting it unreversed made the bot's run-around test read the wrong car as the tail
* whenever it approached a cut of two or more forwards.
*/
return move.reverse
? [...tray.consist, ...dest.couples]
: [...[...dest.couples].reverse(), ...tray.consist];
}
/**
* Would this move drag the cars the crew has just set out back onto the train?
*
* Coupling is mandatory, so pulling out through the end a cut is standing at picks it up again —
* which usually undoes the set-out the crew made this turn. The bot cannot make an ILLEGAL move
* (legality is enforced upstream), so this costs it nothing to ignore; it simply wastes the Move,
* and the crew arrives with the car it was trying to leave behind.
*/
function recouplesOwnCut(s: GameState, player: PlayerIndex, i: Intent): boolean {
return i.type === 'switch.move' && ownCutFor(s, player, i.trayId, i.reverse).length > 0;
}
/** Is this player's crew sitting somewhere it can never depart from? */
function strandedFromOffice(s: GameState, player: PlayerIndex): boolean {
const area = areaOf(s, player);
@@ -1238,6 +1291,26 @@ function followThrough(
}
case 'switch': {
/**
* A MOVE THAT DRAGS THE CREW'S OWN CUT BACK ON IS A WASTED MOVE, so take those off the table
* before any heuristic gets to choose one.
*
* Coupling is mandatory (§A.4), so pulling out through the end a cut is standing at picks it
* straight back up — which undoes the set-out the crew just made. Measured before this filter:
* **625 of 1,029 set-outs across 60 games were recoupled by the very next move**, 219 of them
* cars that had just been spotted at an industry. The bot was not doing anything illegal; it
* was spending two Moves to end up where it started, over and over.
*
* Filtered here rather than at each `find` below because there are six of them and a rule that
* has to be remembered at six call sites is a rule that will be forgotten at the seventh. The
* originals come back if the filter would leave the crew with no move at all — backed into a
* stub behind its own cars, the only way out IS through them, and standing still is worse.
*/
const clear = options.filter((i) => !recouplesOwnCut(s, player, i));
if (options.some((i) => i.type === 'switch.move') && clear.some((i) => i.type === 'switch.move')) {
options = clear;
}
// Re-check every Move, not just when choosing the option. Conditions change mid-turn — a car
// gets coupled, a siding fills — and once there is nothing left to do the fall-through would
// pick an arbitrary legal move and burn the remaining Moves shuttling.
@@ -1457,8 +1530,30 @@ function followThrough(
}
const clear = options.find((i) => i.type === 'freightAgent.clearInbound');
if (clear) return because('the red Inbound box is full and blocking further unloading', clear);
const stock = options.find((i) => i.type === 'freightAgent.stockOutbound');
if (stock) return because('stock a green box so a Laborer has work next Stage', stock);
/**
* PREFER THE BOX WHOSE LOAD CAN ACTUALLY BE WORKED.
*
* §6.3 lets the Freight Agent stage a load with no car spotted — cargo may wait on the dock —
* so every facility with room and a matching car in the Division Yard is now offered, not just
* the ready ones. `canStockProductively` chose the option believing a ready facility existed;
* taking the first offer regardless would spend the Stage's one Freight Agent action on some
* other industry that cannot move its load for want of a car. Staging ahead is still taken as
* a fallback: it is legal, it cannot jam anything, and it saves an action later.
*/
const stockable = options.filter(
(i): i is Extract<Intent, { type: 'freightAgent.stockOutbound' }> =>
i.type === 'freightAgent.stockOutbound',
);
const workable = stockable.find((i) => stockCanBeWorked(s, player, i.at, i.carType));
const stock = workable ?? stockable[0];
if (stock) {
return because(
workable
? 'stock a green box whose load a Laborer can start next Stage'
: 'stage a load ahead of the car — it waits in the green box until one is spotted',
stock,
);
}
/**
* NEVER UNJAM A HEALTHY BOX.
*
@@ -1508,7 +1603,7 @@ function wantedCars(s: GameState, player: PlayerIndex): WantedCar[] {
const f = card.facility;
if (!f || f.kind !== 'freight') continue;
const spotted = f.industryTrack.cars.length;
if (spotted >= f.industryTrack.length) continue;
if (spotted >= MAX_CONSIST) continue;
// Every commodity the industry handles, asked of its profile. A hand-written switch here had
// drifted from the sheet: it named two industries that do not exist (`produceShed`,
// `oilRefinery`) and omitted three that do (`freightHouse`, `refinery`, `packingSheds`), so
@@ -1537,12 +1632,12 @@ function wantedCars(s: GameState, player: PlayerIndex): WantedCar[] {
* Would spotting this car here do any work?
*
* An OUTBOUND facility needs an EMPTY car of its own commodity to load onto; an INBOUND one needs
* a LOADED car of its commodity to unload. Anything else merely consumes a slot on a finite
* industry track (§9.3).
* a LOADED car of its commodity to unload. Anything else merely consumes room on the industry's
* track, which holds four cars like any other card (§9.3).
*/
function facilityWants(f: Facility, car: RollingStock): boolean {
if (f.kind !== 'freight') return false;
if (f.industryTrack.cars.length >= f.industryTrack.length) return false;
if (f.industryTrack.cars.length >= MAX_CONSIST) return false;
if (!facilityCarTypes(f).includes(car.type)) return false;
if (!car.loaded && f.allows.outbound) return true;
if (car.loaded && f.allows.inbound) return true;
+43 -15
View File
@@ -15,6 +15,7 @@
* panel cannot drift from the rules.
*/
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';
@@ -130,14 +131,26 @@ export function narrate(e: GameEvent, ctx: NarrateContext = {}): Narration {
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.`,
};
case 'carsCoupled':
case 'carsCoupled': {
/**
* TAKING YOUR OWN CUT BACK IS NOT THE SAME EVENT AS FINDING CARS ON THE LINE, and the history
* read as though it were — "coupled 2 cars" told a player who had just set those very cars out
* that the game had silently undone their work. It has not: they were standing at the end the
* train pulled out through, and coupling is mandatory (§A.4).
*/
const own = e.recoupled?.stock.length ?? 0;
const found = e.stock.length - own;
const parts: string[] = [];
if (own > 0) parts.push(`picked its own ${carsLabel(e.recoupled!.stock)} back up off ${at(e.recoupled!.at)} on the way out`);
if (found > 0) parts.push(`coupled ${carsLabel(e.stock.slice(own))} standing on the line`);
return {
tone: 'plain',
where: e.at,
text:
`Coupled ${e.stock.length} car(s) at ${at(e.at)} ${e.toNose ? 'ONTO THE NOSE' : 'behind the train'}` +
`: ${carsLabel(e.stock)}`,
` — ${parts.join(', and ')}`,
};
}
case 'consistSorted':
return {
tone: 'good',
@@ -145,10 +158,14 @@ export function narrate(e: GameEvent, ctx: NarrateContext = {}): Narration {
text: `SMALL YARD — consist re-ordered from [${carsLabel(e.before)}] to [${carsLabel(e.after)}], so the right car is now on the end and can be spotted`,
};
case 'carsDropped':
// WHICH END. A cut comes off an outer end (§A.3) and the end decides everything that follows:
// the train may pull away from cars set out behind it and must couple back up to cars set out
// in front. "Dropped 2 cars" left the one fact that matters out of the record.
return {
tone: 'plain',
where: e.at,
text: `Dropped ${carsLabel(e.stock)} at ${at(e.at)}`,
text:
`Set out ${carsLabel(e.stock)} at ${at(e.at)}, off the ${e.fromNose ? 'NOSE — ahead of the engine, so pulling forward will couple them again' : 'TAIL — behind the engine, so it may pull away and leave them'}`,
};
// -- cards
@@ -226,6 +243,14 @@ 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':
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`,
};
case 'trainMadeUp':
return {
tone: 'good',
@@ -493,37 +518,40 @@ export function impediments(s: GameState, player: PlayerIndex = 0): Impediment[]
where: `${name} ${key}`,
why: blockedByBox
? 'green box has a load but MEN is occupied'
: `no empty ${want} spotted on this industry's track — a load has nowhere to go until a ` +
'crew sets one out here (§9.3)',
: `a load is staged but no empty ${want} is spotted on this industry's track — it stays ` +
'in the green box until a crew sets one out here (§9.3)',
severity: blockedByBox ? 'waiting' : 'stuck',
});
}
if (f.allows.outbound && f.outboundBox.length === 0) {
/**
* WHAT TO DO NEXT, in the order you have to do it.
* WHAT TO DO NEXT — AND THE TWO STEPS CAN BE DONE IN EITHER ORDER.
*
* A freight industry cannot be stocked at all until an empty car of its commodity is standing
* on its track (§9.3) — so "needs a Freight Agent action" was the second step told to a player
* who had not done the first, and the Freight Agent option simply would not be there. Measured
* before the rule was enforced, 78% of the stocking moves the menu offered had no car to load
* onto.
* §6.3 stocking needs only a car in the Division Yard; §9.3's "Load the car" is what needs an
* empty car of the commodity standing on the industry's track. So an empty siding is not a
* reason to hold the Freight Agent back — it is a second errand to run before the Laborers can
* start. Saying "bring a car in FIRST" sent players to do them in a fixed order they are not
* bound by, and wasted the Stage's one Freight Agent action.
*/
const spotted = f.industryTrack.cars.some((c) => !c.loaded && facilityCarTypes(f).includes(c.type));
out.push({
where: `${name} ${key}`,
why: spotted
? 'green box empty — nothing to load (needs a Freight Agent action)'
: `green box empty, and no empty ${want} is spotted here — bring one in with a crew FIRST, ` +
'then the Freight Agent can stage a load onto it (§9.3)',
: `green box empty — the Freight Agent can stage a load now, but no empty ${want} is ` +
'spotted here, so a crew must set one out before Laborers can work it (§9.3)',
severity: 'waiting',
});
}
if (f.industryTrack.cars.length >= f.industryTrack.length) {
// Four cars is the whole of any track card, industry or not — the same limit that caps a
// consist. It is no longer the industry's box count, which is what used to make a one-box
// industry report itself full with a single car standing on it.
if (f.industryTrack.cars.length >= MAX_CONSIST) {
out.push({
where: `${name} ${key}`,
why: `industry track full (${f.industryTrack.length} cars) — no room to spot another`,
why: `industry track full (${MAX_CONSIST} cars) — no room to spot another`,
severity: 'stuck',
});
}
+18 -9
View File
@@ -204,7 +204,7 @@ export function compress(frames: Frame[]): Packed {
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
// 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];
return [ci, wi, c.enhancements, c.tray, c.cars, fi, c.train, c.ad, c.enhancementsWhat, c.standingWest];
});
return { ...f, cells } as unknown as Frame;
});
@@ -238,7 +238,7 @@ export function rehydrateCells(
facs: unknown[],
): unknown[] {
return packed.map((row) => {
const p = row as [number, number, string[], string | null, string[], number, unknown, unknown, string[]];
const p = row as [number, number, string[], string | null, string[], number, unknown, unknown, string[], number];
const c = cards[p[0]] as [number, number, string, string, boolean, string[]];
return {
row: c[0], col: c[1], kind: c[2], label: c[3], running: c[4], links: c[5],
@@ -249,6 +249,10 @@ export function rehydrateCells(
// 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,
// which read as 0 — the whole cut east of the engine, which is what they used to draw anyway.
standingWest: p[9] ?? 0,
};
});
}
@@ -453,7 +457,10 @@ const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({'&':'&amp;','<':'&lt;','
function miniFacility(x) {
let h = '<div class="mini">';
if (x.greenCap > 0) h += '<span class="dim">grn </span>' + boxes(x.green, x.greenCap, 'g');
if (x.trackCap > 0) h += '<br><span class="dim">work </span>' +
// Gated on the sign itself. This used to gate on trackCap, which was a stand-in for "freight
// facility" back when only a freight card had an industry track length; the length is gone and
// maw is the honest test — a Passenger Facility has no MEN | AT | WORK sign at all.
if (x.maw.length > 0) h += '<br><span class="dim">work </span>' +
x.maw.map((m) => '<span class="box ' + (m ? 'm' : 'empty') + '">' + (m ? esc(m) : '·') + '</span>').join('');
if (x.redCap > 0) h += '<br><span class="dim">red </span>' + boxes(x.red, x.redCap, 'r');
return h + '</div>';
@@ -522,18 +529,20 @@ function render() {
'<div class="fac"><b>' + esc(x.name) + '</b> <span class="dim">' + esc(x.commodity) + ' · ' + esc(x.flow) +
' · laborers ' + esc(x.laborers) + ' · porters ' + esc(x.porters) + '</span>' +
'<div class="boxes"><span class="dim">green</span>' + boxes(x.green, x.greenCap, 'g') + '</div>' +
// No sign and no siding on a Passenger Facility: maw is empty for one, but the LABEL was
// printed before the loop, so a Depot showed the caption over nothing. The mini card above
// gates on trackCap and was already right; this copy was not.
// No sign on a Passenger Facility: maw is empty for one, but the LABEL was printed before
// the loop, so a Depot showed the caption over nothing.
// (No backticks in here — this whole block is inside a template literal.)
(x.maw.length > 0
? '<div class="boxes"><span class="dim">MEN|AT|WORK</span>' +
x.maw.map((m) => '<span class="box ' + (m ? 'm' : 'empty') + '">' + (m ? esc(m) : '·') + '</span>').join('') + '</div>'
: '') +
'<div class="boxes"><span class="dim">red</span>' + boxes(x.red, x.redCap, 'r') + '</div>' +
// 's', not 'g': the siding is a place, not a direction, and green is reserved for outbound.
(x.trackCap > 0 || x.track.length > 0
? '<div class="boxes"><span class="dim">siding</span>' + boxes(x.track, x.trackCap, 's') + '</div>'
// 's', not 'g': standing here is a place, not a direction, and green is reserved for outbound.
// Cap 0 so only the cars actually spotted are drawn — an industry card prints no siding, and
// the row of empty squares this used to draw claimed both that it did and that the siding was
// as long as the industry's box count. It holds four cars, the same as any track card.
(x.track.length > 0
? '<div class="boxes"><span class="dim">spotted</span>' + boxes(x.track, 0, 's') + '</div>'
: '') +
'<div class="fstat ' + (x.jammed ? 'bad' : (x.canFinish ? 'good' : 'idle')) + '">' +
(x.jammed
+82 -9
View File
@@ -17,6 +17,7 @@ import {
facilityCarType,
laborersLeft,
movesFor,
ownCutFor,
portersLeft,
} from '../engine/apply.ts';
import {
@@ -39,10 +40,11 @@ import {
officeProfile,
trainProfile,
houseRules,
mainlineDescription,
} from '../engine/content.ts';
import type { Intent } from '../engine/intents.ts';
import type { Facility, GameState, PlayerIndex, TrackCard, TurnoutOrientation } from '../engine/state.ts';
import { playerAtSeat, railFacingOf, seatOf, turnOf } 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';
import { connectionsFor, slopeOfPair, variantsFor } from '../engine/track.ts';
@@ -103,6 +105,18 @@ export type CellView = {
*/
ad: { used: number; of: number } | null;
cars: string[];
/**
* Cars in `cars` that stand WEST of the train on this card — 0 when no train is here.
*
* `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.
*/
standingWest: number;
facility: FacilityView | null;
/**
* The port pairs this card joins, as two-letter codes — 'ew' for the through track, and 'ne',
@@ -125,7 +139,8 @@ export type FacilityView = {
/**
* Freight or passengers — the one thing the renderers could not previously ask.
*
* Without it they guessed from side effects (`trackCap > 0`, `laborers` starting "0/0"), and one
* Without it they guessed from side effects (a non-empty industry track, `laborers` starting
* "0/0"), and one
* of the three simply did not guess at all, so a Depot drew three MEN | AT | WORK boxes it has no
* Laborer to work. Reported from playtesting.
*/
@@ -138,8 +153,15 @@ export type FacilityView = {
maw: (string | null)[];
red: string[];
redCap: number;
/**
* Cars standing on the industry's track, and nothing about how many more will fit.
*
* `trackCap` used to ride alongside this and every renderer drew that many empty squares — a
* printed siding, as long as the industry's box count. No industry card prints one, and the
* number was wrong anyway: a card holds four cars like any other. Both the field and the squares
* are gone; the room left is `spaceOn`'s business, not a drawing's.
*/
track: string[];
trackCap: number;
laborers: string;
porters: string;
/**
@@ -258,6 +280,14 @@ export type DivisionView = {
* on that grade has no visible meaning.
*/
gradeUp: string | null;
/**
* Mainline cards only: what the card does to a train, from `mainlineDescription`.
*
* "I have no idea the impact Hilly and Uncontrolled Siding have on game play" — and there was
* nowhere to find out: the tip carried the card's NAME and its modifiers and nothing about the
* crossing time or whether trains may pass.
*/
what?: string;
/** Mainline cards only: how many regions the card is divided into (§2.1 — two). */
regions?: number;
/** Office nodes only: the Running Track, Limits to Limits, west to east. */
@@ -479,7 +509,6 @@ function facilityView(
red: f.inboundBox.map(carLabel),
redCap: f.capacity.inbound,
track: f.industryTrack.cars.map(carLabel),
trackCap: f.industryTrack.length,
laborers: `${laborersLeft(f)}/${f.laborers}`,
porters: `${portersLeft(f)}/${f.porters}`,
canFinish: canFinishHere(f),
@@ -546,6 +575,21 @@ function baseOf(
}
/** The train standing on a given grid square, drawn as it is seated in the Crew Tray. */
/**
* Where the train standing on this card sits among the cars standing on it, clamped to the row.
*
* 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'] {
for (const [id, t] of s.trays) {
if (t.position.at !== 'grid') continue;
@@ -687,7 +731,20 @@ export function describeIntent(s: GameState, i: Intent): string {
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);
if (dest && dest.couples.length > 0) {
picks = ` — couples ${carsLabel(dest.couples)} on the way${i.reverse ? ' (behind)' : ' (onto the nose)'}`;
/**
* NAME THE CARS THE CREW SET OUT HERE SEPARATELY. They are at the front of `couples` — the
* walk seeds itself with the cut at the end the train pulls out through — and a button
* reading "couples 2 cars" over cars the player put down thirty seconds ago is exactly the
* surprise this label exists to prevent, running the other way.
*/
const own = ownCutFor(s, playerAtSeat(s, tray!.position.at === 'grid' ? tray!.position.seat : 0), i.trayId, i.reverse).length;
const end = i.reverse ? ' (behind)' : ' (onto the nose)';
picks =
own > 0
? ` — takes your own ${carsLabel(dest.couples.slice(0, own))} back off this card` +
(dest.couples.length > own ? `, then couples ${carsLabel(dest.couples.slice(own))} on the way` : '') +
end
: ` — couples ${carsLabel(dest.couples)} on the way${end}`;
}
}
return `move to ${at(i.to)}${i.reverse ? ' (reverse)' : ''}${picks}`;
@@ -768,6 +825,16 @@ export function describeIntent(s: GameState, i: Intent): string {
return `board passengers at ${at(i.at)}`;
case 'porter.detrain':
return `detrain passengers at ${at(i.at)}`;
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 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`;
}
case 'newTrain.placeCar':
// carLabel knows a caboose carries the crew, not freight. Formatting it here by hand put
// "add loaded caboose" on a button.
@@ -815,9 +882,13 @@ export function describeIntent(s: GameState, i: Intent): string {
// ABS Signals exists to prevent, but no such collision is implemented — granting clearance is
// currently free. Saying otherwise invents a consequence the engine will never deliver.
// See implications.md §10 Q13.
// THE TRAIN BEING RULED ON GOES ON THE BUTTON, not in the tooltip. `actionButton` splits a
// label at the first em-dash and shows only the head, so "ALLOW — Train 7 follows…" left the
// one thing the ruling is ABOUT — which train — behind a hover. Reported from play: the
// Superintendent could not tell which train he was clearing without pointing at the button.
return i.allow
? `ALLOW — ${who} follows ${ahead} onto the same Mainline card, closing up behind it`
: `HOLD — ${who} waits where it is, losing the Stage but keeping the line clear`;
? `ALLOW ${who} to follow ${ahead} — onto the same Mainline card, closing up behind it`
: `HOLD ${who} — it waits where it is, losing the Stage but keeping the line clear`;
}
case 'draw.fromDepartment': {
// Naming the card is the whole point of a FACE-UP pile: "Department 2" tells a player nothing,
@@ -933,7 +1004,8 @@ export function snapshot(
card.geometry.kind === 'office'
? { used: area.adOccupancy.length, of: officeProfile(area.tier).adTracks }
: null,
cars: (card.facility?.industryTrack.length ? card.facility.industryTrack.cars : card.standing).map(carLabel),
cars: carsOn(card).map(carLabel),
standingWest: standingWestOn(s, key, carsOn(card).length),
facility: fv,
});
}
@@ -1006,6 +1078,7 @@ export function snapshot(
...(n.absSignals ? ['ABS Signals'] : []),
],
gradeUp: isGrade ? (n.gradeUp ?? 'east') : null,
what: mainlineDescription(n.card, n.gradeUp ?? 'east'),
};
}
const oa = areaAtSeat(s, n.seat);
@@ -1458,7 +1531,7 @@ function cellDescription(card: TrackCard, officeName: string, onRunning: boolean
const where = onRunning
? ' · ON THE RUNNING TRACK — industries belong on a stub; a car left standing here is hit by the next arrival'
: '';
return `${flow} ${p.carTypes.join('/')} · spot a matching car on its siding to work a load${progress}${where}`;
return `${flow} ${p.carTypes.join('/')} · spot a matching car on its track to work a load${progress}${where}`;
}
case 'track':
switch (g.geometry) {