/** * Browser entry point — wires the DOM to a `Session`. * * Presentation only. Every question of what is legal, what it means, or what the board looks like * is answered by the engine or by the shared view helpers. */ 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 { TOOLTIP_CSS, installTooltips } from './tooltip.ts'; import { playCue } from './sound.ts'; import { MOVES_PER_LOCAL_OPS } from '../engine/content.ts'; import type { LocalSession } from './session.ts'; import { createLocalSession } from './session.ts'; const SAVE_KEY = 'station-master.save.v1'; /** * The game, behind the Session boundary. * * Typed as `LocalSession` because this page is the solitaire client and uses undo, local saves and * new-game — all of which are local-only. The parts that draw and submit go through the plain * `Session` surface, which is what a remote client will provide unchanged. */ let session: LocalSession; /** Which card or track piece is picked, waiting for a location. */ let selected: string | null = null; /** * WHAT the picked card is being used for. * * The hand is the action surface, and a card has two verbs: play it onto the board, or discard it * onto a Department. Both then ask "where?", and the answer is highlighted in place — squares on the * board for a play, the three Department piles for a discard. Without this the two flows would need * two selections, which is the thing being removed. */ let mode: 'play' | 'discard' | null = null; /** A square picked on the board, waiting for a rotation. */ let pendingAt: string | null = null; /** * AUTO-FOCUS on the district. * * It is only worth the vertical space during the phases that change it — Local Operations, where * cards and track are placed and the crew switches, and Cargo, where loads move. During New Train, * Mainline and Supervisor Shift nothing in the district moves and the Division map is what matters. * * 'auto' follows the phase; 'open' and 'closed' are the player overriding it and stay put until * they change it again. Display only — in a multiplayer game two players may reasonably want it * set differently, so this must never become part of game state. */ let districtMode: 'auto' | 'open' | 'closed' = 'auto'; /** * Sound, OFF until asked for. * * Everything it plays is synthesised rather than recorded, so it is a placeholder for real audio * rather than the finished thing — and a playtester who did not ask for noise should not get any. * One click in the title bar turns it on, and that click is also the gesture browsers require * before any audio may start. */ let soundOn = false; /** * The phase the page last drew, so a change of phase can be announced. * * Local Operations ends the moment the last Move is spent, and New Train and Mainline then run * themselves — so a player looking at the board finds themselves in Cargo with no idea their turn * ended or what happened in between. Reported exactly that way. */ let lastPhase: string | null = null; const FOCUS_PHASES = new Set(['localOps', 'loadUnload']); const $ = (id: string): HTMLElement => { const el = document.getElementById(id); if (!el) throw new Error(`missing element: ${id}`); return el as HTMLElement; }; const esc = (s: string): string => s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] ?? c); /** * A DRAWING OF THE PIECE A PLACEMENT WOULD LAY. * * "Allows traffic from the east to travel west or turn to the south" is exact and still leaves a * player working out which way the leg will point once the card is down. Rendered by `officeSvg` — * the board's own renderer, on a one-card board — so the preview and the board cannot disagree about * what the piece looks like. The coordinate stamp and the RUNNING TRACK caption are stripped: they * belong to a position, and this is a card on its own. */ 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: '', }; return officeSvg([cell] as never, 99).replace( /]*>[^<]*<\/text>/g, '', ); } // --------------------------------------------------------------------------- /** * THE TURN CHART — the five phases of a Stage, in order, with the current one lit. * * Built by `turnChartHtml`, shared with both replay viewers, so all three screens report where you * are in the Day the same way and with the same violet highlight. It used to live here alone. */ function renderTurnChart(f: Frame): void { const actorName = f.actor === null ? null : (f.players[f.actor]?.name ?? null); $('turnchart').innerHTML = turnChartHtml(f, actorName); } function start(): void { const params = new URLSearchParams(location.search); const requested = params.get('seed'); // A seed in the URL makes a game shareable and reproducible: same link, same deal. const seed = requested !== null ? Number(requested) || 1 : Math.floor(Math.random() * 1e9); session = createLocalSession(seed); const saved = load(); if (saved && requested === null) session.restore(saved); applyCapabilities(); // Every render goes through the session, so the page redraws whenever the game says it changed — // which is what a remote session will use to push. Locally it fires on each accepted intent. session.subscribe(render); render(); } /** * Hide the controls this session does not offer. * * Undo, a local save and dealing a new game are all things only a local session can do — a server * cannot un-see what the other players have already seen, the server is the store, and dealing is * the lobby's job. Hidden rather than disabled: a greyed-out Undo in a multiplayer game invites the * question "why not?" every turn, and the honest answer is that the control does not belong there. */ function applyCapabilities(): void { const c = session.capabilities; const hide = (id: string, on: boolean): void => { const el = document.getElementById(id); if (el) el.hidden = !on; }; hide('undo', c.undo); hide('savefile', c.saveLocal); hide('newgame', c.newGame); } function render(): void { const f = session.view(); const menu = session.menu(); // Which squares the selected card or track piece may go on. Highlighting them is what turns the // coordinate list into a board: you pick the thing, then click where it goes. // Squares light up only while a card is picked FOR PLAY. `selected` names the card; the placeable // entry that carries its squares is keyed the same way the menu keys it. const forPlay = mode === 'play' && selected !== null ? menu.hand.find((h) => `hand:${h.cardId}` === selected) : undefined; const chosen = forPlay ? menu.placeable.flatMap((g) => g.items).find((it) => it.subjectKey === forPlay.placeKey) : undefined; // A spot with no coordinate is not on this board — ABS Signals goes out on the Mainline — so it // is chosen from the action list and lights nothing in the district. const spotsAt = new Map(); for (const sp of chosen?.spots ?? []) { if (sp.coord === null) continue; const key = `${sp.coord.row},${sp.coord.col}`; spotsAt.set(key, [...(spotsAt.get(key) ?? []), sp]); } renderTurnChart(f); $('revenue').textContent = String(f.revenue); /** * THE OBJECTIVE, WITHOUT THE COMMENTARY. * * It used to read "3 of 20 · 2 Days left · behind the pace (expected 8)". The score, the target and * the Days left are what a player steers by; the pace verdict and the engine's guess at what the * score ought to be were an opinion taking up the one line that must not wrap — and the expected * figure came from a target that is itself an open question. */ const obj = $('objective'); obj.textContent = `${f.revenue} of ${f.objective.target} · ${f.objective.daysLeft} Day${f.objective.daysLeft === 1 ? '' : 's'} left`; obj.className = 'pace'; $('seed').textContent = String(session.seed()); // -- division $('division').innerHTML = divisionSvg(f.division); // -- board. Both renderers are shared with the replay so the two can never draw different // pictures of the same position. const grid = $('grid'); // The empty squares a legal placement would extend the district onto. Drawn by `officeSvg` in the // same pass so they share its origin and its canvas: a target outside the canvas is a legal move // the player cannot click. const ghostCoords = [...spotsAt.keys()] .filter((k) => !f.cells.some((c) => `${c.row},${c.col}` === k)) .map((k) => { const [gr, gc] = k.split(',').map(Number); return { row: gr!, col: gc! }; }); /** * WHAT PLAYING ON AN OCCUPIED SQUARE WOULD DO. * * Three different acts light up the same blue: building on empty ground, EXTENDING the Running * Track at a Limits sign (the sign moves outward with the card — the only way a district grows * along the main), and ATTACHING an Enhancement to a card already down. The first says "place * here" on a ghost card; the other two said nothing at all, which is why the Depot lighting up * read as a bug rather than as an offer. */ const legalCaps = [...spotsAt.keys()].flatMap((k) => { const cell = f.cells.find((c) => `${c.row},${c.col}` === k); if (!cell) return []; const label = cell.kind === 'limits' ? 'EXTEND THE RUNNING TRACK HERE' : cell.kind === 'office' ? 'ATTACH TO YOUR OFFICE' : 'ATTACH TO THIS CARD'; return [{ row: cell.row, col: cell.col, label }]; }); grid.innerHTML = officeSvg(f.cells, f.runningRow, ghostCoords, legalCaps); // Highlighting rides on top of the drawing: outline the legal squares and make them clickable. for (const [key, list] of spotsAt) { const [gr, gc] = key.split(',').map(Number); const g = grid.querySelector(`g[data-cell="${gr},${gc}"]`); if (g) { g.classList.add('bs-legal'); (g as unknown as HTMLElement).onclick = () => pick(key, list); } } // Wire the targets. They are already in the SVG, so nothing is re-serialised here. for (const [key, list] of spotsAt) { if (f.cells.some((c) => `${c.row},${c.col}` === key)) continue; const g = grid.querySelector(`g[data-ghost="${key}"]`); if (g) (g as unknown as HTMLElement).onclick = () => pick(key, list); } /** * THE SWITCHING MOVE, ON THE BOARD. * * Every switching decision is about geography — which card the crew can reach, what it will couple * on the way, whether it can get back — and none of it was drawn: the moves were text buttons * reading "move to (0, -2)". The classes and the replay viewer have highlighted a position for * months; the play page simply never used them. * * WHERE IT IS, WHERE IT MAY GO, AND WHY NOT THE REST. A blocked card carries its reason in its own * tooltip, so "why can I not get into that industry?" is answered by hovering the industry. */ if (f.moves && !forPlay) { const here = grid.querySelector(`g[data-cell="${f.moves.from.row},${f.moves.from.col}"]`); if (here) here.classList.add('bs-from'); for (const c of f.moves.to) { const g = grid.querySelector(`g[data-cell="${c.row},${c.col}"]`); if (g) g.classList.add('bs-focus'); } for (const b of f.moves.blocked) { const g = grid.querySelector(`g[data-cell="${b.coord.row},${b.coord.col}"]`); if (!g) continue; // Two different things wearing two different marks. A turnout you cannot STOP on is not in // your way — you run through it — so it must not be drawn like an industry that is locked. const passable = b.kind === 'noStopping'; g.classList.add(passable ? 'bs-nostop' : 'bs-blocked'); const own = g.getAttribute('data-tip') ?? ''; const head = passable ? 'NO STOPPING HERE' : 'THE CREW CANNOT MOVE HERE'; g.setAttribute('data-tip', `${own}\n\n${head}: ${b.why}`); } } function pick(key: string, list: { label: string; index: number }[]): void { if (list.length === 1) { const intent = menu.options[list[0]!.index]; if (intent) void session.submit(intent); selected = null; pendingAt = null; } else { pendingAt = key; } render(); } // -- facilities $('facs').innerHTML = facilitiesHtml(f); // Name AND effect. A hand of names alone tells a player nothing about what they can do. // Name and status stay on the page; what the card DOES is reference detail, so it hovers. /** * THE HAND, AS THE ACTION SURFACE. * * Each card carries its own verbs. This used to be a read-only row, with the same cards appearing * again in the action list — once as subjects to play and once as one button per Department to * discard, which for a four-card hand was twelve buttons repeating three choices four times. */ $('hand').innerHTML = menu.hand.length ? menu.hand .map((h) => { const canPlace = h.placeKey !== null && h.spots > 0; const canPlay = canPlace || h.playNow !== null; const canDiscard = h.discard.some((d) => d !== null); const picked = selected === `hand:${h.cardId}`; const verb = (kind: string, on: boolean, text: string, tip: string): string => on ? `` : ''; // A track card shows what it would look like on the board, in every orientation it has — // which is how a player sees a turnout has two at all, and what a curve actually is. const fig = h.shapes.length ? ` data-tip-html="${esc(h.shapes.map((l) => piecePreview(l, h.name)).join(''))}"` : ''; // The card just drawn, badged so it can be told from the two beside it. It stands until // another draw replaces it, rather than flashing once — the question a player asks looking // at the row is "which of these is new", not "did something happen". const fresh = h.cardId === session.justDrawn(); return ( `
` + `${esc(h.name)}` + `
` + verb( 'play', canPlay, canPlace ? `play ${h.spots}` : 'play', canPlace ? `Play it onto the board — ${h.spots} square${h.spots === 1 ? '' : 's'} will light up.` : 'Play it. This card needs no square on the board.', ) + verb('discard', canDiscard, 'discard', 'Discard it face up on top of a Department — pick which one.') + `
` ); }) .join('') : 'empty'; /** * THE THREE DEPARTMENT PILES, and how deep each one is. * * They are decks, not single face-up cards: a discard goes on TOP of the one its owner chooses, so * a pile is a card being offered with a history of cards buried under it. Only the top may be * taken, which makes the depth real information — a deep pile is where cards have been put beyond * reach. Drawn like the hand so they read as cards, dashed and unlit because taking one is a draw * action rather than a click on the card itself. */ $('depts').innerHTML = pilesHtml(f); renderYards(f); // -- the hand's verbs. Picking one selects the card and says what it is for; the "where" is then // highlighted in place, on the board or on the Department piles. for (const b of Array.from($('hand').querySelectorAll('button.cardact'))) { const node = b as HTMLElement; node.onclick = () => { const cardId = node.dataset['card']!; const verb = node.dataset['verb'] as 'play' | 'discard'; const entry = menu.hand.find((h) => h.cardId === cardId); if (!entry) return; // A card that needs no square goes straight down; there is nothing to ask. if (verb === 'play' && entry.placeKey === null && entry.playNow !== null) { const intent = menu.options[entry.playNow]; if (intent) void session.submit(intent); selected = null; mode = null; pendingAt = null; render(); return; } const key = `hand:${cardId}`; const same = selected === key && mode === verb; selected = same ? null : key; mode = same ? null : verb; pendingAt = null; render(); }; } // -- discarding: the three Department piles become the targets. They already show their top card // and their depth, which is exactly what you choose between. const discarding = mode === 'discard' && selected !== null ? menu.hand.find((h) => `hand:${h.cardId}` === selected) : undefined; if (discarding) { // Dim the piles that are not targets, so the three that are read as a choice being offered // rather than as four cards that happen to be there. $('depts').classList.add('aiming'); for (const el of Array.from($('depts').querySelectorAll('[data-dept]'))) { const node = el as HTMLElement; const slot = Number(node.dataset['dept']); const index = discarding.discard[slot]; if (index === null || index === undefined) continue; node.classList.add('target'); node.onclick = () => { const intent = menu.options[index]; if (intent) void session.submit(intent); selected = null; mode = null; render(); }; } } else { $('depts').classList.remove('aiming'); } // -- making up a train: the Division Yard chip that shows the car IS the button. if (menu.makeUp) { for (const el of Array.from($('divyard').querySelectorAll('[data-car]'))) { const node = el as HTMLElement; const car = menu.makeUp!.cars.find( (c) => c.carType === node.dataset['car'] && c.loaded === (node.dataset['loaded'] === '1'), ); if (!car) continue; node.classList.add('addable'); node.onclick = () => { const intent = menu.options[car.index]; if (intent) void session.submit(intent); render(); }; } } /** * THE TIMETABLE, with the slot the die just filled flashed. * * `scheduled` is cleared as it is consumed, so the flash marks the moment rather than the state — * it is gone by the next render, which is what makes it read as "that just happened". */ // Draining: the flash marks the moment the die was read, not a state, so it is gone by the next // render. Taken once here and handed to both the timetable and the action panel. const justSet = session.takeScheduled(); $('timetable').innerHTML = timetableHtml(f, justSet); $('blocked').innerHTML = blockedHtml(f); // -- log const log = $('log'); log.innerHTML = session.lines() .slice(-60) .map((l) => `
${esc(l.text)}
`) .join(''); log.scrollTop = log.scrollHeight; /** * SAY WHEN THE PHASE TURNS OVER. * * The five phases run themselves once Local Operations ends, so the page can change out from under * a player between one click and the next. The turn chart already shows WHERE you are; this says * that it moved, which is the part you miss when you were looking at the board. */ if (lastPhase !== null && lastPhase !== f.phaseKey) { const el = $('phasenote'); el.textContent = `${f.phase} — Day ${f.day}, Stage ${f.stage}`; el.className = 'shown'; window.setTimeout(() => { if (el.textContent?.startsWith(f.phase)) el.className = ''; }, 2600); } lastPhase = f.phaseKey; renderDistrict(f); renderActions(menu, f, justSet); renderUndo(); // Drain whatever the last batch of events earned. Cleared either way, so turning sound on does // not then play a backlog of everything that happened while it was off. const cues = session.takeCues(); if (soundOn) for (const c of cues) playCue(c); save(); } /** * UNDO, as far back as you like. * * The game is a seed and a list of intents, so stepping back is replaying without the last one — * see `undo()` in game.ts. The button says how many moves are behind you, because "can I still get * back?" is the question it exists to answer; it goes quiet when there is nothing to take back. * * The whole page is re-rendered from the rebuilt game, including the history panel, so nothing on * screen is left describing a move that no longer happened. Any card picked up mid-choice is * dropped: the position it was going to be played into may not exist any more. */ function renderUndo(): void { const btn = document.getElementById('undo') as HTMLButtonElement | null; if (!btn || !session.capabilities.undo) return; const n = session.steps(); btn.disabled = n === 0; btn.textContent = n === 0 ? 'Undo' : `Undo (${n})`; btn.onclick = () => { // The session drops the rebuilt game's cues and draws — replaying the history re-records them, // and none of it is news to a player who just stepped back. if (!session.undo()) return; selected = null; mode = null; pendingAt = null; // 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; }; } /** * The two yards, and how close the Division Yard is to running out. * * §2 — used Rolling Stock is set out in the Classification Yard, and it only returns when the * Division Yard is BARE. So the interesting number is not how much has been used but how little is * left, and the moment the Division Yard empties a whole pile comes back at once. */ function renderYards(f: Frame): void { $('divyard').innerHTML = yardHtml(f.yards.division); $('clsyard').innerHTML = yardHtml(f.yards.classification); $('divtot').textContent = `${f.yards.divisionTotal} cars`; $('clstot').textContent = `${f.yards.classificationTotal} cars`; // The one thing worth calling out: the yard about to turn over. const bare = f.yards.divisionTotal === 0; $('divyard').classList.toggle('bare', bare); $('yardnote').textContent = bare ? `The Division Yard is bare — the ${f.yards.classificationTotal} cars in Classification return to it now.` : 'loaded / empty. Classification returns to the Division Yard only when the Division Yard is bare.'; } function renderDistrict(f: Frame): void { const open = districtMode === 'auto' ? FOCUS_PHASES.has(f.phaseKey) : districtMode === 'open'; const sec = $('district'); if (open) sec.classList.remove('folded'); 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; $('districtsummary').textContent = `${f.cells.length} cards · ${f.facilities.length} facilities · ${cars} cars standing` + (crew > 0 ? ` · ${crew} crew on the board` : ''); // Say what pressing it DOES, not what the panel is currently doing. "auto · folded" reads as a // status line and was missed entirely; "always show" is an instruction. const btn = $('districttoggle'); btn.textContent = districtMode === 'auto' ? (open ? 'auto-hide: on — click to keep open' : 'auto-hide: on — click to show') : districtMode === 'open' ? 'always showing — click for auto-hide' : 'always hidden — click for auto-hide'; btn.onclick = () => { // auto -> pin it to the opposite of what auto is doing -> back to auto. districtMode = districtMode === 'auto' ? (open ? 'closed' : 'open') : 'auto'; render(); }; } function renderActions( menu: Menu, f: Frame, justSet: number | null, ): void { const el = $('actions'); if (f.status !== 'active') { const o = f.outcome; el.innerHTML = `
` + `${o?.result === 'win' ? 'YOU WIN' : 'GAME OVER'} — ${esc(String(o?.reason ?? ''))}
` + `final Revenue ${f.revenue} against a target of ${f.objective.target}
` + ``; $('again').onclick = () => { clearSave(); location.search = ''; }; return; } if (menu.direct.length === 0 && menu.placeable.length === 0) { el.innerHTML = '
nothing to decide — the engine is running the Division
'; return; } const apply = (index: number): void => { const intent = menu.options[index]; if (intent) void session.submit(intent); selected = null; mode = null; pendingAt = null; render(); }; /** * A long label is two things: the action, and why it is offered. Put the first on the button and * the second on the tooltip, or the list crowds out the board. * * AND IF THE LABEL CARRIES NO EXPLANATION, ask the card. Tooltips used to depend entirely on a * label happening to contain an em-dash, so an action naming a card could have none at all while * 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 { 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 ( `` ); }; /** * MOVES LEFT, WHERE THE MOVES ARE. * * §6.1 gives six Moves a turn and every switching decision is really "can I still get back?" — so * the count belongs beside the buttons. It was reported only in the history panel, which is the * one place a player is not looking while switching. */ /** * WHAT THE DIE DID, said where the player is looking. * * Playing a train card rolls 1D12 for its departure Stage, and the card simply left the hand — the * answer arrived only in the history panel, one line among many. The timetable now shows it and * flashes the slot; this says it in words at the same moment. */ const scheduledNote = justSet !== null && f.timetable[justSet] != null ? `
` + `Train ${f.timetable[justSet]} is scheduled to depart at Stage ${justSet + 1} — see the Timetable
` : ''; const movesNote = f.movesLeft !== null ? `
` + `${f.movesLeft} of ${MOVES_PER_LOCAL_OPS} Moves left
` : ''; // A heading over the buttons, so the panel says what it is before it says what is in it. The // list below is already phase-specific: it comes from `legalActions`, so in the Cargo phase with // no worker able to act, the only thing offered is "End my Cargo phase". let html = `

Actions

${scheduledNote}${movesNote}`; /** * WHAT IS LEFT IN THE ACTION LIST. * * 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. */ html += menu.direct .filter((g) => !/^(Play|Discard) a card from my hand$/.test(g.title) && !/^Making up /.test(g.title)) .map( (g) => `

${esc(g.title)}

` + g.actions .map((a) => { // §6.2 — a drawn card has to be played or discarded before the turn can end. Keyed on // the INTENT, not the label: matching button text would break the moment the wording // changed, and would have caught `switch.end` too. return actionButton(a); }) .join('') + `
`, ) .join(''); /** * MAKING UP A TRAIN. * * The cars are added from the Division Yard chips, but the panel still has to exist: it names the * train and what its card calls for, and it carries the "no more cars" button, which is the ONLY * way to finish when the yard holds nothing the train may take. * * Moving the cars onto the yard chips without this left a train being made up with no control on * screen at all whenever no chip was addable — a hard softlock, reported at Stage 10 of seed * 775569289 with Train 10 waiting at the West Division Point. */ if (menu.makeUp) { const addable = menu.makeUp.cars.length; html += `

${esc(menu.makeUp.title)}

` + `
` + (addable > 0 ? `Click a car in the Division Yard below to add it — ${addable} kind${addable === 1 ? '' : 's'} it may take are highlighted there.` : menu.makeUp.pass !== null ? 'The Division Yard is bare, so there is nothing to add. Send the train out as it stands.' : 'Nothing in the Division Yard may join this train, and §7 does not allow passing while the yard holds cars.') + `
` + (menu.makeUp.pass !== null ? `` : '') + `
`; } /** * The card is picked in the hand and the square on the board, so all that is left here is the * ROTATION — the one question neither of those can ask, and only for the card actually picked. */ const picked = mode === 'play' && selected !== null ? menu.hand.find((h) => `hand:${h.cardId}` === selected) : undefined; for (const group of menu.placeable) { const relevant = group.items.filter((it) => picked && it.subjectKey === picked.placeKey); if (relevant.length === 0) continue; html += `

${esc(group.title)}

`; for (const item of relevant) { { // Once a square is picked, show only that square's rotations — the rest is noise. const shown = pendingAt ? item.spots.filter((sp) => sp.coord !== null && `${sp.coord.row},${sp.coord.col}` === pendingAt) : item.spots; html += `
` + (pendingAt ? `choose a rotation for (${esc(pendingAt.replace(',', ', '))}):` : 'click a highlighted square, or:') + `
` + shown .map((sp) => { // The picture rides on the button that would lay it, so hovering a rotation shows // that rotation — which is the question "which of these two do I want?" answered. const fig = sp.links.length ? ` data-tip-html="${esc(piecePreview(sp.links, item.subject))}"` : ''; return ( `` ); }) .join('') + `
`; } } html += `
`; } if ( f.phaseKey === 'localOps' && f.option === 'draw' && !menu.options.some((i) => i.type === 'draw.end') ) { // The hand being counted is the ACTOR's — they are the one who cannot end the turn. const hand = f.handCount; html += `
`; } el.innerHTML = html; for (const b of Array.from(el.querySelectorAll('button.act'))) { const node = b as HTMLElement; node.onclick = () => apply(Number(node.dataset['i'])); } } // --------------------------------------------------------------------------- // Saving. localStorage only — nothing leaves the browser. // --------------------------------------------------------------------------- /** * Write the game out as a file. * * The save IS the replay: a seed and the moves made, which the engine can replay exactly. A few * hundred bytes, so a finished game can be emailed or dropped on the site's replay directory — * where a rendered page would have been megabytes. */ function downloadSave(): void { const data = JSON.stringify(session.save(), null, 1); const blob = new Blob([data], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `station-master-seed${session.seed()}-day${session.view().day}.json`; a.click(); URL.revokeObjectURL(url); } function save(): void { if (!session.capabilities.saveLocal) return; try { localStorage.setItem(SAVE_KEY, JSON.stringify(session.save())); } catch { // A full or disabled localStorage must not take the game down with it. } } function load(): Save | null { try { const raw = localStorage.getItem(SAVE_KEY); return raw ? (JSON.parse(raw) as Save) : null; } catch { return null; } } function clearSave(): void { try { localStorage.removeItem(SAVE_KEY); } catch { /* nothing to do */ } } // BOTH stylesheets. The board is SVG built by the shared renderers, and every shape it draws is // styled by class — without BOARD_CSS each rect falls back to a black fill on a near-black // background, so the cards are drawn correctly and are simply invisible. const pageStyle = document.createElement('style'); pageStyle.textContent = BOARD_CSS + TOOLTIP_CSS + TURNCHART_CSS + PANEL_CSS; document.head.appendChild(pageStyle); installTooltips(); const saveBtn = document.getElementById('savefile'); if (saveBtn) saveBtn.onclick = downloadSave; /** * Forget the saved game and deal a fresh one. * * The only way out used to be finishing the game — `start()` restores from localStorage on every * load, so a game you no longer wanted followed you across reloads, and the "new game" button * appeared solely on the game-over screen. Confirmed because it throws the whole game away — Undo * steps back one action at a time, but nothing brings back a game that has been dealt over, and the * replay download is right beside it. * * `location.search = ''` rather than a direct re-render, so a `?seed=` in the URL goes too — leaving * it would deal the same game again and look like the button had done nothing. */ const newBtn = document.getElementById('newgame'); if (newBtn) { newBtn.onclick = () => { const f = session.view(); const day = f.day; const started = f.status === 'active' && (day > 1 || f.stage > 1); if (started && !confirm(`Forget this game (seed ${session.seed()}, Day ${day}) and deal a new one?`)) return; /** * ASK FOR THE SEED, rather than documenting a URL parameter in the title bar. * * The same deal can be replayed, shared or compared by seed, which is worth offering — it was * offered as the note "add ?seed=1234 for a set deal", which spent width on the one line that * must not wrap to explain a thing the button could simply ask. Blank means random. */ const asked = prompt('Seed for the new game — leave blank for a random one:', ''); if (asked === null) return; // cancelled clearSave(); const wanted = asked.trim(); if (wanted === '') { // No `?seed=`, so `start()` rolls one. Reload rather than re-render, to clear any seed in the URL. if (location.search === '') location.reload(); else location.search = ''; return; } location.search = `?seed=${encodeURIComponent(wanted)}`; }; } const soundBtn = document.getElementById('sound'); if (soundBtn) { const paint = (): void => { soundBtn.textContent = soundOn ? '\u{1F50A} sound' : '\u{1F507} muted'; }; soundBtn.onclick = () => { soundOn = !soundOn; paint(); // Confirm the change audibly — the one press where a sound is unambiguously wanted, and it // doubles as the user gesture the browser needs before any audio may start. if (soundOn) playCue('stage'); }; paint(); } start();