Add the interface, then rebuild the economy around the first playtest

The MVP is playable: a turn screen, a career retrospective, an optional
feedback widget, local-storage autosave with file export/import, and a build
that flattens everything into one self-contained HTML file.

A turn has two phases — the scenario and its options, then what the choice did
and, separately, what the day cost regardless. Numbers that move without the
player seeing why are most of what makes them meaningless. Locked options are
shown greyed with the requirement spelled out rather than hidden, so a player
can see the door they cannot open yet.

The interface is named entirely by the pack. `pack.display` maps a state path to
a label, a format and an order, which is why the header reads "Standing" for a
path called `reputation` and why debt disappears while it is zero.

The first playtest then found three things, all of them fair.

*"Wasn't clear what daily drain was for."* The ledger was labelling changes by
the path that moved — "Money −$18" — when the upkeep entry that caused them had
a perfectly good name. It now says "Coffee, transit, lunch". The labels were in
the data the whole time and never reached the screen.

*"Should probably pay rent weekly / get paid every other week… would be good to
have day of week and week # shown."* Packs can now declare a calendar, and the
engine derives the day name, cycle and index from the turn number before the
event is drawn — so content can require a Friday and the header can say
"Thursday · Week 2 · Day 12". Upkeep entries take `every` and `offset`, making
wages fall on alternate Fridays and rent every Monday. The turn screen carries
a diary line — "Wages tomorrow · Rent in 4 days" — computed generically from
whatever a pack schedules.

*"Always in debt — could never get ahead."* The old economy bled $25 a day
regardless of play. It is now roughly break-even at baseline, with a
`spare_shift` event that appears *because* you are broke: the way out of a hole
should be visible from inside it. Across archetypes a careful player ends around
$1,400, an unplanned one treads water, and a careless one sinks into real debt.

That retune broke the coverage test, usefully. Random play stopped reaching hard
times at all, which made the entire debt branch look dead — it was not, since
random play is not a plausible player. Coverage is now the union across five
archetypes, including one that is broke *and* well-liked, because the "ask a
friend for money" options sit in a state no single-axis strategy reaches.

Not covered by any of this: styling and dark mode, which only a human with a
browser can check. This machine has none that can render a page.

109 tests. Reasoning in docs/DECISIONS.md §14-21.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VMSFHyVPitUoosW5wyEADj
This commit is contained in:
JesseMarkowitz
2026-09-10 04:44:49 -04:00
co-authored by Claude Opus 5
parent 1d4ac0fdbd
commit e482f07157
29 changed files with 2613 additions and 63 deletions
+39 -4
View File
@@ -17,19 +17,53 @@ export class MoveError extends Error {}
/** Draw the next event and record where the generator ended up. */
function advance(pack, state) {
const rng = createRng(state.meta.seed, state.meta.rngPosition ?? undefined);
const event = selectEvent(pack, state, rng);
// The calendar is settled before the draw, so an event can require a Friday.
const dated = applyCalendar(pack, state);
const rng = createRng(dated.meta.seed, dated.meta.rngPosition ?? undefined);
const event = selectEvent(pack, dated, rng);
if (!event) {
throw new ContentError(
`no event is eligible at stage "${state.stage}" on turn ${state.turn}; ` +
`no event is eligible at stage "${dated.stage}" on turn ${dated.turn}; ` +
'every stage needs at least one event with no conditions',
);
}
let next = setPath(state, 'meta.currentEventId', event.id);
let next = setPath(dated, 'meta.currentEventId', event.id);
next = setPath(next, 'meta.rngPosition', rng.getPosition());
return next;
}
/**
* Derive the calendar from the turn number.
*
* A pack that declares `calendar` gets `calendar.index` (position in the
* cycle), `calendar.cycle` (which cycle, 1-based) and `calendar.name` written
* into engine-owned state before the turn's event is chosen — so content can
* gate on the day of the week, and upkeep can charge rent on one of them. A
* pack that declares no calendar simply has none; the engine imposes no week.
*/
function applyCalendar(pack, state) {
const calendar = pack.calendar;
if (!calendar?.cycleLength) return state;
const elapsed = state.turn - 1;
const index = ((elapsed % calendar.cycleLength) + calendar.cycleLength) % calendar.cycleLength;
let next = setPath(state, 'calendar.index', index);
next = setPath(next, 'calendar.cycle', Math.floor(elapsed / calendar.cycleLength) + 1);
return setPath(next, 'calendar.name', calendar.unitNames?.[index] ?? null);
}
/**
* Whether a scheduled upkeep entry falls due this turn. `every` is a period in
* turns and `offset` the first turn it lands on (zero-based), so wages every
* fortnight starting on the seventh day are `{ every: 14, offset: 6 }`. An
* entry with no `every` runs every turn.
*/
function isDue(entry, state) {
if (!entry.every) return true;
const elapsed = state.turn - 1 - (entry.offset ?? 0);
return elapsed >= 0 && elapsed % entry.every === 0;
}
/**
* Apply the pack's per-turn upkeep — wages in, rent out, whatever a loan
* costs to carry. Each entry may carry its own conditions, evaluated after the
@@ -40,6 +74,7 @@ function applyUpkeep(pack, state, schema) {
let next = state;
const changes = [];
for (const entry of pack.upkeep ?? []) {
if (!isDue(entry, next)) continue;
if (!check(next, entry.requires).passed) continue;
const applied = applyEffects(next, entry.effects, schema);
next = applied.state;
+3 -1
View File
@@ -11,7 +11,8 @@ import { setPath } from './paths.js';
* day 10", "only if this event hasn't fired" — but may not declare or write
* them, which is what keeps engine bookkeeping from being corrupted by data.
*/
export const RESERVED_ROOTS = new Set(['turn', 'stage', 'seen', 'lastSeen', 'history', 'meta']);
export const RESERVED_ROOTS =
new Set(['turn', 'stage', 'seen', 'lastSeen', 'history', 'meta', 'calendar']);
/**
* Flatten a pack's state declarations into one path -> rule map, expanding the
@@ -51,6 +52,7 @@ export function createState(pack, { seed, schema = resolveSchema(pack) } = {}) {
stage: pack.startingStage,
seen: {},
lastSeen: {},
calendar: {},
history: [],
};
for (const [path, rule] of Object.entries(schema)) {
+19
View File
@@ -95,8 +95,27 @@ export function validatePack(pack) {
list.forEach(walk);
};
if (pack.calendar) {
const { cycleLength, unitNames } = pack.calendar;
if (!Number.isInteger(cycleLength) || cycleLength < 1) {
fail('calendar', `cycleLength ${cycleLength} must be a positive whole number`);
}
if (unitNames && unitNames.length !== cycleLength) {
fail('calendar', `unitNames has ${unitNames.length} entries but cycleLength is ${cycleLength}`);
}
}
(pack.upkeep ?? []).forEach((entry, index) => {
const where = `upkeep[${index}]${entry.label ? ` "${entry.label}"` : ''}`;
if (entry.every !== undefined && (!Number.isInteger(entry.every) || entry.every < 1)) {
fail(where, `every ${entry.every} must be a positive whole number of turns`);
}
if (entry.offset !== undefined && (!Number.isInteger(entry.offset) || entry.offset < 0)) {
fail(where, `offset ${entry.offset} must be zero or a positive whole number`);
}
if (entry.offset !== undefined && entry.every === undefined) {
warn(where, 'offset has no effect without every');
}
checkConditions(where, entry.requires);
if (!entry.effects?.length) fail(where, 'has no effects');
for (const effect of entry.effects ?? []) {
+30
View File
@@ -0,0 +1,30 @@
// Handing the player a file.
//
// Object URLs are revoked on the next frame rather than immediately: Safari
// has historically cancelled the download if the URL goes away too soon.
export function downloadText(filename, text, type = 'application/json') {
const url = URL.createObjectURL(new Blob([text], { type }));
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.append(link);
link.click();
link.remove();
requestAnimationFrame(() => URL.revokeObjectURL(url));
}
/** Read a File the player picked, as text. */
export function readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(new Error('Could not read that file.'));
reader.readAsText(file);
});
}
/** A timestamp suffix that sorts, for filenames. */
export function stamp(date = new Date()) {
return date.toISOString().slice(0, 19).replace(/[:T]/g, '-');
}
+103
View File
@@ -0,0 +1,103 @@
// The feedback and instrumentation log.
//
// Deliberately separate from the save: this is research data for the designer,
// not part of anyone's career. It is exported on its own and never merged into
// a save file.
//
// Each entry records more than the spec's minimum, for two reasons. The full
// before/after diff makes "what did that choice actually do" answerable months
// later without replaying anything. The list of options that were *offered but
// locked* is the strongest available signal that a choice set is too narrow —
// players rarely type into a comment box, but the gates they keep bouncing off
// are recorded whether they say anything or not.
const KEY = 'theladder.feedback.v1';
const FORMAT = 1;
function safely(action, fallback = null) {
try {
return action();
} catch {
return fallback;
}
}
function readRaw() {
return safely(() => {
const raw = localStorage.getItem(KEY);
return raw ? JSON.parse(raw) : [];
}, []) ?? [];
}
function writeRaw(entries) {
return safely(() => {
localStorage.setItem(KEY, JSON.stringify(entries));
return true;
}, false);
}
/**
* Record a turn. `record` is what takeTurn returned; `state` is the state it
* produced, carried for the seed and the running totals at that moment.
*/
export function logTurn(record, state, pack) {
const entries = readRaw();
entries.push({
logged_at: new Date().toISOString(),
pack_id: pack.id,
pack_version: pack.version ?? null,
seed: state.meta.seed,
turn_id: `${state.meta.seed}:${record.turn}`,
turn: record.turn,
stage: record.stage,
event_id: record.eventId,
action_taken: record.optionId,
action_label: record.optionLabel,
changes: record.changes,
upkeep: record.upkeep,
offered: record.offered,
rating: null,
comment: null,
desired_but_unavailable_action: null,
});
writeRaw(entries);
return entries.at(-1);
}
/**
* Attach the player's feedback to a turn already logged. Feedback arrives
* after the choice — often several seconds after — so it is a second write
* rather than part of the first.
*/
export function attachFeedback(turnId, { rating, comment, desiredAction }) {
const entries = readRaw();
const entry = entries.findLast((e) => e.turn_id === turnId);
if (!entry) return false;
if (rating !== undefined) entry.rating = rating;
if (comment !== undefined) entry.comment = comment || null;
if (desiredAction !== undefined) entry.desired_but_unavailable_action = desiredAction || null;
return writeRaw(entries);
}
export function readLog() {
return readRaw();
}
export function clearLog() {
return safely(() => { localStorage.removeItem(KEY); return true; }, false);
}
/** How many entries carry actual player feedback, for the export summary. */
export function feedbackCount(entries = readRaw()) {
return entries.filter((e) => e.rating || e.comment || e.desired_but_unavailable_action).length;
}
export function serializeLog(entries = readRaw()) {
return JSON.stringify({
format: FORMAT,
exported_at: new Date().toISOString(),
turns_logged: entries.length,
turns_with_feedback: feedbackCount(entries),
entries,
}, null, 2);
}
+77
View File
@@ -0,0 +1,77 @@
// Saving and loading.
//
// Local storage is the live save; the file export exists so a cleared cache or
// a crashed browser does not take a career with it. A save is the whole game
// state and nothing else — the engine keeps no state outside it, so this is a
// complete record by construction.
const KEY = 'theladder.save.v1';
const FORMAT = 1;
/** Local storage throws in private windows and when site data is blocked. */
function safely(action, fallback = null) {
try {
return action();
} catch {
return fallback;
}
}
export function saveLocal(state) {
return safely(() => {
localStorage.setItem(KEY, JSON.stringify({ format: FORMAT, savedAt: new Date().toISOString(), state }));
return true;
}, false);
}
export function loadLocal() {
return safely(() => {
const raw = localStorage.getItem(KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
return parsed?.state ?? null;
});
}
export function clearLocal() {
return safely(() => { localStorage.removeItem(KEY); return true; }, false);
}
/** True if the browser will actually remember anything. */
export function storageAvailable() {
return safely(() => {
const probe = '__theladder_probe__';
localStorage.setItem(probe, '1');
localStorage.removeItem(probe);
return true;
}, false);
}
/** A save file's contents, as a string ready to be downloaded. */
export function serializeSave(state) {
return JSON.stringify({ format: FORMAT, savedAt: new Date().toISOString(), state }, null, 2);
}
/**
* Parse an imported save, refusing anything that is not one. A file from a
* different pack is rejected by name rather than loaded into a game whose
* events and characters do not match it.
*/
export function parseSave(text, expectedPackId) {
let parsed;
try {
parsed = JSON.parse(text);
} catch {
throw new Error('That file is not valid JSON.');
}
const state = parsed?.state;
if (!state || typeof state !== 'object' || !state.meta || typeof state.turn !== 'number') {
throw new Error('That does not look like a saved game.');
}
if (expectedPackId && state.meta.packId !== expectedPackId) {
throw new Error(
`That save is from "${state.meta.packId}", but this is "${expectedPackId}".`,
);
}
return state;
}
+230
View File
@@ -0,0 +1,230 @@
// The application: wiring the engine to the screens.
//
// This is the one module that names a content pack, which makes it the seam a
// future pack-picker slots into. Everything below it takes the pack as an
// argument.
//
// Rendering is a full rebuild of the root element. At this size it is fast and
// removes a whole class of stale-view bug — with one deliberate exception: the
// feedback text fields update the model without re-rendering, because
// rebuilding the DOM under a cursor would throw the player out of the box they
// are typing in.
import { corporateLadder } from '../../content/corporateladder/index.js';
import { validatePack } from '../engine/validate.js';
import { resolveSchema } from '../engine/state.js';
import { startGame, currentTurn, takeTurn, findOptionById } from './engine-bridge.js';
import { turnScreen } from './screens/turn.js';
import { retrospectiveScreen } from './screens/retrospective.js';
import { fill } from './dom.js';
import { saveLocal, loadLocal, clearLocal, serializeSave, parseSave, storageAvailable } from '../io/save.js';
import { logTurn, attachFeedback, readLog, serializeLog, clearLog, feedbackCount } from '../io/feedback-log.js';
import { downloadText, readFile, stamp } from '../io/download.js';
const pack = corporateLadder;
const schema = resolveSchema(pack);
const app = {
state: null,
view: null,
root: null,
};
/** Reset the per-turn view, reading the current turn out of the game state. */
function choosingView() {
return {
screen: 'turn',
phase: 'choosing',
turn: currentTurn(pack, app.state),
feedback: emptyFeedback(),
feedbackOpen: false,
};
}
const emptyFeedback = () =>
({ rating: null, comment: '', desiredAction: '', saved: false, touched: false, turnId: null });
function render() {
const screen = app.view.screen === 'retrospective'
? retrospectiveScreen(pack, app.state, schema, actions)
: turnScreen(pack, app.state, schema, app.view, actions);
fill(app.root, screen);
}
const actions = {
onChoose(optionId) {
const option = findOptionById(app.view.turn.event, optionId);
const { state, record } = takeTurn(pack, app.state, optionId);
app.state = state;
saveLocal(state);
const entry = logTurn(record, state, pack);
app.view = {
screen: 'turn',
phase: 'outcome',
turn: app.view.turn,
record,
option,
feedback: { ...emptyFeedback(), turnId: entry?.turn_id ?? null },
feedbackOpen: false,
};
render();
},
onNext() {
flushFeedback();
app.view = choosingView();
render();
},
onRate(rating) {
app.view.feedback.rating = app.view.feedback.rating === rating ? null : rating;
app.view.feedback.saved = app.view.feedback.rating !== null;
app.view.feedback.touched = true;
flushFeedback();
render();
},
// No render: rebuilding the DOM would move the cursor out of the field.
onComment(text) {
app.view.feedback.comment = text;
app.view.feedback.touched = true;
scheduleFlush();
},
onDesiredAction(text) {
app.view.feedback.desiredAction = text;
app.view.feedback.touched = true;
scheduleFlush();
},
onToggleFeedbackDetail() {
app.view.feedbackOpen = !app.view.feedbackOpen;
render();
},
onRetrospective() {
flushFeedback();
app.view = { ...app.view, screen: 'retrospective' };
render();
},
onResume() {
app.view = choosingView();
render();
},
onNewGame() {
const played = app.state?.history?.length ?? 0;
if (played > 0 && !confirm(
`This ends the current run at ${pack.turnUnit} ${app.state.turn}. ` +
'Export a save first if you want to keep it. Start a new game?',
)) return;
flushFeedback();
app.state = startGame(pack, { seed: String(Date.now()), schema, now: new Date().toISOString() });
clearLocal();
saveLocal(app.state);
app.view = choosingView();
render();
},
onExportSave() {
downloadText(`theladder-save-${stamp()}.json`, serializeSave(app.state));
},
onImportSave() {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/json,.json';
input.addEventListener('change', async () => {
const file = input.files?.[0];
if (!file) return;
try {
const state = parseSave(await readFile(file), pack.id);
app.state = state;
saveLocal(state);
app.view = choosingView();
render();
} catch (error) {
alert(`That save could not be loaded.\n\n${error.message}`);
}
});
input.click();
},
onExportFeedback() {
flushFeedback();
const entries = readLog();
if (entries.length === 0) {
alert('Nothing logged yet — play a turn or two first.');
return;
}
downloadText(`theladder-feedback-${stamp()}.json`, serializeLog(entries));
const withFeedback = feedbackCount(entries);
if (confirm(
`Exported ${entries.length} logged turns (${withFeedback} carry feedback).\n\n` +
'Clear the log now that it is saved?',
)) clearLog();
},
};
// Text fields write through on a delay so a long comment is not one storage
// write per keystroke, and always flush before anything that could lose it.
let flushTimer = null;
function scheduleFlush() {
clearTimeout(flushTimer);
flushTimer = setTimeout(flushFeedback, 500);
}
function flushFeedback() {
clearTimeout(flushTimer);
const feedback = app.view?.feedback;
if (!feedback?.turnId) return;
// `touched` rather than "has content": a player who clears a rating or
// deletes a comment is withdrawing it, and that has to be written through
// too. Turns the player simply ignored are never written at all.
if (!feedback.touched) return;
attachFeedback(feedback.turnId, {
rating: feedback.rating,
comment: feedback.comment,
desiredAction: feedback.desiredAction,
});
}
export function boot(rootElement) {
const validation = validatePack(pack);
if (!validation.valid) {
fill(rootElement, errorScreen(validation.errors));
return;
}
for (const warning of validation.warnings) console.warn(`[content] ${warning}`);
if (!storageAvailable()) {
console.warn('[save] local storage is unavailable; progress will not persist. Use Export save.');
}
app.root = rootElement;
const restored = loadLocal();
app.state = restored && restored.meta?.packId === pack.id
? restored
: startGame(pack, { seed: String(Date.now()), schema, now: new Date().toISOString() });
app.view = choosingView();
render();
// Anything half-typed survives a tab close.
window.addEventListener('beforeunload', flushFeedback);
}
function errorScreen(errors) {
const list = document.createElement('ul');
for (const error of errors) {
const item = document.createElement('li');
item.textContent = error;
list.append(item);
}
const wrapper = document.createElement('div');
wrapper.className = 'screen screen--error';
const heading = document.createElement('h1');
heading.textContent = 'This content pack will not load.';
wrapper.append(heading, list);
return wrapper;
}
+92
View File
@@ -0,0 +1,92 @@
// Pieces shared between the turn screen and the retrospective.
import { h } from './dom.js';
import { formatValue, labelFor, headerStats } from './format.js';
import { getPath } from '../engine/paths.js';
/** A labelled bar for a bounded stat. */
export function meter(label, value, bounds, { compact = false } = {}) {
const min = bounds?.min ?? 0;
const max = bounds?.max ?? 100;
const fraction = max === min ? 0 : Math.max(0, Math.min(1, (value - min) / (max - min)));
return h('div', { class: compact ? 'meter meter--compact' : 'meter' },
h('div', { class: 'meter__head' },
h('span', { class: 'meter__label' }, label),
h('span', { class: 'meter__value' }, String(value)),
),
h('div', { class: 'meter__track', role: 'img', 'aria-label': `${label}: ${value} of ${max}` },
h('div', { class: 'meter__fill', style: `width: ${(fraction * 100).toFixed(1)}%` }),
),
);
}
/** The stat strip: money and debt as figures, bounded stats as bars. */
export function statPanel(pack, state, schema) {
return h('div', { class: 'stats' },
headerStats(pack, state, schema).map((stat) => (
stat.rule.format === 'meter'
? meter(stat.label, stat.value, stat.bounds, { compact: true })
: h('div', { class: `figure figure--${stat.path.replace(/\./g, '-')}` },
h('span', { class: 'figure__label' }, stat.label),
h('span', {
class: `figure__value${stat.value < 0 ? ' figure__value--negative' : ''}`,
}, formatValue(pack, stat.path, stat.value)),
)
)),
);
}
/** One character, with how they currently regard the player. */
export function characterCard(pack, state, schema, character) {
return h('article', { class: 'person' },
h('header', { class: 'person__head' },
h('h3', { class: 'person__name' }, character.name),
character.title && h('p', { class: 'person__title' }, character.title),
),
h('p', { class: 'person__description' }, character.description),
h('div', { class: 'person__meters' },
Object.keys(pack.relationshipStats ?? {}).map((stat) => {
const path = `relationships.${character.id}.${stat}`;
return meter(
pack.relationshipStats[stat].label ?? stat,
getPath(state, path),
schema[path],
{ compact: true },
);
}),
),
);
}
/** The change list shown after a choice: what moved, and by how much. */
export function changeList(pack, changes, { className = 'changes' } = {}) {
const meaningful = changes.filter((c) => c.from !== c.to);
if (!meaningful.length) return h('p', { class: 'changes changes--none' }, 'Nothing measurable changed.');
return h('ul', { class: className },
meaningful.map((change) => {
const rising = typeof change.to === 'number' && typeof change.from === 'number'
? change.to > change.from
: Boolean(change.to);
return h('li', { class: `change change--${rising ? 'up' : 'down'}` },
// Upkeep changes carry the label of the entry that caused them —
// "Rent", "Wages" — which is far more use than the path's own name.
h('span', { class: 'change__label' }, change.label ?? labelFor(pack, change.path)),
h('span', { class: 'change__delta' }, deltaText(pack, change)),
change.clamped && h('span', { class: 'change__note' }, 'at its limit'),
);
}),
);
}
function deltaText(pack, change) {
if (typeof change.to !== 'number' || typeof change.from !== 'number') {
return typeof change.to === 'boolean' ? (change.to ? 'now true' : 'no longer true') : 'changed';
}
const delta = change.to - change.from;
const money = pack.display?.[change.path]?.format === 'money';
const magnitude = money
? `$${Math.abs(Math.round(delta)).toLocaleString('en-US')}`
: String(Math.abs(delta));
return `${delta > 0 ? '+' : '−'}${magnitude}`;
}
+26
View File
@@ -0,0 +1,26 @@
// A very small DOM helper. Not a framework — just enough to build elements
// without a wall of createElement calls.
export function h(tag, props = {}, ...children) {
const el = document.createElement(tag);
for (const [key, value] of Object.entries(props ?? {})) {
if (value === null || value === undefined || value === false) continue;
if (key === 'class') el.className = value;
else if (key === 'dataset') Object.assign(el.dataset, value);
else if (key.startsWith('on') && typeof value === 'function') {
el.addEventListener(key.slice(2).toLowerCase(), value);
} else if (key in el && key !== 'list') el[key] = value;
else el.setAttribute(key, value);
}
for (const child of children.flat(Infinity)) {
if (child === null || child === undefined || child === false) continue;
el.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return el;
}
/** Replace an element's contents. */
export function fill(container, ...children) {
container.replaceChildren(...children.flat(Infinity).filter((c) => c !== null && c !== undefined && c !== false));
return container;
}
+34
View File
@@ -0,0 +1,34 @@
// The UI's view of the engine, with the pack's schema bound in.
//
// Re-exported here rather than imported directly so the screens never have to
// thread a schema argument through, and so there is one obvious place to look
// for everything the interface is allowed to do to a game.
import { resolveSchema } from '../engine/state.js';
import * as game from '../engine/game.js';
import { findOption } from '../engine/select.js';
const schemaCache = new WeakMap();
function schemaFor(pack) {
if (!schemaCache.has(pack)) schemaCache.set(pack, resolveSchema(pack));
return schemaCache.get(pack);
}
export function startGame(pack, options = {}) {
return game.startGame(pack, { schema: schemaFor(pack), ...options });
}
export function currentTurn(pack, state) {
return game.currentTurn(pack, state);
}
export function takeTurn(pack, state, optionId, options = {}) {
return game.takeTurn(pack, state, optionId, {
schema: schemaFor(pack),
now: new Date().toISOString(),
...options,
});
}
export const findOptionById = findOption;
+151
View File
@@ -0,0 +1,151 @@
// Turning state paths and conditions into English.
//
// Display names, number formats and which stats appear in the header all come
// from the pack's `display` map, so a new setting renames and re-orders the
// interface without touching the UI. Anything the pack does not describe falls
// back to a derivation from the path itself, so content is never *required* to
// supply a label just to be playable.
import { getPath } from '../engine/paths.js';
import { check } from '../engine/conditions.js';
const titleCase = (text) =>
text.replace(/_/g, ' ').replace(/^\w/, (c) => c.toUpperCase());
/** The pack's display rules for a path, if it has any. */
export function displayFor(pack, path) {
return pack.display?.[path] ?? null;
}
/** A human name for a path, derived from the path when the pack is silent. */
export function labelFor(pack, path) {
const declared = displayFor(pack, path)?.label;
if (declared) return declared;
const segments = path.split('.');
if (segments[0] === 'relationships' && segments.length === 3) {
const character = pack.characters?.find((c) => c.id === segments[1]);
const stat = pack.relationshipStats?.[segments[2]]?.label ?? titleCase(segments[2]);
return `${character?.name ?? titleCase(segments[1])} — ${stat.toLowerCase()}`;
}
return titleCase(segments.at(-1));
}
/** Money is written as money; everything else is a plain number. */
export function formatValue(pack, path, value) {
if (typeof value === 'boolean') return value ? 'yes' : 'no';
if (displayFor(pack, path)?.format === 'money') return formatMoney(value);
return String(value);
}
export function formatMoney(amount) {
const rounded = Math.round(amount);
const body = `$${Math.abs(rounded).toLocaleString('en-US')}`;
return rounded < 0 ? `−${body}` : body;
}
/** A signed change, for the outcome list: "+$45", "−3". */
export function formatDelta(pack, path, from, to) {
const delta = to - from;
if (displayFor(pack, path)?.format === 'money') {
return `${delta > 0 ? '+' : '−'}$${Math.abs(Math.round(delta)).toLocaleString('en-US')}`;
}
return `${delta > 0 ? '+' : '−'}${Math.abs(delta)}`;
}
/**
* One condition as a requirement the player can read: "Negotiation 15+",
* "Trevor — likes you 48+", "not in debt".
*/
export function describeCondition(pack, condition) {
if (!condition || typeof condition !== 'object') return '';
if (Array.isArray(condition)) return condition.map((c) => describeCondition(pack, c)).join(', ');
if (condition.all) return condition.all.map((c) => describeCondition(pack, c)).join(', ');
if (condition.any) return condition.any.map((c) => describeCondition(pack, c)).join(' or ');
if (condition.not) return `not ${describeCondition(pack, condition.not)}`;
const { path, op, value } = condition;
const label = labelFor(pack, path);
if (typeof value === 'boolean') return value ? label.toLowerCase() : `no ${label.toLowerCase()}`;
const amount = formatValue(pack, path, value);
switch (op) {
case '>=': return `${label} ${amount}+`;
case '>': return `${label} over ${amount}`;
case '<=': return `${label} ${amount} or less`;
case '<': return `${label} under ${amount}`;
case '==': return `${label} exactly ${amount}`;
case '!=': return `${label} other than ${amount}`;
default: return `${label} ${op} ${amount}`;
}
}
/** What a locked option is waiting for. */
export function requirementText(pack, failedConditions) {
const parts = failedConditions.map((c) => describeCondition(pack, c)).filter(Boolean);
return parts.length ? `Needs ${parts.join(', ')}` : 'Not available yet';
}
/**
* The stats the header shows, in the pack's declared order, skipping anything
* the pack marks hidden or asks to hide while it is zero.
*/
export function headerStats(pack, state, schema) {
return Object.entries(pack.display ?? {})
.filter(([, rule]) => !rule.hidden)
.map(([path, rule]) => ({
path,
rule,
label: labelFor(pack, path),
value: getPath(state, path),
bounds: schema[path],
}))
.filter((stat) => !(stat.rule.hideWhenZero && !stat.value))
.sort((a, b) => (a.rule.order ?? 99) - (b.rule.order ?? 99));
}
/**
* How the current turn is titled. A pack with a calendar gets its day name and
* cycle ("Thursday", "Week 2 · Day 12"); one without falls back to the turn
* number alone, which is what the engine guarantees.
*/
export function turnHeading(pack, state) {
const unit = capitalize(pack.turnUnit ?? 'turn');
const name = state.calendar?.name;
if (!name) return { title: `${unit} ${state.turn}`, detail: null };
const cycleName = pack.calendar?.cycleName ?? 'Cycle';
return {
title: name,
detail: `${cycleName} ${state.calendar.cycle} · ${unit} ${state.turn}`,
};
}
/**
* The pack's scheduled upkeep, as "what is coming and when". Answers the
* question a player actually has — when am I next paid, when is rent due —
* without them having to reverse-engineer it from the ledger.
*/
export function upcomingUpkeep(pack, state, { limit = 3 } = {}) {
const upcoming = [];
for (const entry of pack.upkeep ?? []) {
if (!entry.every || !entry.label) continue;
if (!check(state, entry.requires).passed) continue;
const offset = entry.offset ?? 0;
const elapsed = state.turn - 1 - offset;
const turnsAway = elapsed < 0 ? -elapsed : (entry.every - (elapsed % entry.every)) % entry.every;
const amount = (entry.effects ?? [])
.filter((e) => e.op === 'add' && typeof e.value === 'number')
.reduce((sum, e) => sum + e.value, 0);
upcoming.push({ label: entry.label, turnsAway, incoming: amount > 0 });
}
return upcoming
.sort((a, b) => a.turnsAway - b.turnsAway)
.filter((entry, index, all) => all.findIndex((e) => e.label === entry.label) === index)
.slice(0, limit);
}
const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
+87
View File
@@ -0,0 +1,87 @@
// The career retrospective.
//
// Structurally identical however the run went — this is a summary, not a
// scoreboard, and there is no win state to congratulate anyone on. It is also
// not an ending: the player can close it and carry on from the same turn.
import { h } from '../dom.js';
import { statPanel, characterCard } from '../components.js';
import { formatMoney, labelFor } from '../format.js';
import { summarize } from '../summary.js';
export function retrospectiveScreen(pack, state, schema, actions) {
const summary = summarize(pack, state);
const unit = pack.turnUnit ?? 'turn';
return h('div', { class: 'screen screen--retrospective' },
h('header', { class: 'retro__head' },
h('p', { class: 'retro__eyebrow' }, pack.name),
h('h1', { class: 'retro__title' }, 'Career retrospective'),
h('p', { class: 'retro__subtitle' },
`${summary.turns} ${unit}${summary.turns === 1 ? '' : 's'} in the ` +
`${(pack.stages?.[summary.stage]?.label ?? summary.stage).toLowerCase()}.`),
),
h('section', { class: 'retro__section' },
h('h2', { class: 'retro__heading' }, 'Where you ended up'),
statPanel(pack, state, schema),
),
h('section', { class: 'retro__section' },
h('h2', { class: 'retro__heading' }, 'How it went'),
h('dl', { class: 'facts' },
fact(`Highest your ${primaryLabel(pack, summary)} got`,
summary.peak === null ? '—' : formatMoney(summary.peak)),
fact('Lowest it got', summary.trough === null ? '—' : formatMoney(summary.trough)),
summary.daysInTheRed > 0 && fact(`${capitalize(unit)}s in the red`, String(summary.daysInTheRed)),
summary.bestDay && fact(`Best ${unit}`,
`${formatMoney(summary.bestDay.net)} — ${summary.bestDay.label}`),
summary.worstDay && fact(`Worst ${unit}`,
`${formatMoney(summary.worstDay.net)} — ${summary.worstDay.label}`),
summary.favouriteAction && fact('What you did most',
`${summary.favouriteAction.label} (${summary.favouriteAction.count}×)`),
fact('Situations you saw', `${summary.eventsSeen} of ${summary.eventsTotal}`),
summary.lockedEncounters > 0 && fact('Doors you could not open yet',
String(summary.lockedEncounters)),
),
),
h('section', { class: 'retro__section' },
h('h2', { class: 'retro__heading' }, 'Where you stand with people'),
h('div', { class: 'retro__people' },
(pack.characters ?? []).map((character) => characterCard(pack, state, schema, character)),
),
),
h('section', { class: 'retro__section' },
h('h2', { class: 'retro__heading' }, 'Notable moments'),
summary.notable.length
? h('ol', { class: 'moments' }, summary.notable.map((moment) => h('li', { class: 'moment' }, moment)))
: h('p', { class: 'moments moments--none' },
'Nothing that anybody would write down. That happens.'),
),
h('footer', { class: 'controls' },
h('button', { class: 'button button--primary', onClick: actions.onResume },
'Keep going'),
h('button', { class: 'button button--quiet', onClick: actions.onExportSave }, 'Export save'),
h('button', { class: 'button button--quiet', onClick: actions.onExportFeedback },
'Export feedback log'),
h('button', { class: 'button button--quiet', onClick: actions.onNewGame }, 'Start again'),
),
);
}
/** The pack's own word for its main resource, lowercased for mid-sentence use. */
function primaryLabel(pack, summary) {
return summary.primaryPath ? labelFor(pack, summary.primaryPath).toLowerCase() : 'balance';
}
function fact(label, value) {
return h('div', { class: 'facts__item' },
h('dt', { class: 'facts__label' }, label),
h('dd', { class: 'facts__value' }, value),
);
}
const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
+171
View File
@@ -0,0 +1,171 @@
// The turn screen, in two phases.
//
// Choosing: the scenario and its options, with locked ones shown greyed and
// labelled with what they are waiting for — a player should be able to see the
// door they cannot open yet, because that is most of what makes the numbers
// mean anything.
//
// Outcome: what happened, what moved, and what the day cost regardless of the
// choice. The feedback widget lives here rather than in the choosing phase,
// because this is the moment a player has an opinion.
import { h } from '../dom.js';
import { statPanel, characterCard, changeList } from '../components.js';
import { requirementText, turnHeading, upcomingUpkeep } from '../format.js';
export function turnScreen(pack, state, schema, view, actions) {
const heading = turnHeading(pack, state);
return h('div', { class: 'screen screen--turn' },
h('header', { class: 'hud' },
h('div', { class: 'hud__where' },
h('p', { class: 'hud__stage' }, pack.stages?.[state.stage]?.title ?? state.stage),
h('h1', { class: 'hud__day' }, heading.title),
heading.detail && h('p', { class: 'hud__detail' }, heading.detail),
),
statPanel(pack, state, schema),
),
diary(pack, state),
h('div', { class: 'layout' },
h('main', { class: 'scene' },
view.phase === 'outcome'
? outcomeView(pack, view, actions)
: choosingView(pack, view, actions),
),
h('aside', { class: 'people' },
h('h2', { class: 'people__heading' }, 'The mailroom'),
(pack.characters ?? []).map((character) => characterCard(pack, state, schema, character)),
),
),
h('footer', { class: 'controls' },
h('button', { class: 'button', onClick: actions.onRetrospective },
'Wrap up my career'),
h('button', { class: 'button button--quiet', onClick: actions.onExportSave }, 'Export save'),
h('button', { class: 'button button--quiet', onClick: actions.onImportSave }, 'Import save'),
h('button', { class: 'button button--quiet', onClick: actions.onExportFeedback },
'Export feedback log'),
h('button', { class: 'button button--quiet', onClick: actions.onNewGame }, 'New game'),
),
);
}
/**
* What is coming and when. A player asked what the daily drain was for; the
* answer is that most of it is not daily, and this says so before the money
* moves rather than after.
*/
function diary(pack, state) {
const upcoming = upcomingUpkeep(pack, state);
if (!upcoming.length) return null;
const unit = pack.turnUnit ?? 'turn';
return h('p', { class: 'diary' },
upcoming.map((entry, index) => h('span', {
class: `diary__entry diary__entry--${entry.incoming ? 'in' : 'out'}`,
},
index > 0 ? ' · ' : '',
entry.label,
entry.turnsAway === 0
? ' today'
: entry.turnsAway === 1 ? ` tomorrow` : ` in ${entry.turnsAway} ${unit}s`,
)),
);
}
function choosingView(pack, view, actions) {
const { event, options } = view.turn;
const visible = options.filter((o) => !o.hidden);
return h('section', { class: 'scenario' },
h('p', { class: 'scenario__text' }, event.description),
h('ul', { class: 'options' },
visible.map(({ option, available, failed }) => h('li', { class: 'options__item' },
h('button', {
class: `option${available ? '' : ' option--locked'}`,
disabled: !available,
onClick: available ? () => actions.onChoose(option.id) : null,
},
h('span', { class: 'option__label' }, option.label),
!available && h('span', { class: 'option__requirement' }, requirementText(pack, failed)),
),
)),
),
);
}
function outcomeView(pack, view, actions) {
const { record, option } = view;
return h('section', { class: 'outcome' },
h('p', { class: 'outcome__chose' }, option.label),
option.result && h('p', { class: 'outcome__text' }, option.result),
h('div', { class: 'outcome__ledger' },
h('h3', { class: 'outcome__heading' }, 'What that changed'),
changeList(pack, record.changes),
record.upkeep.length > 0 && h('div', { class: 'outcome__upkeep' },
h('h3', { class: 'outcome__heading' }, 'And then the day happened'),
changeList(pack, record.upkeep),
),
),
feedbackWidget(view, actions),
h('button', { class: 'button button--primary button--next', onClick: actions.onNext },
`Next ${pack.turnUnit ?? 'turn'}`),
);
}
// Entirely optional: ignoring it does nothing at all, which is the point.
function feedbackWidget(view, actions) {
const { feedback } = view;
const ratingButton = (value, label) => h('button', {
class: `rating${feedback.rating === value ? ' rating--on' : ''}`,
type: 'button',
'aria-pressed': String(feedback.rating === value),
onClick: () => actions.onRate(value),
}, label);
return h('section', { class: 'feedback' },
h('div', { class: 'feedback__row' },
h('span', { class: 'feedback__prompt' }, 'How was that?'),
h('div', { class: 'feedback__ratings' },
ratingButton('up', '👍'),
ratingButton('neutral', '😐'),
ratingButton('down', '👎'),
),
h('button', {
class: 'feedback__toggle',
type: 'button',
onClick: actions.onToggleFeedbackDetail,
}, view.feedbackOpen ? 'Fewer options' : 'Say more'),
),
view.feedbackOpen && h('div', { class: 'feedback__detail' },
h('label', { class: 'field' },
h('span', { class: 'field__label' }, 'Anything you want to tell the designer?'),
h('textarea', {
class: 'field__input',
rows: 2,
value: feedback.comment ?? '',
onInput: (e) => actions.onComment(e.target.value),
}),
),
h('label', { class: 'field' },
h('span', { class: 'field__label' },
"Something you wanted to do that wasn't offered?"),
h('textarea', {
class: 'field__input',
rows: 2,
value: feedback.desiredAction ?? '',
onInput: (e) => actions.onDesiredAction(e.target.value),
}),
),
),
feedback.saved && h('p', { class: 'feedback__saved' }, 'Noted — thank you.'),
);
}
+289
View File
@@ -0,0 +1,289 @@
/* The Ladder — one stylesheet, no framework.
The look is office stationery: manila, rules, stamped figures. Muted enough
that seventeen scenarios in a row do not tire the eye. */
:root {
--paper: #f2eee4;
--card: #fffdf7;
--ink: #26231d;
--ink-soft: #6b6659;
--ink-faint: #938c7c;
--rule: #ded6c4;
--rule-strong: #c9bfa8;
--accent: #7c5a2c;
--accent-soft: #efe3cd;
--up: #4a6b3d;
--down: #a4402f;
--focus: #2f6f9e;
--radius: 3px;
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: Georgia, "Iowan Old Style", "Palatino Linotype", Palatino, serif;
}
@media (prefers-color-scheme: dark) {
:root {
--paper: #1c1a17;
--card: #24211d;
--ink: #e8e3d8;
--ink-soft: #a8a294;
--ink-faint: #7d776a;
--rule: #38342d;
--rule-strong: #4a453b;
--accent: #c9a05e;
--accent-soft: #3a3227;
--up: #85ad72;
--down: #d17a68;
--focus: #6fa8d4;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--paper);
color: var(--ink);
font-family: var(--sans);
font-size: 16px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
.app { max-width: 1080px; margin: 0 auto; padding: 24px 20px 48px; }
.booting { color: var(--ink-faint); padding: 48px 20px; text-align: center; }
/* ---------- head-up display ---------- */
.hud {
display: flex;
flex-wrap: wrap;
gap: 20px 32px;
align-items: flex-end;
justify-content: space-between;
padding-bottom: 16px;
border-bottom: 2px solid var(--rule-strong);
}
.hud__stage {
margin: 0;
font-size: 12px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--ink-faint);
}
.hud__day { margin: 2px 0 0; font-size: 26px; font-weight: 600; letter-spacing: -0.01em; }
.hud__detail { margin: 1px 0 0; font-size: 13px; color: var(--ink-soft); }
.diary {
margin: 14px 0 0; padding: 8px 12px;
font-size: 12.5px; color: var(--ink-soft);
background: var(--card); border: 1px solid var(--rule); border-radius: var(--radius);
}
.diary__entry--in { color: var(--up); }
.diary__entry--out { color: var(--ink-soft); }
.stats { display: flex; flex-wrap: wrap; gap: 10px 26px; align-items: flex-end; }
.figure { display: flex; flex-direction: column; gap: 1px; min-width: 92px; }
.figure__label {
font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-faint);
}
.figure__value { font-family: var(--serif); font-size: 21px; font-variant-numeric: tabular-nums; }
.figure__value--negative { color: var(--down); }
/* ---------- meters ---------- */
.meter { min-width: 150px; }
.meter--compact { min-width: 132px; }
.meter__head {
display: flex; justify-content: space-between; gap: 10px; align-items: baseline;
font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-faint);
}
.meter__value { font-variant-numeric: tabular-nums; color: var(--ink-soft); }
.meter__track {
margin-top: 4px; height: 5px; background: var(--rule); border-radius: 99px; overflow: hidden;
}
.meter__fill {
height: 100%; background: var(--accent); border-radius: 99px;
transition: width 280ms ease;
}
/* ---------- layout ---------- */
.layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 280px;
gap: 36px;
margin-top: 28px;
align-items: start;
}
@media (max-width: 860px) {
.layout { grid-template-columns: minmax(0, 1fr); gap: 28px; }
}
/* ---------- the scenario ---------- */
.scenario__text, .outcome__text {
font-family: var(--serif);
font-size: 20px;
line-height: 1.55;
margin: 0 0 24px;
}
.options { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
.option {
display: flex; flex-direction: column; gap: 3px; width: 100%;
padding: 14px 16px; text-align: left; cursor: pointer;
background: var(--card); color: inherit; font: inherit;
border: 1px solid var(--rule-strong); border-radius: var(--radius);
transition: border-color 120ms ease, transform 120ms ease, background 120ms ease;
}
.option:hover:not(:disabled) { border-color: var(--accent); transform: translateX(2px); }
.option:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.option__label { font-size: 16px; }
.option--locked {
cursor: not-allowed; background: transparent; border-style: dashed;
border-color: var(--rule); color: var(--ink-faint);
}
.option__requirement {
font-size: 12px; letter-spacing: 0.04em; color: var(--ink-faint); font-style: italic;
}
/* ---------- outcome ---------- */
.outcome__chose {
margin: 0 0 10px; font-size: 12px; letter-spacing: 0.12em;
text-transform: uppercase; color: var(--accent);
}
.outcome__ledger {
margin: 26px 0; padding: 18px 20px;
background: var(--card); border: 1px solid var(--rule); border-radius: var(--radius);
}
.outcome__heading {
margin: 0 0 10px; font-size: 11px; letter-spacing: 0.12em;
text-transform: uppercase; color: var(--ink-faint); font-weight: 600;
}
.outcome__upkeep { margin-top: 18px; padding-top: 16px; border-top: 1px dashed var(--rule); }
.changes { list-style: none; margin: 0; padding: 0; display: grid; gap: 5px; }
.changes--none { color: var(--ink-faint); font-style: italic; margin: 0; }
.change { display: flex; gap: 10px; align-items: baseline; font-size: 14px; }
.change__label { color: var(--ink-soft); }
.change__delta { font-variant-numeric: tabular-nums; font-weight: 600; margin-left: auto; }
.change--up .change__delta { color: var(--up); }
.change--down .change__delta { color: var(--down); }
.change__note { font-size: 11px; color: var(--ink-faint); font-style: italic; }
.button--next { margin-top: 8px; }
/* ---------- people ---------- */
.people__heading, .retro__heading {
margin: 0 0 12px; font-size: 11px; letter-spacing: 0.12em;
text-transform: uppercase; color: var(--ink-faint); font-weight: 600;
}
.person {
padding: 16px; margin-bottom: 14px;
background: var(--card); border: 1px solid var(--rule); border-radius: var(--radius);
}
.person__name { margin: 0; font-size: 16px; font-weight: 600; }
.person__title {
margin: 1px 0 0; font-size: 11px; letter-spacing: 0.08em;
text-transform: uppercase; color: var(--ink-faint);
}
.person__description {
margin: 10px 0 14px; font-size: 13px; line-height: 1.5; color: var(--ink-soft);
font-family: var(--serif);
}
.person__meters { display: grid; gap: 8px; }
/* ---------- feedback ---------- */
.feedback {
margin: 24px 0; padding: 14px 16px;
border: 1px dashed var(--rule-strong); border-radius: var(--radius);
}
.feedback__row { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; }
.feedback__prompt { font-size: 13px; color: var(--ink-soft); }
.feedback__ratings { display: flex; gap: 6px; }
.rating {
padding: 4px 10px; font-size: 16px; line-height: 1.2; cursor: pointer;
background: transparent; border: 1px solid var(--rule); border-radius: var(--radius);
filter: grayscale(1); opacity: 0.65; transition: all 120ms ease;
}
.rating:hover { opacity: 1; filter: none; }
.rating--on { filter: none; opacity: 1; border-color: var(--accent); background: var(--accent-soft); }
.rating:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.feedback__toggle {
margin-left: auto; padding: 0; font: inherit; font-size: 12px; cursor: pointer;
background: none; border: none; color: var(--ink-faint); text-decoration: underline;
}
.feedback__detail { display: grid; gap: 12px; margin-top: 14px; }
.field { display: grid; gap: 4px; }
.field__label { font-size: 12px; color: var(--ink-faint); }
.field__input {
width: 100%; padding: 8px 10px; font: inherit; font-size: 14px; resize: vertical;
background: var(--card); color: inherit;
border: 1px solid var(--rule); border-radius: var(--radius);
}
.field__input:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; }
.feedback__saved { margin: 10px 0 0; font-size: 12px; color: var(--up); }
/* ---------- buttons and controls ---------- */
.controls {
display: flex; flex-wrap: wrap; gap: 8px; align-items: center;
margin-top: 36px; padding-top: 18px; border-top: 1px solid var(--rule);
}
.button {
padding: 9px 15px; font: inherit; font-size: 14px; cursor: pointer;
background: var(--card); color: inherit;
border: 1px solid var(--rule-strong); border-radius: var(--radius);
transition: border-color 120ms ease, background 120ms ease;
}
.button:hover { border-color: var(--accent); }
.button:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.button--primary { background: var(--accent); border-color: var(--accent); color: #fffdf7; }
.button--primary:hover { filter: brightness(1.08); }
.button--quiet { border-color: transparent; background: transparent; color: var(--ink-faint); }
.button--quiet:hover { color: var(--ink); border-color: var(--rule); }
/* ---------- retrospective ---------- */
.retro__head { padding-bottom: 20px; border-bottom: 2px solid var(--rule-strong); }
.retro__eyebrow {
margin: 0; font-size: 11px; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--ink-faint);
}
.retro__title { margin: 6px 0 4px; font-size: 32px; font-weight: 600; letter-spacing: -0.02em; }
.retro__subtitle { margin: 0; color: var(--ink-soft); font-family: var(--serif); font-size: 17px; }
.retro__section { margin-top: 34px; }
.retro__people { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 14px; }
.retro__people .person { margin-bottom: 0; }
.facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 14px; margin: 0; }
.facts__item {
padding: 12px 14px; background: var(--card);
border: 1px solid var(--rule); border-radius: var(--radius);
}
.facts__label {
font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-faint);
}
.facts__value { margin: 3px 0 0; font-family: var(--serif); font-size: 16px; }
.moments { margin: 0; padding-left: 22px; display: grid; gap: 7px; }
.moment { font-family: var(--serif); font-size: 16px; }
.moments--none { padding: 0; color: var(--ink-faint); font-style: italic; }
.screen--error { padding: 40px 0; }
.screen--error h1 { font-size: 20px; color: var(--down); }
+67
View File
@@ -0,0 +1,67 @@
// Reading a career back out of its history.
//
// Everything here is derived generically from the turn record and the pack's
// display map — no path is named. A pack with different stats, or none of them
// called money, gets the same retrospective for free.
/** Paths the pack formats as money, in display order. */
function moneyPaths(pack) {
return Object.entries(pack.display ?? {})
.filter(([, rule]) => rule.format === 'money')
.sort((a, b) => (a[1].order ?? 99) - (b[1].order ?? 99))
.map(([path]) => path);
}
/** Every value a path passed through, turn by turn. */
function trace(history, path) {
const values = [];
for (const record of history) {
for (const change of [...record.changes, ...record.upkeep]) {
if (change.path === path && typeof change.to === 'number') values.push(change.to);
}
}
return values;
}
export function summarize(pack, state) {
const history = state.history ?? [];
const primary = moneyPaths(pack)[0] ?? null;
const primaryTrace = primary ? trace(history, primary) : [];
const byLabel = new Map();
for (const record of history) {
byLabel.set(record.optionLabel, (byLabel.get(record.optionLabel) ?? 0) + 1);
}
const favourite = [...byLabel.entries()].sort((a, b) => b[1] - a[1])[0] ?? null;
const netByTurn = history.map((record) => ({
turn: record.turn,
label: record.optionLabel,
net: [...record.changes, ...record.upkeep]
.filter((c) => c.path === primary && typeof c.to === 'number')
.reduce((sum, c) => sum + (c.to - c.from), 0),
}));
const ranked = [...netByTurn].sort((a, b) => b.net - a.net);
const lockedEncounters = history.reduce(
(sum, record) => sum + record.offered.filter((o) => !o.available).length, 0,
);
const eventsSeen = new Set(history.map((r) => r.eventId)).size;
return {
turns: history.length,
stage: state.stage,
notable: state.notable ?? [],
primaryPath: primary,
peak: primaryTrace.length ? Math.max(...primaryTrace) : null,
trough: primaryTrace.length ? Math.min(...primaryTrace) : null,
daysInTheRed: primaryTrace.filter((value) => value < 0).length,
favouriteAction: favourite ? { label: favourite[0], count: favourite[1] } : null,
bestDay: ranked[0]?.net > 0 ? ranked[0] : null,
worstDay: ranked.at(-1)?.net < 0 ? ranked.at(-1) : null,
lockedEncounters,
eventsSeen,
eventsTotal: (pack.events ?? []).length,
};
}