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
+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;
}