// Adaptive Loop — presentation controller. Holds a Session, renders views, and // routes every committed action through the pure domain transition (preview calls // the same nextState on cloned state, so preview == commit). Public controls only; // no domain state or localStorage is injected to fake gameplay. import { ALL_ACTIONS, LINEAGE_IDS, LOOP_IDS, PRESSURE_IDS, PRESSURES, FIXTURE_META, SPECIES_NAMES, type FixtureKind } from "./domain/constants"; import { nextState, outletOf } from "./domain/pipeline"; import { cloneState } from "./domain/serialize"; import { fixturesFor, newlyUnlockedTraits } from "./domain/scenario"; import { SCENARIOS, getScenario } from "./content/scenarios"; import { totalProducer, totalGrazer, totalPhage, totalToxin } from "./domain/derived"; import { MemoryStorage, save, load, clear, type StorageAdapter } from "./persistence/save"; import { advanceAfterWin, eligiblePreservations, fromEnvelope, retry, startCampaign, startStandalone, toEnvelope } from "./session"; import { chamberXY, isShared, LOOP_COLORS, loopPoints, loopsOf, VIEWBOX } from "./presentation/geometry"; import type { Chamber, GameEvent, GameState, LineageId, LoopId, Outcome, PressureId, RotationAction, TransitionResult } from "./domain/types"; const STORAGE: StorageAdapter = typeof localStorage !== "undefined" ? localStorage : new MemoryStorage(); type View = "title" | "standalone-select" | "game" | "trait-choice" | "victory" | "malformed"; type App = { view: View; session: ReturnType | null; selected: RotationAction | null; preview: TransitionResult | null; pendingChoiceSession: ReturnType | null; // session at moment of win, before advance }; let app: App = { view: "title", session: null, selected: null, preview: null, pendingChoiceSession: null }; const appEl = (): HTMLElement => document.getElementById("app")!; // ── helpers ────────────────────────────────────────────────────────────────── function announce(text: string): void { const el = document.querySelector('[data-region="live"]'); if (!el) return; el.textContent = ""; // re-post so assistive tech re-announces window.setTimeout(() => { el.textContent = text; }, 30); } function predictLabel(result: TransitionResult): string { const o = result.state.outcome; if (o === "won") return "Predicted: WIN"; if (o === "collapsed") return "Predicted: ecosystem collapse"; if (o === "expired") return "Predicted: turn limit reached"; return `Predicted turn ${result.state.turn}`; } function computePreview(state: GameState, action: RotationAction): TransitionResult { return nextState(cloneState(state), action); } // ── rendering: title ────────────────────────────────────────────────────────── function renderTitle(): void { const hasSave = load(STORAGE) !== null; appEl().innerHTML = `

Adaptive Loop

How to play${legendHtml()}

A calm deterministic strategy puzzle in a microfluidic culture dish. Rotate overlapping loops to move chambers and redirect flow; provoke adaptations, then exploit their costs.

${legendHtml()}
`; document.getElementById("continue-btn")?.addEventListener("click", () => { const env = load(STORAGE); if (!env) return; app.session = fromEnvelope(env); app.view = "game"; app.selected = null; app.preview = null; render(); }); document.getElementById("new-campaign-btn")?.addEventListener("click", () => { if (load(STORAGE) && !confirm("Start a new campaign? Current progress will be lost.")) return; clear(STORAGE); app.session = startCampaign(); app.view = "game"; app.selected = null; app.preview = null; saveCurrent(); render(); }); document.getElementById("standalone-btn")?.addEventListener("click", () => { app.view = "standalone-select"; render(); }); } function legendHtml(): string { const species = `

Species (shape + color + label): ● P ${SPECIES_NAMES.producer} eats nutrient; ■ G ${SPECIES_NAMES.grazer} eats producer; ▲ H ${SPECIES_NAMES.phage} eats grazer.

`; const pressures = `

Pressures: ${PRESSURE_IDS.map((p) => `${PRESSURES[p].glyph} ${PRESSURES[p].label} → ${PRESSURES[p].traitName}`).join(" ")}

`; const fixtures = `

Fixtures: ${(Object.keys(FIXTURE_META) as FixtureKind[]).map((k) => `${FIXTURE_META[k].glyph} ${FIXTURE_META[k].label}`).join(" ")}

`; const how = `

How to play: Select a loop rotation (focus/hover/tap) to preview exactly one turn, then press Commit. Each rotation moves chamber payloads and reclaims that loop's shared chambers, redirecting nutrient/toxin flow. Win each scenario's objective before the turn limit; if producers + grazers all die, the ecosystem collapses.

`; return `${how}${species}${pressures}${fixtures}`; } // ── rendering: standalone select ────────────────────────────────────────────── function renderStandaloneSelect(): void { // Standalone can replay any scenario with clean baseline. appEl().innerHTML = `

Replay Standalone

    ${SCENARIOS.map((s) => `
  • `).join("")}
`; document.getElementById("menu-btn")?.addEventListener("click", () => { app.view = "title"; render(); }); document.querySelectorAll("[data-scenario]").forEach((b) => b.addEventListener("click", () => { app.session = startStandalone(b.dataset.scenario!); app.view = "game"; app.selected = null; app.preview = null; render(); })); } // ── rendering: game ─────────────────────────────────────────────────────────── function renderGame(): void { const s = app.session!; const sc = getScenario(s.scenarioId); appEl().innerHTML = `

${sc.name} — ${sc.subtitle}

Legend${legendHtml()}
`; document.getElementById("menu-btn")?.addEventListener("click", () => { saveCurrent(); app.view = "title"; render(); }); document.getElementById("save-quit-btn")?.addEventListener("click", () => { saveCurrent(); app.view = "title"; announce("Saved."); render(); }); drawBoard(); renderObjective(); renderPressures(s.state); renderControls(); renderEvents(lastEvents); refreshPreview(); } let lastEvents: GameEvent[] = []; function renderEvents(events: GameEvent[]): void { const el = document.querySelector('[data-region="events"]'); if (!el) return; if (events.length === 0) { el.innerHTML = `

Select a rotation to preview the tick.

`; return; } el.innerHTML = events.map((e) => `

${e.kind} ${escapeHtml(e.text)}

`).join(""); } function escapeHtml(s: string): string { return s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ } as Record)[c]); } function renderObjective(): void { const el = document.querySelector('[data-region="objective"]'); if (!el || !app.session) return; const s = app.session; const sc = getScenario(s.scenarioId); el.innerHTML = `

${sc.name} (${sc.subtitle})

${sc.winDescription}

Turn ${s.state.turn} / ${sc.turnLimit}${terminalNote(s.state.outcome)}

Totals — P:${totalProducer(s.state)} G:${totalGrazer(s.state)} H:${totalPhage(s.state)} T:${totalToxin(s.state)}

Mode: ${s.mode}. ${s.mode === "campaign" ? `Unlocked: ${s.unlockedScenarios.length}/${SCENARIOS.length}.` : "Standalone (clean baseline)."}

`; } function terminalNote(o: Outcome): string { if (o === "won") return ` — WON`; if (o === "collapsed") return ` — COLLAPSED`; if (o === "expired") return ` — EXPIRED`; return ""; } function renderPressures(state: GameState): void { const el = document.querySelector('[data-region="pressures"]'); if (!el) return; const rows = LINEAGE_IDS.map((lin) => { const cells = PRESSURE_IDS.map((p) => { const meta = PRESSURES[p]; const val = state.lineage[lin].pressure[p]; const unlocked = state.lineage[lin].unlocked[p]; const env = state.environmentActive[p]; return ` ${meta.glyph}${val}${unlocked ? '✓' : ""}`; }).join(""); return `
${lin === "producer" ? SPECIES_NAMES.producer : SPECIES_NAMES.grazer}${cells}
`; }).join(""); el.innerHTML = `

Pressures & traits

${rows}

Track 0–3; at 3 a trait unlocks next turn and a global response activates. ✓ = adapted.

`; } function renderControls(): void { buildControls(); updateControlStates(); } function buildControls(): void { const el = document.getElementById("controls"); if (!el || !app.session) return; const s = app.session; const terminal = s.state.outcome !== "playing"; const buttons = ALL_ACTIONS.map((a) => { const preview = computePreview(s.state, a); return ``; }).join(""); el.innerHTML = `
${buttons}
${terminal ? terminalActionsHtml(s.state.outcome) : ""}
`; // rotation interactions: select + preview only (commit is a separate control) document.querySelectorAll(".rotate-btn").forEach((b) => { const action = { loop: b.dataset.loop as LoopId, direction: b.dataset.dir as "cw" | "ccw" }; b.addEventListener("click", () => selectAction(action)); b.addEventListener("focus", () => selectAction(action)); b.addEventListener("mouseenter", () => selectAction(action)); }); document.getElementById("commit-btn")?.addEventListener("click", commit); document.getElementById("cancel-btn")?.addEventListener("click", cancelPreview); wireTerminalActions(); } // Toggle selection styling + commit/cancel enabled state IN PLACE (no DOM rebuild), // so hovering between controls never detaches the commit button mid-interaction. function updateControlStates(): void { if (!app.session) return; const terminal = app.session.state.outcome !== "playing"; document.querySelectorAll(".rotate-btn").forEach((b) => { const match = app.selected && b.dataset.loop === app.selected.loop && b.dataset.dir === app.selected.direction; b.classList.toggle("selected", !!match); }); const commit = document.getElementById("commit-btn") as HTMLButtonElement | null; const cancel = document.getElementById("cancel-btn") as HTMLButtonElement | null; if (commit) commit.disabled = !app.selected || terminal; if (cancel) cancel.disabled = !app.selected; const termEl = document.getElementById("terminal-actions"); if (termEl) { const want = terminal ? terminalActionsHtml(app.session.state.outcome) : ""; if (termEl.innerHTML !== want) { termEl.innerHTML = want; wireTerminalActions(); } } } function terminalActionsHtml(o: Outcome): string { if (o === "won") { if (app.session!.mode === "campaign") return `

Scenario complete!

`; return `

Scenario complete!

`; } if (o === "collapsed") return `

The ecosystem collapsed.

`; if (o === "expired") return `

Turn limit reached.

`; return ""; } function wireTerminalActions(): void { document.getElementById("retry-btn")?.addEventListener("click", () => { if (!app.session) return; app.session = retry(app.session); app.selected = null; app.preview = null; lastEvents = []; render(); announce("Retried scenario."); }); document.getElementById("continue-win-btn")?.addEventListener("click", onWinContinue); } function onWinContinue(): void { if (!app.session) return; if (app.session.mode === "standalone") { app.view = "title"; render(); return; } const eligible = eligiblePreservations(app.session); if (eligible.length === 0) { finalizeCampaignAdvance(null); } else { app.pendingChoiceSession = app.session; app.view = "trait-choice"; render(); } } function finalizeCampaignAdvance(choice: { lineage: LineageId; pressure: PressureId } | null): void { if (!app.session) return; const advanced = advanceAfterWin(app.session, choice); if (advanced === null) { app.view = "victory"; app.session = null; clear(STORAGE); render(); announce("Campaign victory!"); return; } app.session = advanced; app.view = "game"; app.selected = null; app.preview = null; lastEvents = []; saveCurrent(); render(); } function renderTraitChoice(): void { const base = app.pendingChoiceSession!; const unlocked = newlyUnlockedTraits(base.state); const options: { lineage: LineageId; pressure: PressureId }[] = []; for (const lin of LINEAGE_IDS) for (const p of unlocked[lin]) options.push({ lineage: lin, pressure: p }); appEl().innerHTML = `

Preserve a trait?

A trait unlocked this scenario. Preserve one to carry its benefit — and its cost — into the next scenario.

`; document.querySelectorAll("[data-trait]").forEach((b) => b.addEventListener("click", () => finalizeCampaignAdvance(options[Number(b.dataset.trait)]))); document.getElementById("decline-trait-btn")?.addEventListener("click", () => finalizeCampaignAdvance(null)); } function renderVictory(): void { appEl().innerHTML = `

Campaign Complete

You held the culture stable across all five scenarios. The Adaptive Loop is closed.

`; document.getElementById("menu-btn")?.addEventListener("click", () => { app.view = "title"; render(); }); } // ── selection / preview / commit ────────────────────────────────────────────── function selectAction(action: RotationAction): void { if (!app.session || app.session.state.outcome !== "playing") return; if (app.selected && app.selected.loop === action.loop && app.selected.direction === action.direction) return; // no-op reselect app.selected = action; app.preview = computePreview(app.session.state, action); refreshPreview(); updateControlStates(); } function cancelPreview(): void { app.selected = null; app.preview = null; refreshPreview(); updateControlStates(); } function refreshPreview(): void { drawBoard(); if (app.preview) { renderPressures(app.preview.state); // pressure increments visible during preview (Pass-1 fix) renderEvents(keyEvents(app.preview.events)); } else if (app.session) { renderPressures(app.session.state); renderEvents(lastEvents); } } function keyEvents(events: GameEvent[]): GameEvent[] { // A concise, scan-friendly subset that still surfaces movement, flow, overflow, // pressure increments, adaptations (benefit/cost/spillover), and the outcome. const keep = new Set([ "rotate", "nutrient-overflow", "toxin-overflow", "producer-growth", "growth-suppressed", "grazer-feed", "grazer-denied", "phage-feed", "phage-starve", "cloak-cost", "migrate", "trait-unlock", "env-response", "pressure-up", "heat-loss", "heat-prevented", "heat-spillover", "hunger-loss", "hunger-prevented", "toxin-loss", "toxin-cost", "toxin-spillover", "immune-select", "immune-retarget", "immune-damage", "fixture-overflow", "outcome", ]); return events.filter((e) => keep.has(e.kind)); } function commit(): void { if (!app.session || !app.selected) return; const before = app.session; if (before.state.outcome !== "playing") return; // rejected // Single pure transition: events + canonical state in one call (preview == commit). const result = nextState(before.state, app.selected); app.session = { ...before, state: result.state }; app.selected = null; app.preview = null; lastEvents = keyEvents(result.events); saveCurrent(); render(); const o = result.state.outcome; announce(o === "playing" ? `Turn ${result.state.turn}.` : `Turn ${result.state.turn}: ${o}.`); } function saveCurrent(): void { if (app.session) save(STORAGE, toEnvelope(app.session, Date.now())); } // ── board SVG ───────────────────────────────────────────────────────────────── function drawBoard(): void { const svg = document.getElementById("board"); if (!svg || !app.session) return; const state = app.session.state; const previewState = app.preview?.state ?? null; const fx = fixturesFor(state.scenarioId); // build parts const rings = LOOP_IDS.map((L) => ``).join(""); // flow arrows along owner edges — during preview, reflect the post-rotation flow const arrows = flowArrows(previewState ?? state); const nodes = state.chambers.map((c, slot) => chamberSvg(slot, c, fx[slot], previewState)).join(""); // selection highlight ring outline svg.innerHTML = `${rings}${arrows}${nodes}`; } function flowArrows(state: GameState): string { const drawn = new Set(); const parts: string[] = []; for (let slot = 0; slot < 12; slot++) { const out = outletOf(slot, state); const key = `${slot}-${out}`; if (drawn.has(key)) continue; drawn.add(key); const [x1, y1] = chamberXY(slot); const [x2, y2] = chamberXY(out); const mx = (x1 + x2) / 2; const my = (y1 + y2) / 2; parts.push(``); } return parts.join(""); } function chamberSvg(slot: number, c: Chamber, fixtures: FixtureKind[], preview: GameState | null): string { const [x, y] = chamberXY(slot); const fixtureMarks = fixtures.map((k) => `${FIXTURE_META[k].glyph}`).join(""); const pops = (["producer", "grazer", "phage"] as const).map((sp) => c[sp] > 0 ? `${popGlyph(sp)}${c[sp]}` : "").join(""); const delta = preview ? populationDelta(c, preview.chambers[slot]) : ""; const res = `N${c.nutrient}${c.heat > 0 ? ` 🔥${c.heat}` : ""}${c.toxin > 0 ? ` ⚗${c.toxin}` : ""}`; const label = `${slot}${isShared(slot) ? ` ${loopsOf(slot).join("")}` : ""}`; return ` ${fixtureMarks} ${pops} ${res}${label}${delta} `; } function popGlyph(sp: "producer" | "grazer" | "phage"): string { return sp === "producer" ? "●" : sp === "grazer" ? "■" : "▲"; } function populationDelta(now: Chamber, next: Chamber): string { const diffs: string[] = []; (["producer", "grazer", "phage"] as const).forEach((sp) => { const d = next[sp] - now[sp]; if (d !== 0) diffs.push(`${popGlyph(sp)}${d > 0 ? "+" : ""}${d}`); }); ["nutrient", "toxin"].forEach((f) => { const d = (next as unknown as Record)[f] - (now as unknown as Record)[f]; if (d !== 0) diffs.push(`${f === "nutrient" ? "N" : "T"}${d > 0 ? "+" : ""}${d}`); }); if (diffs.length === 0) return ""; return `${diffs.join(" ")}`; } // ── router ──────────────────────────────────────────────────────────────────── function render(): void { switch (app.view) { case "title": renderTitle(); break; case "standalone-select": renderStandaloneSelect(); break; case "game": renderGame(); break; case "trait-choice": renderTraitChoice(); break; case "victory": renderVictory(); break; default: renderTitle(); } } // global keyboard: Escape cancels preview window.addEventListener("keydown", (e) => { if (e.key === "Escape" && app.view === "game" && app.selected) { cancelPreview(); } }); // boot function boot(): void { const env = load(STORAGE); app.view = "title"; app.session = env ? fromEnvelope(env) : null; render(); } boot();