// Adaptive Loop — the one pure transition. nextState(state, action) runs the // fixed 8-phase tick (SPEC §7) and derives deterministic events (SPEC §8, §12). // Never mutates its input. Preview calls this on a clone; commit calls it for real. import type { GameState, RotationAction, GameEvent, TurnResult, LineageId, PressureId, Chamber, } from "./types"; import { LINEAGE_IDS, PRESSURE_IDS } from "./types"; import { LOOPS, LOOP_SHARED_SLOTS, dirStep, CAP, clamp } from "./constants"; import { cloneState } from "./serialize"; import { outletOf, totalPersistent, sustainedHolds, evaluateWin } from "./scenario"; import { SCENARIO_BY_ID } from "../content/scenarios"; import type { FixtureDef } from "../content/scenarios"; const ALL_ACTIONS: RotationAction[] = [ { loop: "A", direction: "cw" }, { loop: "A", direction: "ccw" }, { loop: "B", direction: "cw" }, { loop: "B", direction: "ccw" }, { loop: "C", direction: "cw" }, { loop: "C", direction: "ccw" }, ]; export function allActions(): RotationAction[] { return ALL_ACTIONS.map((a) => ({ ...a })); } function fixturesOf(state: GameState): FixtureDef[] { return SCENARIO_BY_ID[state.scenarioId]?.fixtures ?? []; } function isImmuneNode(state: GameState, slot: number): boolean { return fixturesOf(state).some((f) => f.slot === slot && f.kind === "immuneNode"); } function popOf(c: Chamber, lid: LineageId): number { return lid === "producer" ? c.producer : c.grazer; } function addPop(c: Chamber, lid: LineageId, delta: number) { if (lid === "producer") c.producer = clamp(c.producer + delta, 0, CAP); else c.grazer = clamp(c.grazer + delta, 0, CAP); } function lineageFood(c: Chamber, lid: LineageId): number { return lid === "producer" ? c.nutrient : c.producer; } function speciesFood(c: Chamber, sp: "producer" | "grazer" | "phage"): number { if (sp === "producer") return c.nutrient; if (sp === "grazer") return c.producer; return c.grazer; } // Locally-active trait predicates (SPEC §8 "global unlock ≠ always active"). function heatActive(state: GameState, lid: LineageId, c: Chamber): boolean { return state.lineage[lid].unlocked.heat && c.heat >= 2; } function hungerActive(state: GameState, lid: LineageId, c: Chamber): boolean { return state.lineage[lid].unlocked.hunger && lineageFood(c, lid) === 0; } function cloakActive(state: GameState, lid: LineageId, slot: number): boolean { return state.lineage[lid].unlocked.immunity && isImmuneNode(state, slot); } function ev(e: GameEvent): GameEvent { return e; } export function nextState( input: GameState, action: RotationAction, opts?: { freezeOwnership?: boolean }, ): TurnResult { // Terminal/illegal: reject without changing domain state. if (input.outcome !== "playing") { return { state: input, events: [ev({ phase: "outcome", kind: "rejected", text: `Terminal state (${input.outcome}); action rejected.` })], }; } const state = cloneState(input); const events: GameEvent[] = []; const L = action.loop; const step = dirStep(action.direction); const loopSlots = LOOPS[L]; // ---- Phase 1: rotate & reconnect --------------------------------------- const rotSnap = loopSlots.map((s) => state.chambers[s]); for (let i = 0; i < 6; i++) { const dest = loopSlots[(i + step) % 6]!; state.chambers[dest] = rotSnap[i]!; } state.loops[L].direction = action.direction; if (!opts?.freezeOwnership) { for (const slot of LOOP_SHARED_SLOTS[L]) state.sharedOwner[String(slot)] = L; } events.push( ev({ phase: "rotate", kind: "rotate", text: `Loop ${L} rotated ${action.direction.toUpperCase()}: chambers shift, ownership reclaimed.`, }), ); // ---- Phase 2: channel flow (nutrient & toxin along outlets) ------------ { const snapN = state.chambers.map((c) => c.nutrient); const snapT = state.chambers.map((c) => c.toxin); const sendN = new Array(12).fill(0); const sendT = new Array(12).fill(0); const recvN = new Array(12).fill(0); const recvT = new Array(12).fill(0); for (let i = 0; i < 12; i++) { const out = outletOf(state, i); if (snapN[i]! > 0) { sendN[i] = 1; recvN[out]! += 1; } if (snapT[i]! > 0) { sendT[i] = 1; recvT[out]! += 1; } } for (let i = 0; i < 12; i++) { const nn = clamp(snapN[i]! - sendN[i]! + recvN[i]!, 0, CAP); const nt = clamp(snapT[i]! - sendT[i]! + recvT[i]!, 0, CAP); const overN = snapN[i]! - sendN[i]! + recvN[i]! - nn; const overT = snapT[i]! - sendT[i]! + recvT[i]! - nt; state.chambers[i]!.nutrient = nn; state.chambers[i]!.toxin = nt; if (recvN[i]! > 0) events.push(ev({ phase: "flow", kind: "nutrient", slot: i, text: `+${recvN[i]} nutrient arrived; ${overN > 0 ? `${overN} overflow discarded` : "no overflow"}.` })); if (recvT[i]! > 0) events.push(ev({ phase: "flow", kind: "toxin", slot: i, text: `+${recvT[i]} toxin arrived; ${overT > 0 ? `${overT} overflow discarded` : "no overflow"}.` })); } } // ---- Phase 3: producer growth ------------------------------------------ { const snap = state.chambers.map((c) => ({ ...c })); for (let i = 0; i < 12; i++) { const cur = state.chambers[i]!; const s = snap[i]!; if (s.producer > 0 && s.nutrient > 0) { cur.nutrient -= 1; // consumed unconditionally (SPEC §7 phase 3) const suppressed = heatActive(state, "producer", s); const gain = suppressed ? 0 : 1; const before = cur.producer; cur.producer = clamp(cur.producer + gain, 0, CAP); const wasted = before + gain - cur.producer; events.push( ev({ phase: "growth", kind: suppressed ? "growth-suppressed" : "growth", slot: i, lineage: "producer", text: suppressed ? "Heat-adapted: feeding consumes nutrient but adds no population." : `Producer +${cur.producer - before}${wasted > 0 ? ` (${wasted} overflow)` : ""}.`, }), ); } } } // ---- Phase 4: biological interactions (grazer then phage) -------------- runGrazerSubphase(state, events); runPhageSubphase(state, events); // ---- Phase 5: migration (producer, grazer, phage) --------------------- migrateSpecies(state, "producer", events); migrateSpecies(state, "grazer", events); migrateSpecies(state, "phage", events); // ---- Phase 6: evolution & environmental response activation ----------- for (const lid of LINEAGE_IDS) { const lin = state.lineage[lid]; for (const p of PRESSURE_IDS) { if (lin.pressure[p] >= 3 && !lin.unlocked[p]) { lin.unlocked[p] = true; events.push(ev({ phase: "evolve", kind: "unlock", lineage: lid, pressure: p, text: `${lid} unlocked ${p} trait.` })); } } } for (const p of PRESSURE_IDS) { const anyAt3 = LINEAGE_IDS.some((lid) => state.lineage[lid].pressure[p] >= 3); if (anyAt3 && !state.environmentActive[p]) { state.environmentActive[p] = true; events.push(ev({ phase: "evolve", kind: "env-response", pressure: p, text: `Global ${p} response active.` })); } } // ---- Phase 7: fixtures, exposure, pressure consequences --------------- runFixturesAndPressures(state, events); // ---- Phase 8: outcome & turn finalization ------------------------------ const resolvedTurn = input.turn + 1; const consecutive = sustainedHolds(state) ? input.consecutiveObjectiveTurns + 1 : 0; const collapsed = totalPersistent(state) === 0; let outcome: GameState["outcome"] = "playing"; if (collapsed) { outcome = "collapsed"; events.push(ev({ phase: "outcome", kind: "collapse", text: "Ecosystem collapse: no producer or grazer remains." })); } else if (evaluateWin(state, resolvedTurn, consecutive)) { outcome = "won"; events.push(ev({ phase: "outcome", kind: "win", text: "Objective achieved." })); } else if (resolvedTurn >= (SCENARIO_BY_ID[state.scenarioId]?.turnLimit ?? Infinity)) { outcome = "expired"; events.push(ev({ phase: "outcome", kind: "expire", text: "Turn limit reached." })); } state.turn = resolvedTurn; state.consecutiveObjectiveTurns = consecutive; state.outcome = outcome; state.actionLog = [...input.actionLog, { loop: action.loop, direction: action.direction }]; return { state, events }; } // --- phase 4 helpers -------------------------------------------------------- function runGrazerSubphase(state: GameState, events: GameEvent[]) { const snap = state.chambers.map((c) => ({ ...c })); for (let i = 0; i < 12; i++) { const cur = state.chambers[i]!; const s = snap[i]!; if (s.grazer <= 0) continue; const dormantPrey = hungerActive(state, "producer", s); const edible = s.producer > 0 && !dormantPrey; if (!edible) continue; const cloak = cloakActive(state, "producer", i); const remove = cloak ? Math.min(2, s.producer) : 1; cur.producer = clamp(cur.producer - remove, 0, CAP); const before = cur.grazer; cur.grazer = clamp(cur.grazer + 1, 0, CAP); events.push( ev({ phase: "interact", kind: cloak ? "graze-cloak" : "graze", slot: i, lineage: "grazer", text: cloak ? `Grazer eats cloaked producer: removes ${remove} prey (cloak cost), grazer +${cur.grazer - before}.` : `Grazer consumes producer, grazer +${cur.grazer - before}.`, }), ); } } function runPhageSubphase(state: GameState, events: GameEvent[]) { const snap = state.chambers.map((c) => ({ ...c })); for (let i = 0; i < 12; i++) { const cur = state.chambers[i]!; const s = snap[i]!; if (s.phage <= 0) continue; const dormantPrey = hungerActive(state, "grazer", s); const edible = s.grazer > 0 && !dormantPrey; if (edible) { const cloak = cloakActive(state, "grazer", i); const remove = cloak ? Math.min(2, s.grazer) : 1; cur.grazer = clamp(cur.grazer - remove, 0, CAP); const before = cur.phage; cur.phage = clamp(cur.phage + 1, 0, CAP); events.push( ev({ phase: "interact", kind: cloak ? "phage-cloak" : "phage", slot: i, text: cloak ? `Phage eats cloaked grazer: removes ${remove} prey (cloak cost), phage +${cur.phage - before}.` : `Phage consumes grazer, phage +${cur.phage - before}.`, }), ); } else { const before = cur.phage; cur.phage = clamp(cur.phage - 1, 0, CAP); events.push(ev({ phase: "interact", kind: "phage-starve", slot: i, text: `Phage cannot feed, phage ${before}→${cur.phage}.` })); } } } // --- phase 5 helper ---------------------------------------------------------- function migrateSpecies(state: GameState, sp: "producer" | "grazer" | "phage", events: GameEvent[]) { const snap = state.chambers.map((c) => ({ ...c })); const send = new Array(12).fill(0); const recv = new Array(12).fill(0); for (let i = 0; i < 12; i++) { const s = snap[i]!; if (s[sp] < 2) continue; // Dormancy prevents migration for lineages (phage has no traits). if (sp !== "phage") { const lid = sp as LineageId; if (hungerActive(state, lid, s)) continue; } const dest = outletOf(state, i); if (speciesFood(snap[dest]!, sp) > speciesFood(s, sp)) { send[i] = 1; recv[dest]! += 1; } } for (let i = 0; i < 12; i++) { if (send[i] === 0 && recv[i] === 0) continue; const before = state.chambers[i]![sp]; const next = clamp(before - send[i]! + recv[i]!, 0, CAP); state.chambers[i]![sp] = next; if (send[i] || recv[i]) { events.push( ev({ phase: "migrate", kind: "migrate", slot: i, text: `${sp}: ${send[i] ? "−1 out" : "stays"}${recv[i] ? `, +${recv[i]} in` : ""} (${before}→${next}).`, }), ); } } } // --- phase 7: fixtures + exposure + consequences ---------------------------- function runFixturesAndPressures(state: GameState, events: GameEvent[]) { const fx = fixturesOf(state); const nutrientInlets = fx.filter((f) => f.kind === "nutrientInlet").map((f) => f.slot); const heatSources = fx.filter((f) => f.kind === "heatSource").map((f) => f.slot); const toxinInlets = fx.filter((f) => f.kind === "toxinInlet").map((f) => f.slot); const drains = fx.filter((f) => f.kind === "drain").map((f) => f.slot); const immuneNodes = fx.filter((f) => f.kind === "immuneNode").map((f) => f.slot).sort((a, b) => a - b); // (1) nutrient inlets for (const slot of nutrientInlets) { const add = state.environmentActive.hunger ? 1 : 2; state.chambers[slot]!.nutrient = clamp(state.chambers[slot]!.nutrient + add, 0, CAP); } // (2) heat sources, then global heat -1 for (const slot of heatSources) { const add = state.environmentActive.heat ? 3 : 2; state.chambers[slot]!.heat = clamp(state.chambers[slot]!.heat + add, 0, CAP); } for (let i = 0; i < 12; i++) state.chambers[i]!.heat = clamp(state.chambers[i]!.heat - 1, 0, CAP); // (3) toxin inlets for (const slot of toxinInlets) { const add = state.environmentActive.toxin ? 3 : 2; state.chambers[slot]!.toxin = clamp(state.chambers[slot]!.toxin + add, 0, CAP); } // (4) drains for (const slot of drains) { state.chambers[slot]!.toxin = clamp(state.chambers[slot]!.toxin - 2, 0, CAP); } events.push(ev({ phase: "fixtures", kind: "fixtures", text: "Fixtures applied: inlets, sources, drains." })); // (5) immunity target selection const immuneDamage = state.environmentActive.immunity ? 3 : 2; const selections: { slot: number; lineage: LineageId }[] = []; for (const slot of immuneNodes) { const c = state.chambers[slot]!; const eligible: LineageId[] = LINEAGE_IDS.filter((lid) => popOf(c, lid) > 0 && !state.lineage[lid].unlocked.immunity); if (eligible.length === 0) continue; let chosen: LineageId = eligible[0]!; for (const lid of eligible) { if (popOf(c, lid) > popOf(c, chosen)) chosen = lid; } // tie -> producer (producer comes first in LINEAGE_IDS, and we only replace on strictly greater) selections.push({ slot, lineage: chosen }); const cloakedPresent = LINEAGE_IDS.some((lid) => popOf(c, lid) > 0 && state.lineage[lid].unlocked.immunity); events.push( ev({ phase: "fixtures", kind: "immune-select", slot, lineage: chosen, text: `Immune node selects ${chosen} (damage ${immuneDamage})${cloakedPresent ? "; cloaked lineage forced retarget (spillover)" : ""}.`, }), ); } // (6) exposure snapshot: qualification + occupied, per (slot, lineage, pressure) type Qual = { heat: boolean; hunger: boolean; toxin: boolean }; const qual: Record = {}; // key `${slot}:${lineage}` for (let i = 0; i < 12; i++) { const c = state.chambers[i]!; for (const lid of LINEAGE_IDS) { if (popOf(c, lid) <= 0) continue; qual[`${i}:${lid}`] = { heat: c.heat >= 2, hunger: lineageFood(c, lid) === 0, toxin: c.toxin >= 2, }; } } // immunity qualification from selections const immuneQualified = new Set(selections.map((s) => `${s.slot}:${s.lineage}`)); // (7) increment pressure tracks (+1 if lineage occupied >=1 qualifying chamber) for (const lid of LINEAGE_IDS) { const lin = state.lineage[lid]; for (const p of PRESSURE_IDS) { let any = false; if (p === "immunity") any = selections.some((s) => s.lineage === lid); else for (let i = 0; i < 12; i++) { const q = qual[`${i}:${lid}`]; if (q && (q as Record)[p]) { any = true; break; } } if (any) { const before = lin.pressure[p]; lin.pressure[p] = clamp(lin.pressure[p] + 1, 0, 3); if (lin.pressure[p] !== before) events.push(ev({ phase: "pressure", kind: "pressure-up", lineage: lid, pressure: p, text: `${lid} ${p} pressure ${before}→${lin.pressure[p]}.` })); } } } // (8) consequences: heat, hunger, toxin, immunity (in order); spillover after heat/toxin applyPressureConsequences(state, "heat", qual, immuneQualified, selections, immuneDamage, events); applyPressureConsequences(state, "hunger", qual, immuneQualified, selections, immuneDamage, events); applyPressureConsequences(state, "toxin", qual, immuneQualified, selections, immuneDamage, events); applyPressureConsequences(state, "immunity", qual, immuneQualified, selections, immuneDamage, events); } function applyPressureConsequences( state: GameState, pressure: PressureId, qual: Record, _immuneQualified: Set, selections: { slot: number; lineage: LineageId }[], immuneDamage: number, events: GameEvent[], ) { if (pressure === "immunity") { for (const sel of selections) { const c = state.chambers[sel.slot]!; if (popOf(c, sel.lineage) <= 0) continue; // skip if already zero const before = popOf(c, sel.lineage); addPop(c, sel.lineage, -immuneDamage); events.push(ev({ phase: "pressure", kind: "immune-damage", slot: sel.slot, lineage: sel.lineage, text: `Immune damage ${sel.lineage} ${before}→${popOf(c, sel.lineage)}.` })); } return; } for (let i = 0; i < 12; i++) { for (const lid of LINEAGE_IDS) { const c = state.chambers[i]!; if (popOf(c, lid) <= 0) continue; // skip current-zero even if qualified const q = qual[`${i}:${lid}`]; if (!q || !(q as Record)[pressure]) continue; const adapted = state.lineage[lid].unlocked[pressure]; if (pressure === "heat") { if (adapted) { events.push(ev({ phase: "pressure", kind: "heat-shield", slot: i, lineage: lid, text: `${lid} Heat Shield prevents heat loss.` })); } else { const before = popOf(c, lid); addPop(c, lid, -2); events.push(ev({ phase: "pressure", kind: "heat-loss", slot: i, lineage: lid, text: `${lid} heat loss ${before}→${popOf(c, lid)}.` })); } } else if (pressure === "hunger") { if (adapted) { events.push(ev({ phase: "pressure", kind: "dormancy", slot: i, lineage: lid, text: `${lid} Dormancy prevents hunger loss.` })); } else { const before = popOf(c, lid); addPop(c, lid, -1); events.push(ev({ phase: "pressure", kind: "hunger-loss", slot: i, lineage: lid, text: `${lid} hunger loss ${before}→${popOf(c, lid)}.` })); } } else if (pressure === "toxin") { if (adapted) { // Efflux: pay 1 nutrient; if none, lose 1 pop. Producer pays before grazer (loop order). if (c.nutrient > 0) { c.nutrient = clamp(c.nutrient - 1, 0, CAP); events.push(ev({ phase: "pressure", kind: "efflux-pay", slot: i, lineage: lid, text: `${lid} Efflux pays 1 nutrient to resist toxin.` })); } else { const before = popOf(c, lid); addPop(c, lid, -1); events.push(ev({ phase: "pressure", kind: "efflux-cost", slot: i, lineage: lid, text: `${lid} Efflux: no nutrient, loses ${before - popOf(c, lid)} population.` })); } } else { const before = popOf(c, lid); addPop(c, lid, -1); events.push(ev({ phase: "pressure", kind: "toxin-loss", slot: i, lineage: lid, text: `${lid} toxin loss ${before}→${popOf(c, lid)}.` })); } } } } // spillover: heat & toxin detox after both lineages resolved if (pressure === "heat" || pressure === "toxin") { for (let i = 0; i < 12; i++) { const c = state.chambers[i]!; let reducers = 0; for (const lid of LINEAGE_IDS) { if (state.lineage[lid].unlocked[pressure] && popOf(c, lid) > 0) reducers++; } if (reducers > 0) { const reduce = Math.min(2, reducers); const field = pressure === "heat" ? "heat" : "toxin"; const before = c[field]; c[field] = clamp(c[field] - reduce, 0, CAP); if (c[field] !== before) events.push(ev({ phase: "pressure", kind: "spillover", slot: i, pressure, text: `${field} −${before - c[field]} (adapted spillover).` })); } } } } // Replay an action log from a baseline+inheritance; must reproduce canonical state. export function replayLog( baseline: GameState, actions: RotationAction[], opts?: { freezeOwnership?: boolean }, ): GameState { let s = baseline; for (const a of actions) { const r = nextState(s, a, opts); s = r.state; if (s.outcome !== "playing") break; // terminal stops further resolution } return s; }