(Adaptive Loop) Pass 1

Adaptive Loop — a deterministic microfluidic strategy puzzle. Pure serializable
nextState(state,action) owns every committed turn; previews call the same
function on a clone. 5 handcrafted scenarios, bounded solver with verified
win/lose routes + shared-ownership counterfactual, exact localStorage
persistence/replay, accessible SVG interface, Vitest truth/solver/persistence
tests, and Playwright black-box browser proof.

Scenarios 3 and 4 retuned per SPEC §9 (provably unwinnable as originally
specified); proofs and exact changes in docs/scenario-tuning.md. Invariants
preserved. See CONTEXT-MANIFEST.md for the disclosure boundary and residual
risks.

Aggregate verified: tsc --noEmit, vitest (59), vite build, playwright (10).
This commit is contained in:
AlexKucera committed 2026-08-12 22:06:09 +02:00
1 parent dc8bfd6846
commit bd7203fc9e
31 files changed
+7113

No files matched your search

+706
View File
@@ -0,0 +1,706 @@
// Adaptive Loop — presentation controller + SVG rendering (SPEC §12, §13).
// Vanilla TS, no framework. Renders state, drives preview/commit through the
// pure nextState, persists after every turn, and is keyboard/screen-reader usable.
import type { GameState, RotationAction, LineageId, PressureId, GameEvent } from "./domain/types";
import { nextState } from "./domain/pipeline";
import { cloneState, canonicalStringify } from "./domain/serialize";
import { outletOf, totalPersistent } from "./domain/scenario";
import { SCENARIOS, SCENARIO_BY_ID } from "./content/scenarios";
import { PRESSURES, SPECIES } from "./domain/constants";
import { SLOT_POS, LOOP_POLYGONS, VIEWBOX, loopCenter } from "./presentation/geometry";
import {
startCampaign,
retry as retrySession,
enterScenario,
eligibleTraits,
preserveTrait,
unlockNext,
nextScenarioId,
type Session,
} from "./session";
import {
browserStorage,
saveEnvelope,
loadEnvelope,
clearSave,
emptyCampaign,
type CampaignProgress,
} from "./persistence/save";
type Screen = "title" | "game" | "trait-choice" | "standalone-pick";
type PendingWin = { session: Session; choices: { lineage: LineageId; pressure: PressureId }[] } | null;
interface App {
screen: Screen;
session: Session | null;
preview: RotationAction | null;
pendingWin: PendingWin;
lastEvents: GameEvent[];
}
const app: App = { screen: "title", session: null, preview: null, pendingWin: null, lastEvents: [] };
const root = document.getElementById("app")!;
const store = browserStorage();
let liveTimer: number | undefined;
// ---------- helpers ----------
function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string, text?: string): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text != null) e.textContent = text;
return e;
}
function announce(msg: string) {
const live = root.querySelector<HTMLElement>('[data-region="live"]');
if (live) {
live.textContent = "";
window.clearTimeout(liveTimer);
liveTimer = window.setTimeout(() => (live.textContent = msg), 30);
}
}
function saveCurrent(session: Session) {
saveEnvelope({ schemaVersion: 1, state: session.state, campaign: session.campaign, savedAt: Date.now() }, store);
}
// ---------- title screen ----------
function renderTitle() {
const hasSave = loadEnvelope(store).env != null;
root.innerHTML = "";
const main = el("main", "screen title-screen");
main.id = "main";
main.tabIndex = -1;
const h1 = el("h1", "title", "Adaptive Loop");
const tag = el("p", "muted tagline", "A deterministic microfluidic strategy puzzle.");
const panel = el("div", "menu");
const newBtn = mkBtn("new-campaign", "New Campaign", () => startNewCampaign());
panel.append(newBtn);
if (hasSave) {
panel.append(mkBtn("continue", "Continue", () => continueGame()));
}
const standalone = mkBtn("standalone", "Replay Standalone", () => {
app.screen = "standalone-pick";
renderStandalonePick();
});
panel.append(standalone);
const help = el("details", "help");
help.innerHTML = `<summary>How to play & legend</summary>
<div class="help-body">
<p>Rotate the three loops (A, B, C) clockwise or counter-clockwise. Each rotation moves the
chamber payloads, sets that loop's flow direction, and claims its shared slots — changing where
nutrient and toxin flow.</p>
<ul>
<li><b>Veridan</b> (producer) eats nutrient and grows.</li>
<li><b>Cilia</b> (grazer) eats producers.</li>
<li><b>Phage</b> eats grazers; starves without them.</li>
<li>Pressures: 🔥 heat, ☾ hunger, ⚗ toxin, ◊ immunity. At pressure 3 a lineage adapts
(benefit + cost + spillover).</li>
</ul>
<p>Focus or hover a rotation to preview; press the Commit button (or Enter on a rotation) to play it.
Escape cancels a preview.</p>
</div>`;
main.append(h1, tag, panel, help);
const live = el("div", "sr-only");
live.setAttribute("data-region", "live");
live.setAttribute("aria-live", "polite");
live.setAttribute("aria-atomic", "true");
root.append(main, live);
newBtn.focus();
}
function mkBtn(action: string, label: string, onClick: () => void, opts: { keys?: string; primary?: boolean } = {}): HTMLButtonElement {
const b = el("button", opts.primary ? "btn primary" : "btn", label);
b.dataset.action = action;
if (opts.keys) b.dataset.key = opts.keys;
b.addEventListener("click", onClick);
return b;
}
const LEGEND_HTML = `<p><b>● Veridan</b> (producer, cyan) eats nutrient and grows. <b>▲ Cilia</b> (grazer, gold)
eats producers. <b>◆ Phage</b> (purple) eats grazers; starves without them.</p>
<p>Fixtures: <span class=\"fixture-nutrientInlet\">▽N</span> nutrient inlet,
<span class=\"fixture-toxinInlet\">▽T</span> toxin inlet, <span class=\"fixture-heatSource\">🔥s</span> heat source,
<span class=\"fixture-drain\">▼</span> drain, <span class=\"fixture-immuneNode\">◊</span> immune node,
<span class=\"fixture-objectiveMarker\">◎</span> objective marker.</p>
<p>Pressures build to 3 → a lineage adapts (benefit + cost + spillover):
🔥 heat→Heat Shield, ☾ hunger→Dormancy, ⚗ toxin→Efflux, ◊ immunity→Cloak.</p>
<p><b>Select a loop direction to preview</b> (focus/hover/tap); press <b>Commit</b> or <b>Enter</b> to play it. <b>Escape</b> cancels.</p>`;
function legendPanel(open: boolean): HTMLElement {
const d = el("details", "help in-game-help");
if (open) d.setAttribute("open", "");
d.id = "in-game-help";
d.innerHTML = `<summary>Legend & controls</summary><div class="help-body">${LEGEND_HTML}</div>`;
return d;
}
function toggleHelp() {
const d = root.querySelector<HTMLElement>("#in-game-help");
if (d) { if (d.hasAttribute("open")) d.removeAttribute("open"); else d.setAttribute("open", ""); }
}
// ---------- standalone pick ----------
function renderStandalonePick() {
root.innerHTML = "";
const main = el("main", "screen");
main.id = "main";
main.tabIndex = -1;
main.append(el("h2", "", "Replay Standalone"), el("p", "muted", "Clean baseline lineages. No traits carry in or out."));
const list = el("div", "scenario-list");
for (const sc of SCENARIOS) {
const b = mkBtn("play-standalone", `Scenario ${sc.index + 1}: ${sc.title}`, () => {
const campaign = emptyCampaign(); // standalone: all unlocked for replay, clean
const state = enterScenario(campaign, sc.id, "standalone");
app.session = { state, campaign };
app.screen = "game";
renderGameWithControls();
announce(`Standalone replay: ${sc.title}.`);
});
const desc = el("div", "muted small", `${sc.subtitle} — ${sc.teaches}`);
const wrap = el("div", "scenario-item");
wrap.append(b, desc);
list.append(wrap);
}
list.append(mkBtn("menu", "Back", () => { app.screen = "title"; renderTitle(); }));
main.append(list);
const live = el("div", "sr-only");
live.setAttribute("data-region", "live");
live.setAttribute("aria-live", "polite");
root.append(main, live);
}
// ---------- game screen ----------
function renderGame() {
const session = app.session!;
const sc = SCENARIO_BY_ID[session.state.scenarioId]!;
root.innerHTML = "";
const main = el("main", "screen game-screen");
main.id = "main";
main.tabIndex = -1;
main.append(el("h1", "sr-only", "Adaptive Loop"));
const topbar = el("header", "topbar");
topbar.append(
el("h2", "scenario-title", `Scenario ${sc.index + 1}: ${sc.title}`),
el("span", "badge", `${sc.subtitle}`),
);
const controls = el("div", "controls");
controls.append(
mkBtn("menu", "Menu", () => { app.screen = "title"; renderTitle(); }),
mkBtn("save-quit", "Save & Quit", () => { if (app.session) saveCurrent(app.session); app.screen = "title"; renderTitle(); announce("Saved. Returning to title."); }),
session.state.mode === "campaign" ? mkBtn("retry", "Retry", () => doRetry()) : mkBtn("menu", "Back to menu", () => { app.screen = "title"; renderTitle(); }),
mkBtn("help", "Legend", () => toggleHelp()),
);
topbar.append(controls);
main.append(topbar);
main.append(legendPanel(false));
topbar.append(controls);
main.append(topbar);
const layout = el("div", "layout");
const leftRail = el("aside", "rail rail-left");
leftRail.setAttribute("aria-label", "Scenario status");
leftRail.append(
statRow("Objective", sc.winDescription),
statRow("Turn", `${session.state.turn} / ${sc.turnLimit}`),
statRow("Producer + Grazer", `${totalPersistent(session.state)}`),
statRow("Mode", session.state.mode),
);
if (session.state.mode === "campaign") {
leftRail.append(statRow("Campaign", `${session.campaign.unlocked.length}/${SCENARIOS.length} unlocked`));
const traits = inheritedTraitsText(session.campaign);
if (traits) leftRail.append(statRow("Inherited traits", traits));
}
const boardWrap = el("div", "board-wrap");
boardWrap.append(renderBoard(session.state));
const commitBar = el("div", "commit-bar");
const commitBtn = mkBtn("commit", "Commit rotation", () => doCommit(), { primary: true, keys: "Enter" });
commitBtn.disabled = !app.preview;
commitBar.append(commitBtn, mkBtn("cancel-preview", "Cancel preview (Esc)", () => clearPreview()));
boardWrap.append(commitBar);
const rightRail = el("aside", "rail rail-right");
rightRail.setAttribute("aria-label", "Pressures, traits, events");
rightRail.append(renderPressuresAndTraits(session.state));
const previewBox = el("div", "preview-box");
previewBox.id = "preview-box";
rightRail.append(previewBox);
const eventBox = el("div", "event-box");
eventBox.id = "event-box";
eventBox.setAttribute("role", "log");
eventBox.setAttribute("aria-label", "Last turn events");
renderEventsInto(eventBox);
rightRail.append(eventBox);
layout.append(leftRail, boardWrap, rightRail);
main.append(layout);
const live = el("div", "sr-only");
live.setAttribute("data-region", "live");
live.setAttribute("aria-live", "polite");
live.setAttribute("aria-atomic", "true");
root.append(main, live);
// focus first rotation control
const firstRot = main.querySelector<HTMLButtonElement>('[data-action="rotate"]');
firstRot?.focus();
updatePreviewBox();
}
function statRow(label: string, value: string): HTMLElement {
const row = el("div", "stat-row");
row.append(el("span", "stat-label", label), el("span", "stat-value", value));
return row;
}
function inheritedTraitsText(c: CampaignProgress): string {
const parts: string[] = [];
(["producer", "grazer"] as LineageId[]).forEach((lid) => {
for (const p of c.inherited[lid] ?? []) parts.push(`${lid}:${PRESSURES[p].traitName}`);
});
return parts.join(", ");
}
// ---------- SVG board ----------
function renderBoard(state: GameState): SVGElement {
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("viewBox", `0 0 ${VIEWBOX.w} ${VIEWBOX.h}`);
svg.setAttribute("class", "board");
svg.setAttribute("role", "img");
svg.setAttribute("aria-label", "Culture board: three interlocking loops of chambers.");
// loop ring outlines
(["A", "B", "C"] as const).forEach((L) => {
const pts = LOOP_POLYGONS[L].map((p) => `${p.x},${p.y}`).join(" ");
const poly = document.createElementNS(svgNS, "polygon");
poly.setAttribute("points", pts);
poly.setAttribute("class", `loop-ring loop-${L.toLowerCase()}`);
poly.setAttribute("data-loop", L);
poly.setAttribute("aria-hidden", "true");
svg.append(poly);
// loop label at center
const c = loopCenter(L);
const lbl = document.createElementNS(svgNS, "text");
lbl.setAttribute("x", String(c.x));
lbl.setAttribute("y", String(c.y));
lbl.setAttribute("class", "loop-label");
lbl.setAttribute("text-anchor", "middle");
lbl.textContent = L;
lbl.setAttribute("aria-hidden", "true");
svg.append(lbl);
});
const sc = SCENARIO_BY_ID[state.scenarioId]!;
const fixturesBySlot = new Map<number, typeof sc.fixtures>();
for (const f of sc.fixtures) fixturesBySlot.set(f.slot, [...(fixturesBySlot.get(f.slot) ?? []), f]);
// preview deltas
const preview = app.preview ? nextState(cloneState(state), app.preview).state : null;
const previewEvents = app.preview ? nextState(cloneState(state), app.preview).events : null;
// flow arrows (nutrient/toxin) for current or preview
drawFlowArrows(svg, preview ?? state);
for (let i = 0; i < 12; i++) {
const p = SLOT_POS[i]!;
const g = document.createElementNS(svgNS, "g");
g.setAttribute("transform", `translate(${p.x},${p.y})`);
g.setAttribute("class", "chamber-group");
g.dataset.slot = String(i);
const c = state.chambers[i]!;
const circle = document.createElementNS(svgNS, "circle");
circle.setAttribute("r", "30");
circle.setAttribute("class", "chamber");
g.append(circle);
// fixture glyphs
const fx = fixturesBySlot.get(i) ?? [];
for (const f of fx) {
const mark = document.createElementNS(svgNS, "text");
mark.setAttribute("class", `fixture fixture-${f.kind}`);
mark.setAttribute("text-anchor", "middle");
mark.setAttribute("y", "-34");
mark.textContent = fixtureGlyph(f.kind);
mark.setAttribute("aria-hidden", "true");
g.append(mark);
}
// species counts (shape glyph + short label + color, SPEC §13)
type Sp = { glyph: string; n: number; cls: string };
const sps: Sp[] = [];
if (c.producer) sps.push({ glyph: "●", n: c.producer, cls: "sp-producer" });
if (c.grazer) sps.push({ glyph: "▲", n: c.grazer, cls: "sp-grazer" });
if (c.phage) sps.push({ glyph: "◆", n: c.phage, cls: "sp-phage" });
const popTxt = document.createElementNS(svgNS, "text");
popTxt.setAttribute("class", "chamber-pop");
popTxt.setAttribute("text-anchor", "middle");
popTxt.setAttribute("y", "2");
if (sps.length === 0) {
popTxt.textContent = "·";
} else {
sps.forEach((s, i) => {
const t = document.createElementNS(svgNS, "tspan");
t.setAttribute("class", s.cls);
if (i > 0) t.setAttribute("dx", "4");
t.textContent = `${s.glyph}${s.n}`;
popTxt.append(t);
});
}
g.append(popTxt);
// resource line
const res: string[] = [];
if (c.nutrient) res.push(`N${c.nutrient}`);
if (c.heat) res.push(`🔥${c.heat}`);
if (c.toxin) res.push(`⚗${c.toxin}`);
if (res.length) {
const rt = document.createElementNS(svgNS, "text");
rt.setAttribute("class", "chamber-res");
rt.setAttribute("text-anchor", "middle");
rt.setAttribute("y", "16");
rt.textContent = res.join(" ");
g.append(rt);
}
// preview delta annotation
if (preview && previewEvents) {
const d = chamberDelta(state.chambers[i]!, preview.chambers[i]!);
if (d) {
const dt = document.createElementNS(svgNS, "text");
dt.setAttribute("class", "chamber-delta");
dt.setAttribute("text-anchor", "middle");
dt.setAttribute("y", "44");
dt.textContent = d;
g.append(dt);
}
}
svg.append(g);
}
return svg;
}
function fixtureGlyph(kind: string): string {
switch (kind) {
case "nutrientInlet": return "▽N";
case "heatSource": return "🔥s";
case "toxinInlet": return "▽T";
case "drain": return "▼";
case "immuneNode": return "◊";
case "objectiveMarker": return "◎";
default: return "";
}
}
function chamberDelta(a: GameState["chambers"][number], b: GameState["chambers"][number]): string {
const parts: string[] = [];
const fields: [keyof typeof a, string][] = [
["producer", "P"], ["grazer", "G"], ["phage", "H"], ["nutrient", "N"], ["toxin", "T"], ["heat", "🔥"],
];
for (const [f, lbl] of fields) {
const d = (b[f] as number) - (a[f] as number);
if (d !== 0) parts.push(`${lbl}${d > 0 ? "+" : ""}${d}`);
}
return parts.join(" ");
}
function drawFlowArrows(svg: SVGElement, state: GameState) {
const svgNS = "http://www.w3.org/2000/svg";
for (let i = 0; i < 12; i++) {
const c = state.chambers[i]!;
if (c.nutrient <= 0 && c.toxin <= 0) continue;
const out = outletOf(state, i);
const a = SLOT_POS[i]!;
const b = SLOT_POS[out]!;
const ln = document.createElementNS(svgNS, "line");
ln.setAttribute("x1", String(a.x));
ln.setAttribute("y1", String(a.y));
ln.setAttribute("x2", String(b.x));
ln.setAttribute("y2", String(b.y));
ln.setAttribute("class", `flow-arrow ${c.toxin > 0 ? "flow-toxin" : "flow-nutrient"}`);
ln.setAttribute("marker-end", "url(#arrowhead)");
ln.setAttribute("aria-hidden", "true");
svg.append(ln);
}
// arrowhead def
const defs = document.createElementNS(svgNS, "defs");
defs.innerHTML = `<marker id="arrowhead" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
<path d="M0,0 L6,3 L0,6 Z" fill="currentColor"/></marker>`;
svg.prepend(defs);
}
// ---------- pressures & traits panel ----------
function renderPressuresAndTraits(state: GameState): HTMLElement {
const box = el("div", "panel");
box.append(el("h3", "panel-h", "Pressures & Traits"));
(["producer", "grazer"] as LineageId[]).forEach((lid) => {
const lin = state.lineage[lid];
const row = el("div", "lineage-row");
row.append(el("div", "lineage-name", `${SPECIES[lid]!.name} (${lid})`));
(["heat", "hunger", "toxin", "immunity"] as PressureId[]).forEach((p) => {
const cell = el("div", "pressure-cell");
const unlocked = lin.unlocked[p];
cell.classList.toggle("unlocked", unlocked);
cell.setAttribute("title", `${PRESSURES[p].traitName}: ${lin.pressure[p]}/3${unlocked ? " (adapted)" : ""}`);
cell.append(el("span", "pressure-glyph", PRESSURES[p].glyph), el("span", "pressure-val", `${lin.pressure[p]}`));
if (unlocked) cell.append(el("span", "adapted-tag", "✓"));
row.append(cell);
});
box.append(row);
});
// environment responses
const envActive = (["heat", "hunger", "toxin", "immunity"] as PressureId[]).filter((p) => state.environmentActive[p]);
if (envActive.length) {
box.append(el("div", "env-row", "Active responses: " + envActive.map((p) => PRESSURES[p].glyph + p).join(", ")));
}
if (state.consecutiveObjectiveTurns > 0) {
box.append(el("div", "env-row", `Equilibrium held: ${state.consecutiveObjectiveTurns} turn(s).`));
}
return box;
}
// ---------- rotation controls (rendered under the board via commit bar; also a control grid) ----------
// We render the 6 rotation controls inside the board wrap.
function renderRotationControls(state: GameState): HTMLElement {
const grid = el("div", "rotation-grid");
grid.setAttribute("role", "group");
grid.setAttribute("aria-label", "Loop rotations");
(["A", "B", "C"] as const).forEach((L) => {
(["ccw", "cw"] as const).forEach((d) => {
const action: RotationAction = { loop: L, direction: d };
const b = el("button", "btn rot-btn", `Loop ${L} ${d.toUpperCase()}`);
b.dataset.action = "rotate";
b.dataset.loop = L;
b.dataset.dir = d;
const pred = predictLabel(state, action);
b.setAttribute("aria-label", `Select loop ${L} ${d === "cw" ? "clockwise" : "counter-clockwise"} (preview). Press Enter to commit. ${pred}`);
b.addEventListener("focus", () => setPreview(action));
b.addEventListener("mouseenter", () => setPreview(action));
// (no blur-clear: would clear the preview when focus moves to Commit)
b.addEventListener("mouseleave", () => { if (app.preview && sameAction(app.preview, action)) maybeClearPreview(); });
// pointer/touch: SELECT to preview (preview-then-commit, SPEC §13)
b.addEventListener("click", () => setPreview(action));
// keyboard: Enter / Space commits the focused (previewed) rotation
b.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") { e.preventDefault(); doCommit(action); }
});
grid.append(b);
});
});
return grid;
}
function sameAction(a: RotationAction, b: RotationAction) { return a.loop === b.loop && a.direction === b.direction; }
function predictLabel(state: GameState, action: RotationAction): string {
const r = nextState(cloneState(state), action);
if (r.state.outcome === "won") return "Predicted: WIN";
if (r.state.outcome === "collapsed") return "Predicted: collapse";
if (r.state.outcome === "expired") return "Predicted: turn limit reached";
return `Preview: turn ${r.state.turn}`;
}
// We need rotation controls visible — append into board wrap after render.
const _origRenderGame = renderGame;
function renderGameWithControls() {
_origRenderGame();
const boardWrap = root.querySelector(".board-wrap");
if (boardWrap && app.session) boardWrap.append(renderRotationControls(app.session.state));
}
// ---------- preview ----------
function setPreview(action: RotationAction) {
app.preview = action;
// re-render board + preview box without full screen rebuild
const boardWrap = root.querySelector(".board-wrap");
if (boardWrap && app.session) {
const oldSvg = boardWrap.querySelector("svg");
const newSvg = renderBoard(app.session.state);
if (oldSvg) oldSvg.replaceWith(newSvg);
const commitBtn = root.querySelector<HTMLButtonElement>('[data-action="commit"]');
if (commitBtn) commitBtn.disabled = false;
}
updatePreviewBox();
}
function maybeClearPreview() {
// only clear if no rotation control is focused
const focused = document.activeElement as HTMLElement | null;
if (focused && focused.dataset?.action === "rotate") return;
clearPreview();
}
function clearPreview() {
app.preview = null;
const boardWrap = root.querySelector(".board-wrap");
if (boardWrap && app.session) {
const oldSvg = boardWrap.querySelector("svg");
const newSvg = renderBoard(app.session.state);
if (oldSvg) oldSvg.replaceWith(newSvg);
const commitBtn = root.querySelector<HTMLButtonElement>('[data-action="commit"]');
if (commitBtn) commitBtn.disabled = true;
}
updatePreviewBox();
}
function updatePreviewBox() {
const box = root.querySelector("#preview-box");
if (!box || !app.session) return;
if (!app.preview) {
box.innerHTML = `<h3 class="panel-h">Preview</h3><p class="muted">Focus or hover a rotation to see the exact one-turn outcome.</p>`;
return;
}
const r = nextState(cloneState(app.session.state), app.preview);
const lines: string[] = [];
lines.push(`<h3 class="panel-h">Preview: Loop ${app.preview.loop} ${app.preview.direction.toUpperCase()}</h3>`);
if (r.state.outcome !== "playing") lines.push(`<p class="outcome outcome-${r.state.outcome}">Result: ${r.state.outcome.toUpperCase()}</p>`);
lines.push(`<p class="small">Turn ${app.session.state.turn} → ${r.state.turn}. Producer+Grazer ${totalPersistent(app.session.state)} → ${totalPersistent(r.state)}.</p>`);
// highlight key events
const keyEvents = r.events.filter((e) => ["pressure-up", "unlock", "env-response", "heat-shield", "heat-loss", "dormancy", "hunger-loss", "efflux-pay", "efflux-cost", "toxin-loss", "spillover", "immune-select", "immune-damage", "collapse", "win", "expire"].includes(e.kind));
if (keyEvents.length) {
lines.push(`<ul class="preview-events">${keyEvents.slice(0, 8).map((e) => `<li>${e.text}</li>`).join("")}</ul>`);
}
box.innerHTML = lines.join("");
}
// ---------- commit / flow ----------
function doCommit(forceAction?: RotationAction) {
if (!app.session) return;
const action = forceAction ?? app.preview;
if (!action) { announce("Select a rotation first."); return; }
if (app.session.state.outcome !== "playing") return;
const before = canonicalStringify(app.session.state);
const res = nextState(app.session.state, action);
const after = res.state;
if (canonicalStringify(after) === before) return; // rejected (shouldn't happen for playing)
const newSession: Session = { state: after, campaign: app.session.campaign };
app.session = newSession;
app.preview = null;
saveCurrent(newSession);
app.lastEvents = res.events;
showEvents(res.events);
announce(`Turn ${after.turn}: ${res.events.filter((e) => e.phase === "outcome").map((e) => e.text).join(" ") || "rotation resolved."}`);
if (after.outcome === "won") {
handleWin(newSession);
} else if (after.outcome === "collapsed" || after.outcome === "expired") {
renderGameWithControls();
announce(`Scenario ${after.outcome}. Press Retry to try again.`);
} else {
renderGameWithControls();
}
}
function renderEventsInto(box: HTMLElement) {
box.innerHTML = "";
box.append(el("h3", "panel-h", "Last turn (phase order)"));
const ul = el("ul", "event-list");
for (const e of app.lastEvents) {
const li = el("li", `event event-${e.phase}`, e.text);
ul.append(li);
}
if (app.lastEvents.length === 0) ul.append(el("li", "muted", "No turns committed yet."));
box.append(ul);
}
function showEvents(events: GameEvent[]) {
app.lastEvents = events;
const box = root.querySelector("#event-box");
if (box) renderEventsInto(box as HTMLElement);
}
function handleWin(session: Session) {
const sc = SCENARIO_BY_ID[session.state.scenarioId]!;
if (session.state.mode === "standalone") {
// standalone completion doesn't change campaign; show a win banner + back.
renderGameWithControls();
announce(`Standalone scenario complete: ${sc.title}.`);
return;
}
// campaign: offer trait preservation (0 or 1 newly unlocked, not already inherited)
const choices = eligibleTraits(session);
app.pendingWin = { session, choices };
app.screen = "trait-choice";
renderTraitChoice();
}
function renderTraitChoice() {
const pw = app.pendingWin!;
const sc = SCENARIO_BY_ID[pw.session.state.scenarioId]!;
root.innerHTML = "";
const main = el("main", "screen trait-screen");
main.id = "main";
main.tabIndex = -1;
const isLast = sc.index === SCENARIOS.length - 1;
main.append(el("h2", "", isLast ? "Campaign Victory!" : `Scenario ${sc.index + 1} complete`));
main.append(el("p", "muted", isLast ? "You stabilized the final equilibrium. The campaign is won." : `You may preserve zero or one trait that adapted this scenario.`));
const panel = el("div", "menu");
panel.append(mkBtn("skip-trait", "Preserve nothing", () => advanceCampaign(null)));
for (const ch of pw.choices) {
const label = `Keep ${SPECIES[ch.lineage]!.name} ${PRESSURES[ch.pressure].traitName} (${ch.lineage})`;
panel.append(mkBtn("keep-trait", label, () => advanceCampaign(ch), { primary: true }));
}
main.append(panel);
const live = el("div", "sr-only");
live.setAttribute("data-region", "live");
live.setAttribute("aria-live", "polite");
root.append(main, live);
panel.querySelector<HTMLButtonElement>('[data-action="skip-trait"]')?.focus();
announce(isLast ? "Campaign victory!" : "Choose a trait to preserve, or nothing.");
}
function advanceCampaign(trait: { lineage: LineageId; pressure: PressureId } | null) {
const pw = app.pendingWin!;
let campaign = unlockNext(pw.session.campaign, pw.session.state.scenarioId);
campaign = preserveTrait(campaign, trait);
clearSave(store);
const sc = SCENARIO_BY_ID[pw.session.state.scenarioId]!;
if (sc.index === SCENARIOS.length - 1) {
// campaign victory
app.pendingWin = null;
app.session = null;
app.screen = "title";
renderTitle();
announce("Campaign complete. Returning to title.");
return;
}
const nextId = nextScenarioId(campaign);
const state = enterScenario(campaign, nextId, "campaign");
app.session = { state, campaign };
app.pendingWin = null;
app.screen = "game";
renderGameWithControls();
announce(`Entering ${SCENARIO_BY_ID[nextId]!.title}.`);
}
// ---------- retry ----------
function doRetry() {
if (!app.session) return;
app.session = retrySession(app.session);
app.preview = null;
renderGameWithControls();
announce("Scenario reset to entry snapshot.");
}
// ---------- title actions ----------
function startNewCampaign() {
clearSave(store);
app.session = startCampaign();
app.screen = "game";
renderGameWithControls();
announce(`New campaign: ${SCENARIO_BY_ID[app.session.state.scenarioId]!.title}.`);
}
function continueGame() {
const loaded = loadEnvelope(store);
if (!loaded.env) { renderTitle(); return; }
app.session = { state: loaded.env.state, campaign: loaded.env.campaign };
app.screen = "game";
renderGameWithControls();
announce("Continued saved game.");
}
// ---------- keyboard (Escape cancels preview) ----------
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && app.preview) {
clearPreview();
e.preventDefault();
}
});
// ---------- bootstrap ----------
function boot() {
renderTitle();
renderTitle();
}
boot();
// re-export for potential tooling
export { renderGameWithControls };