Show the bot's reasoning and rejected options in the replay

This commit is contained in:
Jesse
2026-07-31 15:22:45 -04:00
parent d261ad7af8
commit 160190da3f
3 changed files with 328 additions and 49 deletions
+195 -5
View File
@@ -23,10 +23,11 @@ import { applyIntent, areaOf, facilityCarType, laborersLeft, portersLeft } from
import type { GameLength } from '../engine/content.ts';
import { MAINLINE_PROFILES, lengthProfile, officeProfile } from '../engine/content.ts';
import type { GameEvent } from '../engine/events.ts';
import type { Intent } from '../engine/intents.ts';
import { legalActions } from '../engine/legal.ts';
import { createGame } from '../engine/setup.ts';
import type { GameConfig, GameState } from '../engine/state.ts';
import { developerBot } from './bot.ts';
import type { Facility, GameConfig, GameState } from '../engine/state.ts';
import { developerBot, lastChoiceReason } from './bot.ts';
import type { Impediment } from './narrate.ts';
import { carLabel, clockTime, idleNote, impediments, isVisible, narrate, phaseLabel } from './narrate.ts';
@@ -58,6 +59,14 @@ export type FacilityView = {
trackCap: number;
laborers: string;
porters: string;
/**
* Can a load actually come off WORK onto a spotted car (§9.3)? A load with nowhere to go parks on
* WORK and LOCKS the industry track, blocking the very car that would clear it — the deadlock
* that held freight to a 3% completion rate.
*/
canFinish: boolean;
/** A load is sitting on WORK with no spotted car to receive it. */
jammed: boolean;
};
export type TrainChip = { label: string; consist: string[] };
@@ -85,6 +94,26 @@ export type Frame = {
timetable: (number | null)[];
blocked: Impediment[];
trains: { label: string; where: string }[];
/** What the bot chose here, why, and what it passed over. Null on engine-driven frames. */
decision: Decision | null;
/** A Local Operations turn that changed nothing — the frames worth your attention. */
wasted: boolean;
};
/**
* The choice behind a frame.
*
* The whole point is `rejected`: the replay could always show what happened, never what COULD have
* happened, so a daft move was visible but the alternatives it passed over were not — which is
* exactly what you need to say what it should have done instead.
*/
export type Decision = {
actor: number;
chose: string;
why: string;
/** Every legal option not taken, grouped by kind with a count. */
rejected: { kind: string; count: number; detail: string }[];
totalOptions: number;
};
// ---------------------------------------------------------------------------
@@ -124,14 +153,116 @@ function facilityView(
trackCap: f.industryTrack.length,
laborers: `${laborersLeft(f)}/${f.laborers}`,
porters: `${portersLeft(f)}/${f.porters}`,
canFinish: canFinishHere(f),
jammed: f.menAtWork.some((l) => l !== null) && !canFinishHere(f),
};
}
/** Is a car spotted that a load on WORK could actually come off onto (§9.3)? */
function canFinishHere(f: Facility): boolean {
const pending = f.menAtWork.find((l) => l !== null) ?? f.outboundBox[0];
if (!pending) return false;
return f.industryTrack.cars.some((c) => !c.loaded && c.type === pending.type);
}
/**
* Summarise the choice: what was taken, why, and what was passed over.
*
* Options are grouped by kind because a switching turn can offer 40 destinations, and a list that
* long hides the shape of the decision rather than showing it.
*/
function describeDecision(
s: GameState,
actor: number,
chosen: Intent,
options: Intent[],
why: string,
): Decision {
const groups = new Map<string, Intent[]>();
for (const o of options) {
if (o === chosen) continue;
const list = groups.get(o.type) ?? [];
list.push(o);
groups.set(o.type, list);
}
const rejected = [...groups.entries()]
.map(([kind, list]) => ({ kind, count: list.length, detail: sampleDetail(s, kind, list) }))
.sort((a, b) => b.count - a.count);
return { actor, chose: describeIntent(s, chosen), why, rejected, totalOptions: options.length };
}
/** A short, concrete example of what a group of rejected options would have done. */
function sampleDetail(s: GameState, kind: string, list: Intent[]): string {
// Deduplicate by DESCRIPTION. Orientation variants and repeated copies of a card describe
// identically, so the raw list reads "play Overpass at (0,0)" three times over and hides the
// actual range of choices — the opposite of what this panel is for.
const seen = new Set<string>();
for (const i of list) seen.add(describeIntent(s, i));
const unique = [...seen];
const shown = unique.slice(0, 4);
const more = unique.length - shown.length;
return shown.join('; ') + (more > 0 ? ` … and ${more} more distinct` : '');
}
/** One readable line for a single intent. */
function describeIntent(s: GameState, i: Intent): string {
const at = (c: { row: number; col: number }): string => `(${c.row},${c.col})`;
switch (i.type) {
case 'localOps.choose':
return `choose ${i.option}`;
case 'card.play':
return `play ${cardName(s, i.cardId)}${i.placement ? ` at ${at(i.placement)}` : ''}`;
case 'card.discard':
return `discard ${cardName(s, i.cardId)}`;
case 'track.lay':
return `lay ${i.hand === 'none' ? '' : i.hand + '-hand '}${i.geometry} at ${at(i.placement)}`;
case 'switch.move':
return `move to ${at(i.to)}${i.reverse ? ' (reverse)' : ''}`;
case 'switch.dropCars':
return `drop ${i.count} car(s)`;
case 'switch.sortConsist':
return `re-order consist [${i.order.join(',')}]`;
case 'freightAgent.stockOutbound':
return `stock a ${i.carType} at ${at(i.at)}`;
case 'freightAgent.unjam':
return `unjam ${i.from} at ${at(i.at)}`;
case 'freightAgent.clearInbound':
return `clear red box at ${at(i.at)}`;
case 'laborer.startLoad':
return `start a load at ${at(i.at)}`;
case 'laborer.advanceLoad':
return `advance load in box ${i.box} at ${at(i.at)}`;
case 'laborer.beginUnload':
return `begin unloading car ${i.carIndex} at ${at(i.at)}`;
case 'porter.board':
return `board passengers at ${at(i.at)}`;
case 'porter.detrain':
return `detrain passengers at ${at(i.at)}`;
case 'newTrain.placeCar':
return `add ${i.loaded ? 'loaded' : 'empty'} ${i.carType}`;
case 'mainline.modify':
return `${cardName(s, i.cardId)} on Mainline card ${i.node}`;
case 'maneuver.redFlags':
return `Red Flags on ${i.trayId}`;
case 'maneuver.flyingSwitch':
return `Flying Switch ${i.count} car(s) into ${at(i.to)}`;
case 'mainline.clearance':
return i.allow ? 'grant clearance' : 'refuse clearance';
case 'draw.fromDepartment':
return `draw the face-up card in slot ${i.slot + 1}`;
default:
return i.type;
}
}
function snapshot(
s: GameState,
lines: { text: string; tone: string }[],
where: { row: number; col: number } | null,
whereFrom: { row: number; col: number } | null = null,
decision: Decision | null = null,
wasted = false,
): Frame {
const area = areaOf(s, 0);
const trayAt = new Map<string, string>();
@@ -218,6 +349,8 @@ function snapshot(
deck: s.decks.homeOffice.length,
departments: s.decks.departments.map((id) => (id ? cardName(s, id) : '—')),
timetable: [...s.timetable],
decision,
wasted,
blocked: impediments(s, 0),
trains: [...s.trays.values()].map((t) => ({
label: t.trainNumber === null ? 'local crew' : `Train ${t.trainIsExtra ? 'X' : ''}${t.trainNumber}`,
@@ -304,6 +437,8 @@ export function record(seed: number, length: GameLength, maxSteps = 100_000): Re
// Tracks whether a phase did anything, so an empty one can say so rather than ending silently.
let didSomething = false;
// The choice that produced the events about to be pushed.
let pendingDecision: Decision | null = null;
const push = (events: GameEvent[]): void => {
const visible = events.filter(isVisible);
@@ -328,7 +463,16 @@ export function record(seed: number, length: GameLength, maxSteps = 100_000): Re
const where = visible.map((e) => narrate(e, narrateCtx)).find((n) => n.where)?.where ?? null;
const moved = visible.find((e) => e.type === 'trayMoved');
const from = moved && moved.type === 'trayMoved' ? moved.from : null;
frames.push(snapshot(s, lines, where ?? null, from));
const d = pendingDecision;
pendingDecision = null;
// A Local Operations turn that ended with nothing but the turn ending is a wasted action —
// six Moves and a card play spent on nothing. Among 600+ frames these are invisible unless
// marked, and they are the ones worth reviewing.
const wasted =
d !== null &&
(d.chose === 'switch.end' || d.chose === 'draw.end' || d.chose === 'loadUnload.end') &&
visible.every((e) => e.type === 'phaseEnded' || e.type === 'actorChanged');
frames.push(snapshot(s, lines, where ?? null, from, d, wasted));
};
frames.push(
@@ -345,8 +489,11 @@ export function record(seed: number, length: GameLength, maxSteps = 100_000): Re
if (actor === null) break;
const options = legalActions(s, actor);
if (options.length === 0) break;
const applied = applyIntent(s, actor, developerBot.choose(s, actor, options));
const chosen = developerBot.choose(s, actor, options);
const decision = describeDecision(s, actor, chosen, options, lastChoiceReason());
const applied = applyIntent(s, actor, chosen);
if (!applied.ok) break;
pendingDecision = decision;
push(applied.events);
}
@@ -432,6 +579,17 @@ kbd{background:#2a3038;border:1px solid var(--line);border-radius:3px;padding:0
.mini .box{padding:0 4px;font-size:9.5px}
.cell.office{border-color:var(--clock)}
.cell.modifier{border-style:dashed;opacity:.85}
.chose{font-size:15px;margin-bottom:4px}
.why{font-style:italic;opacity:.85;margin-bottom:2px}
.rejected{list-style:none;margin:0;padding:0;max-height:210px;overflow:auto}
.rejected li{padding:3px 0;border-top:1px solid rgba(128,128,128,.25);font-size:12px}
.wasted{background:#b03030;color:#fff;font-weight:bold;padding:3px 6px;margin-bottom:5px;border-radius:3px}
.fstat{margin-top:4px;font-size:11px;padding:2px 5px;border-radius:3px;display:inline-block}
.fstat.good{background:rgba(40,140,60,.28)}
.fstat.bad{background:rgba(190,50,50,.38);font-weight:bold}
.fstat.idle{opacity:.6}
.wastedmark{color:#e06060;font-weight:bold}
</style></head><body>
<header>
@@ -455,6 +613,7 @@ kbd{background:#2a3038;border:1px solid var(--line);border-radius:3px;padding:0
</div>
<div>
<section><h2>What just happened</h2><div id="now"></div></section>
<section><h2>Decision — what it chose, and what it passed over</h2><div id="decision"></div></section>
<section><h2>Cards</h2>
<div><span class="dim">your hand:</span> <span id="hand">—</span></div>
<div style="margin-top:5px"><span class="dim">face-up Department slots:</span> <span id="depts">—</span></div>
@@ -468,7 +627,7 @@ kbd{background:#2a3038;border:1px solid var(--line);border-radius:3px;padding:0
<div class="legend">
<b>Keyboard:</b> <kbd>←</kbd>/<kbd>→</kbd> step · <kbd>space</kbd> play/pause ·
<kbd>Home</kbd>/<kbd>End</kbd> first/last · <kbd>S</kbd> next Stage · <kbd>R</kbd> next revenue change ·
<kbd>C</kbd> next collision.<br>
<kbd>C</kbd> next collision · <kbd>W</kbd> next wasted turn · <kbd>J</kbd> next jam.<br>
Running Track is the lighter row. <span class="chip">T4</span> is a train on the Division;
<span style="background:var(--warn);color:#0d1117;font-weight:700;border-radius:3px;padding:0 4px">🚂 T4</span>
is the crew in your yard — it carries the whole train with it as it moves, and a dashed outline
@@ -485,6 +644,8 @@ kbd{background:#2a3038;border:1px solid var(--line);border-radius:3px;padding:0
<button id="stage">next Stage ⏭</button>
<button id="money">next revenue 💰</button>
<button id="crash">next collision ⚠</button>
<button id="waste">next wasted turn 🗑</button>
<button id="jam">next jam 🔒</button>
<input type="range" id="scrub" min="0" value="0">
<select id="speed">
<option value="3000">extra slow</option>
@@ -585,9 +746,34 @@ function render() {
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>' +
'<div class="boxes"><span class="dim">siding</span>' + boxes(x.track, x.trackCap, 'g') + '</div>' +
'<div class="fstat ' + (x.jammed ? 'bad' : (x.canFinish ? 'good' : 'idle')) + '">' +
(x.jammed
? 'JAMMED — a load is on WORK with no car spotted to receive it; the industry track is locked'
: (x.canFinish
? 'ready — a matching empty car is spotted, so a load can finish'
: 'no car spotted — starting a load here would jam it')) +
'</div>' +
'</div>').join('');
$('now').innerHTML = f.lines.map((l) => '<div class="line t-' + l.tone + '">' + esc(l.text) + '</div>').join('');
var d = f.decision;
if (!d) {
$('decision').innerHTML = '<span class="dim">no choice here — the engine advanced on its own</span>';
} else {
var h = '';
if (f.wasted) h += '<div class="wasted">WASTED TURN — the whole action produced no change</div>';
h += '<div class="chose"><span class="dim">chose:</span> <b>' + esc(d.chose) + '</b></div>';
h += '<div class="why">why: ' + esc(d.why) + '</div>';
h += '<div class="dim" style="margin:6px 0 3px">passed over ' + (d.totalOptions - 1) +
' other legal option' + ((d.totalOptions - 1) === 1 ? '' : 's') + ':</div>';
if (d.rejected.length === 0) h += '<div class="dim">none — this was the only legal action</div>';
else h += '<ul class="rejected">' + d.rejected.map(function (r) {
return '<li><b>' + esc(r.kind) + '</b> <span class="dim">x' + r.count + '</span><br>' +
'<span class="dim">' + esc(r.detail) + '</span></li>';
}).join('') + '</ul>';
$('decision').innerHTML = h;
}
$('blocked').innerHTML = f.blocked.length === 0
? '<li class="dim">nothing blocked</li>'
: f.blocked.map((b) => '<li class="sev-' + b.severity + '"><b>' + esc(b.where) + '</b> — ' + esc(b.why) + '</li>').join('');
@@ -615,6 +801,8 @@ $('fwd').onclick = () => go(i + 1);
$('stage').onclick = () => findNext((f, p) => f.stage !== p.stage || f.day !== p.day);
$('money').onclick = () => findNext((f, p) => f.revenue !== p.revenue);
$('crash').onclick = () => findNext((f) => f.lines.some((l) => /COLLISION|collision/.test(l.text)));
$('waste').onclick = () => findNext((f) => f.wasted);
$('jam').onclick = () => findNext((f) => f.facilities.some((x) => x.jammed));
$('play').onclick = () => {
if (timer) { clearInterval(timer); timer = null; $('play').textContent = '▶ play'; return; }
$('play').textContent = '⏸ pause';
@@ -632,6 +820,8 @@ document.onkeydown = (e) => {
else if (e.key === 's' || e.key === 'S') $('stage').click();
else if (e.key === 'r' || e.key === 'R') $('money').click();
else if (e.key === 'c' || e.key === 'C') $('crash').click();
else if (e.key === 'w' || e.key === 'W') $('waste').click();
else if (e.key === 'j' || e.key === 'J') $('jam').click();
else if (e.key === ' ') { e.preventDefault(); $('play').click(); }
};
render();