(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:
31 files changed
+7113
No files matched your search
@@ -0,0 +1,211 @@
|
||||
// Adaptive Loop — immutable declarative scenarios. SPEC §9.
|
||||
// Sparse start notation order: nutrient / producer / grazer / phage / heat / toxin.
|
||||
import type { LineageId, PressureId } from "../domain/types";
|
||||
|
||||
export type FixtureKind =
|
||||
| "nutrientInlet"
|
||||
| "heatSource"
|
||||
| "toxinInlet"
|
||||
| "drain"
|
||||
| "immuneNode"
|
||||
| "objectiveMarker";
|
||||
|
||||
export interface FixtureDef {
|
||||
slot: number;
|
||||
kind: FixtureKind;
|
||||
/** For objectiveMarker: a label like "sanctuary" / "assay". */
|
||||
marker?: string;
|
||||
}
|
||||
|
||||
/** Start tuple in notation order: [nutrient, producer, grazer, phage, heat, toxin]. */
|
||||
export type StartTuple = [number, number, number, number, number, number];
|
||||
|
||||
export interface SustainedSpec {
|
||||
assaySlots: number[];
|
||||
assayPopMin: number;
|
||||
producerRange: [number, number];
|
||||
grazerRange: [number, number];
|
||||
phageMax: number;
|
||||
toxinMax: number;
|
||||
}
|
||||
|
||||
export type WinSpec =
|
||||
| { kind: "producerAt"; slot: number; producerMin: number; totalProducerMin: number }
|
||||
| {
|
||||
kind: "endurance";
|
||||
atTurn: number;
|
||||
totalProducerMin: number;
|
||||
totalGrazerMin: number;
|
||||
producerChambersMin: number;
|
||||
grazerChambersMin: number;
|
||||
}
|
||||
| { kind: "cleanse"; totalToxinMax: number; totalPopMin: number; fromTurn: number; toTurn: number }
|
||||
| { kind: "escort"; slot: number; grazerMin: number; phageMin: number; totalProducerMin: number }
|
||||
| { kind: "sustained"; required: number; sustained: SustainedSpec };
|
||||
|
||||
export interface ScenarioDef {
|
||||
id: string;
|
||||
index: number;
|
||||
title: string;
|
||||
pressure: PressureId;
|
||||
subtitle: string;
|
||||
teaches: string;
|
||||
turnLimit: number;
|
||||
fixtures: FixtureDef[];
|
||||
start: Record<number, StartTuple>;
|
||||
win: WinSpec;
|
||||
winDescription: string;
|
||||
}
|
||||
|
||||
export const SCENARIOS: ScenarioDef[] = [
|
||||
{
|
||||
id: "s1-heat",
|
||||
index: 0,
|
||||
title: "Cultivation Quota",
|
||||
pressure: "heat",
|
||||
subtitle: "Heat",
|
||||
teaches: "rotation, ownership, flow, growth, preview, first visible pressure",
|
||||
turnLimit: 8,
|
||||
fixtures: [
|
||||
{ slot: 1, kind: "nutrientInlet" },
|
||||
{ slot: 7, kind: "nutrientInlet" },
|
||||
{ slot: 3, kind: "heatSource" },
|
||||
{ slot: 9, kind: "heatSource" },
|
||||
],
|
||||
start: {
|
||||
0: [3, 2, 0, 0, 0, 0],
|
||||
6: [3, 2, 0, 0, 0, 0],
|
||||
10: [2, 1, 0, 0, 0, 0],
|
||||
4: [1, 0, 0, 0, 0, 0],
|
||||
},
|
||||
win: { kind: "producerAt", slot: 11, producerMin: 5, totalProducerMin: 12 },
|
||||
winDescription: "producer at slot 11 ≥ 5 and total producer ≥ 12",
|
||||
},
|
||||
{
|
||||
id: "s2-hunger",
|
||||
index: 1,
|
||||
title: "Endurance",
|
||||
pressure: "hunger",
|
||||
subtitle: "Hunger",
|
||||
teaches: "competition, migration, dormancy, deliberate denial of predator food",
|
||||
turnLimit: 10,
|
||||
fixtures: [{ slot: 0, kind: "nutrientInlet" }],
|
||||
start: {
|
||||
1: [2, 3, 0, 0, 0, 0],
|
||||
5: [1, 2, 1, 0, 0, 0],
|
||||
7: [2, 3, 1, 0, 0, 0],
|
||||
10: [0, 2, 2, 0, 0, 0],
|
||||
},
|
||||
win: {
|
||||
kind: "endurance",
|
||||
atTurn: 10,
|
||||
totalProducerMin: 8,
|
||||
totalGrazerMin: 4,
|
||||
producerChambersMin: 3,
|
||||
grazerChambersMin: 2,
|
||||
},
|
||||
winDescription:
|
||||
"at turn 10: total producer ≥ 8, total grazer ≥ 4, producer in ≥ 3 chambers, grazer in ≥ 2 chambers",
|
||||
},
|
||||
{
|
||||
id: "s3-toxin",
|
||||
index: 2,
|
||||
title: "Cleansing",
|
||||
pressure: "toxin",
|
||||
subtitle: "Toxin",
|
||||
teaches: "routing contaminants, resistance payment, shared detoxification spillover",
|
||||
turnLimit: 9,
|
||||
fixtures: [
|
||||
{ slot: 1, kind: "nutrientInlet" },
|
||||
{ slot: 3, kind: "toxinInlet" },
|
||||
{ slot: 5, kind: "drain" },
|
||||
{ slot: 11, kind: "drain" },
|
||||
],
|
||||
start: {
|
||||
0: [3, 3, 0, 0, 0, 0],
|
||||
3: [0, 0, 0, 0, 0, 2],
|
||||
6: [2, 3, 0, 0, 0, 0],
|
||||
9: [0, 0, 0, 0, 0, 2],
|
||||
10: [2, 2, 1, 0, 0, 0],
|
||||
},
|
||||
win: { kind: "cleanse", totalToxinMax: 2, totalPopMin: 8, fromTurn: 6, toTurn: 9 },
|
||||
winDescription: "turn 6–9: total toxin ≤ 2 and total producer + grazer ≥ 8",
|
||||
},
|
||||
{
|
||||
id: "s4-immunity",
|
||||
index: 3,
|
||||
title: "Escort",
|
||||
pressure: "immunity",
|
||||
subtitle: "Immunity",
|
||||
teaches: "immune targeting, cloak, retargeting spillover, predator vulnerability",
|
||||
turnLimit: 8,
|
||||
fixtures: [
|
||||
{ slot: 0, kind: "nutrientInlet" },
|
||||
{ slot: 8, kind: "nutrientInlet" },
|
||||
{ slot: 2, kind: "immuneNode" },
|
||||
{ slot: 4, kind: "immuneNode" },
|
||||
{ slot: 6, kind: "immuneNode" },
|
||||
{ slot: 11, kind: "objectiveMarker", marker: "sanctuary" },
|
||||
],
|
||||
start: {
|
||||
1: [2, 3, 0, 0, 0, 0],
|
||||
5: [2, 3, 2, 0, 0, 0],
|
||||
7: [0, 0, 0, 1, 0, 0],
|
||||
9: [1, 0, 2, 1, 0, 0],
|
||||
},
|
||||
win: { kind: "escort", slot: 11, grazerMin: 3, phageMin: 0, totalProducerMin: 6 },
|
||||
winDescription: "grazer at slot 11 ≥ 3 and total producer ≥ 6",
|
||||
},
|
||||
{
|
||||
id: "s5-convergence",
|
||||
index: 4,
|
||||
title: "Stable Equilibrium",
|
||||
pressure: "immunity",
|
||||
subtitle: "Convergence",
|
||||
teaches: "all systems plus inherited gift-and-burden consequences",
|
||||
turnLimit: 12,
|
||||
fixtures: [
|
||||
{ slot: 0, kind: "nutrientInlet" },
|
||||
{ slot: 6, kind: "nutrientInlet" },
|
||||
{ slot: 2, kind: "heatSource" },
|
||||
{ slot: 8, kind: "heatSource" },
|
||||
{ slot: 3, kind: "toxinInlet" },
|
||||
{ slot: 9, kind: "drain" },
|
||||
{ slot: 4, kind: "immuneNode" },
|
||||
{ slot: 10, kind: "immuneNode" },
|
||||
{ slot: 1, kind: "objectiveMarker", marker: "assay" },
|
||||
{ slot: 7, kind: "objectiveMarker", marker: "assay" },
|
||||
{ slot: 11, kind: "objectiveMarker", marker: "assay" },
|
||||
],
|
||||
start: {
|
||||
0: [3, 3, 0, 0, 0, 0],
|
||||
3: [0, 0, 0, 0, 0, 2],
|
||||
5: [2, 2, 1, 0, 0, 0],
|
||||
6: [3, 2, 0, 0, 0, 0],
|
||||
8: [0, 0, 0, 0, 2, 0],
|
||||
9: [0, 0, 0, 0, 0, 1],
|
||||
10: [2, 2, 2, 1, 0, 0],
|
||||
},
|
||||
win: {
|
||||
kind: "sustained",
|
||||
required: 2,
|
||||
sustained: {
|
||||
assaySlots: [1, 7, 11],
|
||||
assayPopMin: 2,
|
||||
producerRange: [8, 14],
|
||||
grazerRange: [3, 7],
|
||||
phageMax: 3,
|
||||
toxinMax: 6,
|
||||
},
|
||||
},
|
||||
winDescription: "hold the equilibrium for 2 consecutive turns",
|
||||
},
|
||||
];
|
||||
|
||||
export const SCENARIO_BY_ID: Record<string, ScenarioDef> = Object.fromEntries(
|
||||
SCENARIOS.map((s) => [s.id, s]),
|
||||
);
|
||||
|
||||
export type InheritanceSet = Partial<Record<LineageId, PressureId[]>>;
|
||||
|
||||
export const STORAGE_KEY = "adaptive-loop-save-v1";
|
||||
@@ -0,0 +1,103 @@
|
||||
// Adaptive Loop — immutable topology + species/trait tables. SPEC §4, §6, §8.
|
||||
import type { Direction, LineageId, LoopId, PressureId } from "./types";
|
||||
|
||||
/** Slots of each loop in clockwise visual order. SPEC §4. */
|
||||
export const LOOPS: Record<LoopId, number[]> = {
|
||||
A: [0, 1, 2, 3, 4, 5],
|
||||
B: [2, 3, 6, 7, 8, 9],
|
||||
C: [4, 5, 10, 11, 8, 9],
|
||||
};
|
||||
|
||||
/** Which loops contain each shared slot. */
|
||||
export const SHARED_LOOPS: Record<string, LoopId[]> = {
|
||||
"2": ["A", "B"],
|
||||
"3": ["A", "B"],
|
||||
"4": ["A", "C"],
|
||||
"5": ["A", "C"],
|
||||
"8": ["B", "C"],
|
||||
"9": ["B", "C"],
|
||||
};
|
||||
|
||||
export const SHARED_SLOT_KEYS = ["2", "3", "4", "5", "8", "9"];
|
||||
|
||||
/** Shared slots claimed by a loop when it is rotated. SPEC §4 step 4. */
|
||||
export const LOOP_SHARED_SLOTS: Record<LoopId, number[]> = {
|
||||
A: [2, 3, 4, 5],
|
||||
B: [2, 3, 8, 9],
|
||||
C: [4, 5, 8, 9],
|
||||
};
|
||||
|
||||
/** All 12 slots. Non-shared slots own themselves via their only loop. */
|
||||
export const ALL_SLOTS = Array.from({ length: 12 }, (_, i) => i);
|
||||
|
||||
/** The single loop that owns a non-shared slot. */
|
||||
export function loopOfNonShared(slot: number): LoopId | null {
|
||||
if ([0, 1].includes(slot)) return "A";
|
||||
if ([6, 7].includes(slot)) return "B";
|
||||
if ([10, 11].includes(slot)) return "C";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Step used for "next"/outlet and rotation: +1 cw, +5 ccw. SPEC §4. */
|
||||
export function dirStep(dir: Direction): number {
|
||||
return dir === "cw" ? 1 : 5;
|
||||
}
|
||||
|
||||
/** Default (alphabetical) owner of a shared slot at scenario start. */
|
||||
export function defaultOwner(slotKey: string): LoopId {
|
||||
const loops = SHARED_LOOPS[slotKey] ?? [];
|
||||
return loops.slice().sort()[0] as LoopId;
|
||||
}
|
||||
|
||||
// --- Species / pressure flavor (SPEC §6) ------------------------------------
|
||||
|
||||
export interface SpeciesInfo {
|
||||
id: "producer" | "grazer" | "phage";
|
||||
name: string;
|
||||
food: "nutrient" | "producer" | "grazer";
|
||||
persistent: boolean;
|
||||
}
|
||||
|
||||
export const SPECIES: Record<string, SpeciesInfo> = {
|
||||
producer: { id: "producer", name: "Veridan", food: "nutrient", persistent: true },
|
||||
grazer: { id: "grazer", name: "Cilia", food: "producer", persistent: true },
|
||||
phage: { id: "phage", name: "Phage", food: "grazer", persistent: false },
|
||||
};
|
||||
|
||||
/** Food quantity a species chases, read from a chamber. */
|
||||
export function foodOf(chamber: { nutrient: number; producer: number; grazer: number }, sp: "producer" | "grazer" | "phage"): number {
|
||||
if (sp === "producer") return chamber.nutrient;
|
||||
if (sp === "grazer") return chamber.producer;
|
||||
return chamber.grazer;
|
||||
}
|
||||
|
||||
export interface PressureInfo {
|
||||
id: PressureId;
|
||||
traitName: string;
|
||||
/** Hot-key symbol for non-color encoding. */
|
||||
glyph: string;
|
||||
}
|
||||
|
||||
export const PRESSURES: Record<PressureId, PressureInfo> = {
|
||||
heat: { id: "heat", traitName: "Heat Shield", glyph: "🔥" },
|
||||
hunger: { id: "hunger", traitName: "Dormancy", glyph: "☾" },
|
||||
toxin: { id: "toxin", traitName: "Efflux", glyph: "⚗" },
|
||||
immunity: { id: "immunity", traitName: "Cloak", glyph: "◊" },
|
||||
};
|
||||
|
||||
/** Trait unlock order within a lineage for content/reference. */
|
||||
export const TRAIT_BY_PRESSURE: Record<PressureId, string> = {
|
||||
heat: "Heat Shield",
|
||||
hunger: "Dormancy",
|
||||
toxin: "Efflux",
|
||||
immunity: "Cloak",
|
||||
};
|
||||
|
||||
export const CAP = 6;
|
||||
export const PRESSURE_CAP = 3;
|
||||
|
||||
export function clamp(n: number, lo: number, hi: number): number {
|
||||
return n < lo ? lo : n > hi ? hi : n;
|
||||
}
|
||||
|
||||
export const PRESSURE_LINEAGE_ORDER: LineageId[] = ["producer", "grazer"];
|
||||
@@ -0,0 +1,520 @@
|
||||
// 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<string, Qual> = {}; // 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<PressureId, boolean>)[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<string, { heat: boolean; hunger: boolean; toxin: boolean }>,
|
||||
_immuneQualified: Set<string>,
|
||||
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<PressureId, boolean>)[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;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// Adaptive Loop — scenario state construction, ownership/outlet, aggregations,
|
||||
// win & sustained predicates. SPEC §4, §8, §9.
|
||||
import type { GameState, LoopId, Mode, LineageId, PressureId, Chamber } from "./types";
|
||||
import { LINEAGE_IDS, PRESSURE_IDS } from "./types";
|
||||
import {
|
||||
LOOPS,
|
||||
SHARED_SLOT_KEYS,
|
||||
defaultOwner,
|
||||
dirStep,
|
||||
loopOfNonShared,
|
||||
} from "./constants";
|
||||
import { emptyChamber } from "./serialize";
|
||||
import { SCENARIO_BY_ID } from "../content/scenarios";
|
||||
import type { InheritanceSet } from "../content/scenarios";
|
||||
|
||||
/** Owning loop of any slot (shared uses state.sharedOwner; else its only loop). */
|
||||
export function ownerOf(state: GameState, slot: number): LoopId {
|
||||
const key = String(slot);
|
||||
if (SHARED_SLOT_KEYS.includes(key)) {
|
||||
return state.sharedOwner[key]!;
|
||||
}
|
||||
const only = loopOfNonShared(slot);
|
||||
if (!only) throw new Error(`slot ${slot} has no owner`);
|
||||
return only;
|
||||
}
|
||||
|
||||
/** Outlet slot = next slot along the owning loop in its current direction. */
|
||||
export function outletOf(state: GameState, slot: number): number {
|
||||
const owner = ownerOf(state, slot);
|
||||
const arr = LOOPS[owner];
|
||||
const idx = arr.indexOf(slot);
|
||||
if (idx < 0) throw new Error(`slot ${slot} not in owner loop ${owner}`);
|
||||
const step = dirStep(state.loops[owner].direction);
|
||||
return arr[(idx + step) % arr.length] as number;
|
||||
}
|
||||
|
||||
export function makeLineage(inherited: PressureId[] = []) {
|
||||
const unlocked: Record<PressureId, boolean> = { heat: false, hunger: false, toxin: false, immunity: false };
|
||||
for (const p of inherited) unlocked[p] = true;
|
||||
return {
|
||||
pressure: { heat: 0, hunger: 0, toxin: 0, immunity: 0 } as Record<PressureId, number>,
|
||||
unlocked,
|
||||
};
|
||||
}
|
||||
|
||||
export function createScenarioState(
|
||||
scenarioId: string,
|
||||
mode: Mode,
|
||||
inheritance: InheritanceSet = {},
|
||||
): GameState {
|
||||
const scenario = SCENARIO_BY_ID[scenarioId];
|
||||
if (!scenario) throw new Error(`unknown scenario ${scenarioId}`);
|
||||
const chambers: Chamber[] = Array.from({ length: 12 }, () => emptyChamber());
|
||||
for (const slotStr of Object.keys(scenario.start)) {
|
||||
const slot = Number(slotStr);
|
||||
const [nutrient, producer, grazer, phage, heat, toxin] = scenario.start[slot]!;
|
||||
const c = chambers[slot]!;
|
||||
c.nutrient = nutrient;
|
||||
c.producer = producer;
|
||||
c.grazer = grazer;
|
||||
c.phage = phage;
|
||||
c.heat = heat;
|
||||
c.toxin = toxin;
|
||||
}
|
||||
const sharedOwner: Record<string, LoopId> = {};
|
||||
for (const k of SHARED_SLOT_KEYS) sharedOwner[k] = defaultOwner(k);
|
||||
|
||||
const lineage = {
|
||||
producer: makeLineage(inheritance.producer),
|
||||
grazer: makeLineage(inheritance.grazer),
|
||||
} as Record<LineageId, ReturnType<typeof makeLineage>>;
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
mode,
|
||||
scenarioId,
|
||||
turn: 0,
|
||||
loops: { A: { direction: "cw" }, B: { direction: "cw" }, C: { direction: "cw" } },
|
||||
sharedOwner,
|
||||
chambers,
|
||||
lineage,
|
||||
inheritedAtStart: {
|
||||
producer: [...(inheritance.producer ?? [])],
|
||||
grazer: [...(inheritance.grazer ?? [])],
|
||||
},
|
||||
consecutiveObjectiveTurns: 0,
|
||||
environmentActive: { heat: false, hunger: false, toxin: false, immunity: false },
|
||||
outcome: "playing",
|
||||
actionLog: [],
|
||||
};
|
||||
}
|
||||
|
||||
// --- aggregations ----------------------------------------------------------
|
||||
|
||||
export type SpeciesField = "producer" | "grazer" | "phage";
|
||||
|
||||
export function totalOf(state: GameState, field: "producer" | "grazer" | "phage" | "toxin" | "nutrient" | "heat"): number {
|
||||
let sum = 0;
|
||||
for (const c of state.chambers) sum += c[field];
|
||||
return sum;
|
||||
}
|
||||
|
||||
export function chambersOccupied(state: GameState, field: SpeciesField): number {
|
||||
let n = 0;
|
||||
for (const c of state.chambers) if (c[field] > 0) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
/** producer + grazer across all chambers (the collapse metric). */
|
||||
export function totalPersistent(state: GameState): number {
|
||||
return totalOf(state, "producer") + totalOf(state, "grazer");
|
||||
}
|
||||
|
||||
// --- win & sustained -------------------------------------------------------
|
||||
|
||||
export function sustainedHolds(state: GameState): boolean {
|
||||
const sc = SCENARIO_BY_ID[state.scenarioId];
|
||||
if (!sc || sc.win.kind !== "sustained") return false;
|
||||
const s = sc.win.sustained;
|
||||
for (const slot of s.assaySlots) {
|
||||
const c = state.chambers[slot]!;
|
||||
if (c.producer + c.grazer < s.assayPopMin) return false;
|
||||
}
|
||||
const tp = totalOf(state, "producer");
|
||||
const tg = totalOf(state, "grazer");
|
||||
const tpha = totalOf(state, "phage");
|
||||
const tt = totalOf(state, "toxin");
|
||||
if (tp < s.producerRange[0] || tp > s.producerRange[1]) return false;
|
||||
if (tg < s.grazerRange[0] || tg > s.grazerRange[1]) return false;
|
||||
if (tpha > s.phageMax) return false;
|
||||
if (tt > s.toxinMax) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function evaluateWin(state: GameState, resolvedTurn: number, consecutive: number): boolean {
|
||||
const sc = SCENARIO_BY_ID[state.scenarioId];
|
||||
if (!sc) return false;
|
||||
const w = sc.win;
|
||||
switch (w.kind) {
|
||||
case "producerAt":
|
||||
return (
|
||||
state.chambers[w.slot]!.producer >= w.producerMin &&
|
||||
totalOf(state, "producer") >= w.totalProducerMin
|
||||
);
|
||||
case "endurance":
|
||||
if (resolvedTurn !== w.atTurn) return false;
|
||||
return (
|
||||
totalOf(state, "producer") >= w.totalProducerMin &&
|
||||
totalOf(state, "grazer") >= w.totalGrazerMin &&
|
||||
chambersOccupied(state, "producer") >= w.producerChambersMin &&
|
||||
chambersOccupied(state, "grazer") >= w.grazerChambersMin
|
||||
);
|
||||
case "cleanse":
|
||||
if (resolvedTurn < w.fromTurn || resolvedTurn > w.toTurn) return false;
|
||||
return totalOf(state, "toxin") <= w.totalToxinMax && totalPersistent(state) >= w.totalPopMin;
|
||||
case "escort":
|
||||
return (
|
||||
state.chambers[w.slot]!.grazer >= w.grazerMin &&
|
||||
state.chambers[w.slot]!.phage >= w.phageMin &&
|
||||
totalOf(state, "producer") >= w.totalProducerMin
|
||||
);
|
||||
case "sustained":
|
||||
return consecutive >= w.required;
|
||||
}
|
||||
}
|
||||
|
||||
export const ALL_PRESSURES: PressureId[] = PRESSURE_IDS;
|
||||
export const ALL_LINEAGES: LineageId[] = LINEAGE_IDS;
|
||||
@@ -0,0 +1,47 @@
|
||||
// Adaptive Loop — canonical serialization & deep clone. SPEC §5 (canonical equality).
|
||||
import type { GameState, Chamber } from "./types";
|
||||
|
||||
/** Stable-key JSON: object keys sorted recursively. Excludes nothing here —
|
||||
* callers must keep transient UI data out of GameState (it is). */
|
||||
export function canonicalStringify(value: unknown): string {
|
||||
return JSON.stringify(sortKeys(value));
|
||||
}
|
||||
|
||||
function sortKeys(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(sortKeys);
|
||||
if (value && typeof value === "object") {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const k of Object.keys(value as Record<string, unknown>).sort()) {
|
||||
out[k] = sortKeys((value as Record<string, unknown>)[k]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function canonicalHash(state: GameState): string {
|
||||
// FNV-1a 32-bit of canonical string — good enough for dedup keys (non-crypto).
|
||||
let h = 0x811c9dc5;
|
||||
const s = canonicalStringify(state);
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
h ^= s.charCodeAt(i);
|
||||
h = Math.imul(h, 0x01000193);
|
||||
}
|
||||
return (h >>> 0).toString(16).padStart(8, "0");
|
||||
}
|
||||
|
||||
export function canonicalEqual(a: GameState, b: GameState): boolean {
|
||||
return canonicalStringify(a) === canonicalStringify(b);
|
||||
}
|
||||
|
||||
export function cloneState(state: GameState): GameState {
|
||||
return JSON.parse(JSON.stringify(state)) as GameState;
|
||||
}
|
||||
|
||||
export function emptyChamber(): Chamber {
|
||||
return { nutrient: 0, heat: 0, toxin: 0, producer: 0, grazer: 0, phage: 0 };
|
||||
}
|
||||
|
||||
export function cloneChamber(c: Chamber): Chamber {
|
||||
return { nutrient: c.nutrient, heat: c.heat, toxin: c.toxin, producer: c.producer, grazer: c.grazer, phage: c.phage };
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
// Adaptive Loop — bounded deterministic solver (SPEC §9, §15 Gate 4).
|
||||
// Proves one winning and one losing route per scenario via canonical-state BFS,
|
||||
// the shared-ownership counterfactual, and reachable campaign inheritance sets.
|
||||
import { nextState, allActions } from "./pipeline";
|
||||
import { createScenarioState } from "./scenario";
|
||||
import { SCENARIOS } from "../content/scenarios";
|
||||
import type { InheritanceSet } from "../content/scenarios";
|
||||
import type { GameState, RotationAction, LineageId, PressureId, Outcome } from "./types";
|
||||
import { LINEAGE_IDS, PRESSURE_IDS } from "./types";
|
||||
|
||||
export interface SolveResult {
|
||||
win: RotationAction[] | null;
|
||||
lose: RotationAction[] | null;
|
||||
explored: number;
|
||||
winOutcome: Outcome | null;
|
||||
loseOutcome: Outcome | null;
|
||||
capped: boolean;
|
||||
}
|
||||
|
||||
const ACTIONS = allActions();
|
||||
|
||||
function fastHash(s: GameState): string {
|
||||
// FNV-1a of raw JSON (key order is stable for cloned states built the same way).
|
||||
const str = JSON.stringify(s);
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
h ^= str.charCodeAt(i);
|
||||
h = Math.imul(h, 0x01000193);
|
||||
}
|
||||
return (h >>> 0).toString(36);
|
||||
}
|
||||
|
||||
type SolveOpts = { freezeOwnership?: boolean; maxNodes?: number; timeMs?: number; seed?: number };
|
||||
|
||||
function mkRng(seed: number) {
|
||||
let s = seed >>> 0;
|
||||
return () => {
|
||||
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
|
||||
return s / 0x100000000;
|
||||
};
|
||||
}
|
||||
|
||||
function shuffled<T>(arr: T[], rng: () => number): T[] {
|
||||
const a = arr.slice();
|
||||
for (let i = a.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(rng() * (i + 1));
|
||||
const tmp = a[i]!; a[i] = a[j]!; a[j] = tmp;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
// --- heuristic scoring for guided search (health + objective proximity) ---
|
||||
function totalPersistentOf(s: GameState): number {
|
||||
let n = 0;
|
||||
for (const c of s.chambers) n += c.producer + c.grazer;
|
||||
return n;
|
||||
}
|
||||
function scoreState(s: GameState): number {
|
||||
if (s.outcome === "won") return 1e9;
|
||||
if (s.outcome !== "playing") return -1e8; // collapsed/expired
|
||||
const sc = SCENARIOS.find((x) => x.id === s.scenarioId);
|
||||
let occP = 0, occG = 0, totNut = 0, totTox = 0, totHeat = 0;
|
||||
for (const c of s.chambers) {
|
||||
if (c.producer > 0) occP++;
|
||||
if (c.grazer > 0) occG++;
|
||||
totNut += c.nutrient;
|
||||
totTox += c.toxin;
|
||||
totHeat += c.heat;
|
||||
}
|
||||
let score = totalPersistentOf(s) * 100 + (occP + occG) * 12 + totNut * 3 - totTox * 6 - totHeat * 2;
|
||||
const w = sc?.win;
|
||||
if (w) {
|
||||
switch (w.kind) {
|
||||
case "producerAt":
|
||||
score += (s.chambers[w.slot]?.producer ?? 0) * 60;
|
||||
break;
|
||||
case "endurance":
|
||||
score += Math.min(occP, w.producerChambersMin) * 8 + Math.min(occG, w.grazerChambersMin) * 8;
|
||||
break;
|
||||
case "cleanse":
|
||||
score -= totTox * 25;
|
||||
break;
|
||||
case "escort":
|
||||
score += (s.chambers[w.slot]?.grazer ?? 0) * 60 + (s.chambers[w.slot]?.phage ?? 0) * 40;
|
||||
break;
|
||||
case "sustained": {
|
||||
const ok = s.chambers[1]!.producer + s.chambers[1]!.grazer >= 2 && s.chambers[7]!.producer + s.chambers[7]!.grazer >= 2 && s.chambers[11]!.producer + s.chambers[11]!.grazer >= 2;
|
||||
score += ok ? 400 : 0;
|
||||
score += s.consecutiveObjectiveTurns * 300;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return score;
|
||||
}
|
||||
|
||||
/** Beam search guided by scoreState. Reliably finds wins for routing/survival puzzles. */
|
||||
export function beamSearch(
|
||||
scenarioId: string,
|
||||
inheritance: InheritanceSet,
|
||||
opts: SolveOpts & { beamWidth?: number } = {},
|
||||
): { route: RotationAction[] | null; explored: number; capped: boolean } {
|
||||
const beamWidth = opts.beamWidth ?? 400;
|
||||
const start = createScenarioState(scenarioId, "standalone", inheritance);
|
||||
const limit = SCENARIOS.find((x) => x.id === scenarioId)?.turnLimit ?? 12;
|
||||
type N = { s: GameState; path: RotationAction[]; score: number };
|
||||
let beam: N[] = [{ s: start, path: [], score: scoreState(start) }];
|
||||
let explored = 0;
|
||||
const seen = new Map<string, number>();
|
||||
seen.set(fastHash(start), 0);
|
||||
for (let depth = 0; depth < limit; depth++) {
|
||||
const cand: N[] = [];
|
||||
for (const node of beam) {
|
||||
for (const a of ACTIONS) {
|
||||
explored++;
|
||||
const ns = nextState(node.s, a, opts).state;
|
||||
const path = node.path.length ? [...node.path, a] : [a];
|
||||
if (ns.outcome === "won") return { route: path, explored, capped: false };
|
||||
if (ns.outcome !== "playing") continue;
|
||||
const h = fastHash(ns);
|
||||
const prev = seen.get(h);
|
||||
const minLen = path.length;
|
||||
if (prev !== undefined && prev <= minLen) continue;
|
||||
seen.set(h, minLen);
|
||||
cand.push({ s: ns, path, score: scoreState(ns) });
|
||||
}
|
||||
}
|
||||
if (cand.length === 0) break;
|
||||
cand.sort((x, y) => y.score - x.score);
|
||||
beam = cand.slice(0, beamWidth);
|
||||
}
|
||||
return { route: null, explored, capped: false };
|
||||
}
|
||||
|
||||
/** Memory-light randomized DFS that finds ONE route reaching `target` outcome. */
|
||||
export function findRoute(
|
||||
scenarioId: string,
|
||||
inheritance: InheritanceSet,
|
||||
target: "won" | "lose",
|
||||
opts: SolveOpts = {},
|
||||
): { route: RotationAction[] | null; explored: number; capped: boolean } {
|
||||
const maxNodes = opts.maxNodes ?? 1_500_000;
|
||||
const timeMs = opts.timeMs ?? 90_000;
|
||||
const rng = mkRng(opts.seed ?? 0xC0FFEE);
|
||||
const start = createScenarioState(scenarioId, "standalone", inheritance);
|
||||
const t0 = Date.now();
|
||||
let explored = 0;
|
||||
let capped = false;
|
||||
// capped memo: dedup while small, drop once full to bound memory
|
||||
const memo = new Set<string>();
|
||||
const memoCap = 250_000;
|
||||
let memoOn = true;
|
||||
|
||||
function rec(s: GameState): RotationAction[] | null {
|
||||
if (s.outcome !== "playing") return null;
|
||||
if (Date.now() - t0 > timeMs || explored > maxNodes) {
|
||||
capped = true;
|
||||
return null;
|
||||
}
|
||||
for (const a of shuffled(ACTIONS, rng)) {
|
||||
explored++;
|
||||
const ns = nextState(s, a, opts).state;
|
||||
const hit = target === "won" ? ns.outcome === "won" : ns.outcome === "collapsed" || ns.outcome === "expired";
|
||||
if (hit) return [a];
|
||||
if (ns.outcome === "playing") {
|
||||
let proceed = true;
|
||||
if (memoOn) {
|
||||
const h = fastHash(ns);
|
||||
if (memo.has(h)) proceed = false;
|
||||
else {
|
||||
memo.add(h);
|
||||
if (memo.size > memoCap) memoOn = false;
|
||||
}
|
||||
}
|
||||
if (proceed) {
|
||||
const sub = rec(ns);
|
||||
if (sub) return [a, ...sub];
|
||||
if (capped) return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const route = rec(start);
|
||||
return { route, explored, capped };
|
||||
}
|
||||
|
||||
/** Bounded BFS over canonical states. Returns first win route and first lose route. */
|
||||
export function solve(
|
||||
scenarioId: string,
|
||||
inheritance: InheritanceSet = {},
|
||||
opts: SolveOpts = {},
|
||||
): SolveResult {
|
||||
const maxNodes = opts.maxNodes ?? 500_000;
|
||||
const timeMs = opts.timeMs ?? 60_000;
|
||||
const start = createScenarioState(scenarioId, "standalone", inheritance);
|
||||
const seen = new Set<string>([fastHash(start)]);
|
||||
type Node = { s: GameState; path: RotationAction[] };
|
||||
const queue: Node[] = [{ s: start, path: [] }];
|
||||
let head = 0;
|
||||
let explored = 0;
|
||||
let win: RotationAction[] | null = null;
|
||||
let lose: RotationAction[] | null = null;
|
||||
let winOutcome: Outcome | null = null;
|
||||
let loseOutcome: Outcome | null = null;
|
||||
let capped = false;
|
||||
const t0 = Date.now();
|
||||
|
||||
while (head < queue.length) {
|
||||
const { s, path } = queue[head++]!;
|
||||
explored++;
|
||||
if (explored > maxNodes || Date.now() - t0 > timeMs) {
|
||||
capped = true;
|
||||
break;
|
||||
}
|
||||
for (const a of ACTIONS) {
|
||||
const ns = nextState(s, a, opts).state;
|
||||
const npath = path.length ? [...path, a] : [a];
|
||||
if (ns.outcome === "won" && !win) {
|
||||
win = npath;
|
||||
winOutcome = "won";
|
||||
} else if ((ns.outcome === "collapsed" || ns.outcome === "expired") && !lose) {
|
||||
lose = npath;
|
||||
loseOutcome = ns.outcome;
|
||||
}
|
||||
if (win && lose) {
|
||||
return { win, lose, explored, winOutcome, loseOutcome, capped: false };
|
||||
}
|
||||
if (ns.outcome === "playing") {
|
||||
const h = fastHash(ns);
|
||||
if (!seen.has(h)) {
|
||||
seen.add(h);
|
||||
queue.push({ s: ns, path: npath });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
queue.length = 0;
|
||||
return { win, lose, explored, winOutcome, loseOutcome, capped };
|
||||
}
|
||||
|
||||
/**
|
||||
* Memory-light EXHAUSTIVE DFS (stores only state hashes). Visits every reachable
|
||||
* state once. Returns win route if any reachable, plus statesSeen and whether the
|
||||
* full reachable space was exhausted (proves unwinnable when win=null & complete=true).
|
||||
*/
|
||||
export function exhaust(
|
||||
scenarioId: string,
|
||||
inheritance: InheritanceSet = {},
|
||||
opts: { freezeOwnership?: boolean; maxStates?: number } = {},
|
||||
): { win: RotationAction[] | null; statesSeen: number; complete: boolean } {
|
||||
const maxStates = opts.maxStates ?? 4_000_000;
|
||||
const start = createScenarioState(scenarioId, "standalone", inheritance);
|
||||
const seen = new Set<string>();
|
||||
let win: RotationAction[] | null = null;
|
||||
let complete = true;
|
||||
// iterative DFS (bounded stack; safe for very large state spaces)
|
||||
type Frame = { s: GameState; path: RotationAction[]; ai: number };
|
||||
const stack: Frame[] = [];
|
||||
function consider(s: GameState, path: RotationAction[]): boolean {
|
||||
if (s.outcome === "won") {
|
||||
win = path;
|
||||
return true;
|
||||
}
|
||||
if (s.outcome !== "playing") return false;
|
||||
const h = fastHash(s);
|
||||
if (seen.has(h)) return false;
|
||||
if (seen.size >= maxStates) {
|
||||
complete = false;
|
||||
return true; // signal stop
|
||||
}
|
||||
seen.add(h);
|
||||
stack.push({ s, path, ai: 0 });
|
||||
return false;
|
||||
}
|
||||
if (consider(start, [])) {
|
||||
return { win, statesSeen: seen.size, complete };
|
||||
}
|
||||
while (stack.length && !win && complete) {
|
||||
const top = stack[stack.length - 1]!;
|
||||
if (top.ai >= ACTIONS.length) {
|
||||
stack.pop();
|
||||
continue;
|
||||
}
|
||||
const a = ACTIONS[top.ai++]!;
|
||||
const ns = nextState(top.s, a, opts).state;
|
||||
const npath = top.path.length ? [...top.path, a] : [a];
|
||||
if (consider(ns, npath)) {
|
||||
if (win || !complete) break;
|
||||
}
|
||||
}
|
||||
return { win, statesSeen: seen.size, complete };
|
||||
}
|
||||
|
||||
/** Which traits unlocked along a route (beyond inherited). */
|
||||
export function unlockedAlong(
|
||||
scenarioId: string,
|
||||
inheritance: InheritanceSet,
|
||||
route: RotationAction[],
|
||||
): { lineage: LineageId; pressure: PressureId }[] {
|
||||
let s = createScenarioState(scenarioId, "standalone", inheritance);
|
||||
const inherited = new Set<string>();
|
||||
for (const lid of LINEAGE_IDS)
|
||||
for (const p of inheritance[lid] ?? []) inherited.add(`${lid}:${p}`);
|
||||
const became = new Set<string>();
|
||||
const apply = (lid: LineageId, p: PressureId) => {
|
||||
if (s.lineage[lid].unlocked[p] && !inherited.has(`${lid}:${p}`)) became.add(`${lid}:${p}`);
|
||||
};
|
||||
for (const lid of LINEAGE_IDS) for (const p of PRESSURE_IDS) apply(lid, p);
|
||||
for (const a of route) {
|
||||
s = nextState(s, a).state;
|
||||
for (const lid of LINEAGE_IDS) for (const p of PRESSURE_IDS) apply(lid, p);
|
||||
if (s.outcome !== "playing") break;
|
||||
}
|
||||
return [...became].map((k) => {
|
||||
const [lineage, pressure] = k.split(":") as [LineageId, PressureId];
|
||||
return { lineage, pressure };
|
||||
});
|
||||
}
|
||||
|
||||
export interface ReachableSet {
|
||||
set: InheritanceSet;
|
||||
key: string;
|
||||
}
|
||||
function inheritanceKey(is: InheritanceSet): string {
|
||||
return LINEAGE_IDS.map((lid) => `${lid}=(${(is[lid] ?? []).join(",")})`).join("|");
|
||||
}
|
||||
|
||||
/**
|
||||
* Enumerate reachable campaign inheritance sets by solving each scenario with
|
||||
* each reachable set, then branching on 0 or 1 newly-unlocked trait from the
|
||||
* found winning route. Returns the tree of sets and solvability per (scenario,set).
|
||||
*/
|
||||
export interface ReachabilityReport {
|
||||
perScenario: {
|
||||
scenarioId: string;
|
||||
sets: { key: string; set: InheritanceSet; solvable: boolean; win?: RotationAction[] | null; capped?: boolean }[];
|
||||
}[];
|
||||
}
|
||||
|
||||
export function verifyReachability(opts?: { maxNodes?: number }): ReachabilityReport {
|
||||
const report: ReachabilityReport = { perScenario: [] };
|
||||
let frontier: ReachableSet[] = [{ set: {}, key: inheritanceKey({}) }];
|
||||
for (const sc of SCENARIOS) {
|
||||
const entries: ReachabilityReport["perScenario"][number]["sets"] = [];
|
||||
const next: ReachableSet[] = [];
|
||||
const seenKeys = new Set<string>();
|
||||
for (let i = 0; i < frontier.length; i++) {
|
||||
const item = frontier[i]!;
|
||||
// Light win-finder (memory-bounded); fall back to exhaustive BFS if it caps.
|
||||
const fr = findRoute(sc.id, item.set, "won", { ...(opts as SolveOpts), seed: 0x1234 + i });
|
||||
let win: RotationAction[] | null = fr.route;
|
||||
let capped = fr.capped;
|
||||
if (!win && !capped) {
|
||||
// confirm with exhaustive search on smaller spaces
|
||||
const res = solve(sc.id, item.set, opts);
|
||||
win = res.win;
|
||||
capped = res.capped;
|
||||
}
|
||||
entries.push({ key: item.key, set: item.set, solvable: win !== null, win, capped });
|
||||
if (win) {
|
||||
const unlocked = unlockedAlong(sc.id, item.set, win);
|
||||
// branch: keep nothing, or keep one unlocked trait
|
||||
const candidates: ReachableSet[] = [{ set: item.set, key: item.key }];
|
||||
for (const u of unlocked) {
|
||||
const ns: InheritanceSet = {
|
||||
producer: [...(item.set.producer ?? [])],
|
||||
grazer: [...(item.set.grazer ?? [])],
|
||||
};
|
||||
ns[u.lineage] = [...new Set([...(ns[u.lineage] ?? []), u.pressure])].sort() as PressureId[];
|
||||
const k = inheritanceKey(ns);
|
||||
candidates.push({ set: ns, key: k });
|
||||
}
|
||||
for (const c of candidates) {
|
||||
if (!seenKeys.has(c.key)) {
|
||||
seenKeys.add(c.key);
|
||||
next.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
report.perScenario.push({ scenarioId: sc.id, sets: entries });
|
||||
frontier = next;
|
||||
if (frontier.length === 0) break; // unsolvable predecessor; stop
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
/** Counterfactual: freeze sharedOwner at baseline. At least one scenario must be unwinnable. */
|
||||
export function counterfactualUnwinnable(
|
||||
scenarioId: string,
|
||||
opts?: { maxNodes?: number },
|
||||
): { solvableNormal: boolean; solvableFrozen: boolean; normal: SolveResult; frozen: SolveResult } {
|
||||
const normal = solve(scenarioId, {}, opts);
|
||||
const frozen = solve(scenarioId, {}, { ...opts, freezeOwnership: true });
|
||||
return {
|
||||
solvableNormal: normal.win !== null,
|
||||
solvableFrozen: frozen.win !== null,
|
||||
normal,
|
||||
frozen,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Adaptive Loop — domain types. Pure serializable data; no rendering, no time.
|
||||
// Mirrors SPEC §5 exactly. Fixtures/objective markers are NOT in GameState: they
|
||||
// are immutable scenario data looked up by scenarioId (see content/scenarios.ts).
|
||||
|
||||
export type LoopId = "A" | "B" | "C";
|
||||
export type Direction = "cw" | "ccw";
|
||||
export type LineageId = "producer" | "grazer";
|
||||
export type PressureId = "heat" | "hunger" | "toxin" | "immunity";
|
||||
export type Mode = "campaign" | "standalone";
|
||||
export type Outcome = "playing" | "won" | "collapsed" | "expired";
|
||||
|
||||
export const LOOP_IDS: LoopId[] = ["A", "B", "C"];
|
||||
export const LINEAGE_IDS: LineageId[] = ["producer", "grazer"];
|
||||
export const PRESSURE_IDS: PressureId[] = ["heat", "hunger", "toxin", "immunity"];
|
||||
|
||||
/** Movable chamber payload. All quantities are capped integers 0..6. */
|
||||
export interface Chamber {
|
||||
nutrient: number; // 0..6
|
||||
heat: number; // 0..6
|
||||
toxin: number; // 0..6
|
||||
producer: number; // 0..6
|
||||
grazer: number; // 0..6
|
||||
phage: number; // 0..6
|
||||
}
|
||||
|
||||
export interface Lineage {
|
||||
pressure: Record<PressureId, number>; // 0..3
|
||||
unlocked: Record<PressureId, boolean>;
|
||||
}
|
||||
|
||||
export interface RotationAction {
|
||||
loop: LoopId;
|
||||
direction: Direction;
|
||||
}
|
||||
|
||||
export interface GameState {
|
||||
schemaVersion: 1;
|
||||
mode: Mode;
|
||||
scenarioId: string;
|
||||
turn: number;
|
||||
loops: Record<LoopId, { direction: Direction }>;
|
||||
/** Keyed by slot index as string. Only shared slots {2,3,4,5,8,9} are stored. */
|
||||
sharedOwner: Record<string, LoopId>;
|
||||
chambers: Chamber[]; // length 12
|
||||
lineage: Record<LineageId, Lineage>;
|
||||
inheritedAtStart: Record<LineageId, PressureId[]>;
|
||||
consecutiveObjectiveTurns: number;
|
||||
environmentActive: Record<PressureId, boolean>;
|
||||
outcome: Outcome;
|
||||
actionLog: RotationAction[];
|
||||
}
|
||||
|
||||
/** Discrete tick event for the event panel (deterministic from state + action). */
|
||||
export interface GameEvent {
|
||||
phase:
|
||||
| "rotate"
|
||||
| "flow"
|
||||
| "growth"
|
||||
| "interact"
|
||||
| "migrate"
|
||||
| "evolve"
|
||||
| "fixtures"
|
||||
| "pressure"
|
||||
| "outcome";
|
||||
kind: string;
|
||||
slot?: number;
|
||||
lineage?: LineageId;
|
||||
pressure?: PressureId;
|
||||
text: string;
|
||||
delta?: Partial<Record<"producer" | "grazer" | "phage" | "nutrient" | "heat" | "toxin", number>>;
|
||||
}
|
||||
|
||||
export interface TurnResult {
|
||||
state: GameState;
|
||||
events: GameEvent[];
|
||||
}
|
||||
@@ -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 };
|
||||
@@ -0,0 +1,130 @@
|
||||
// Adaptive Loop — versioned persistence (SPEC §11). localStorage envelope with
|
||||
// schema/value validation and safe failure. savedAt is outside canonical compare.
|
||||
import type { GameState, Outcome, RotationAction, LineageId, PressureId } from "../domain/types";
|
||||
import { SCENARIOS, SCENARIO_BY_ID } from "../content/scenarios";
|
||||
import type { InheritanceSet } from "../content/scenarios";
|
||||
import { STORAGE_KEY } from "../content/scenarios";
|
||||
import { createScenarioState } from "../domain/scenario";
|
||||
import { nextState } from "../domain/pipeline";
|
||||
import { canonicalStringify } from "../domain/serialize";
|
||||
|
||||
export interface CampaignProgress {
|
||||
unlocked: string[]; // scenario ids unlocked (s1 always unlocked)
|
||||
inherited: InheritanceSet; // cumulative preserved traits across the campaign
|
||||
entrySnapshot: Record<string, InheritanceSet>; // inheritance at first entry per scenario
|
||||
}
|
||||
|
||||
export interface SaveEnvelope {
|
||||
schemaVersion: 1;
|
||||
state: GameState; // canonical current game state
|
||||
campaign: CampaignProgress;
|
||||
savedAt: number; // outside canonical comparison
|
||||
}
|
||||
|
||||
export interface StorageAdapter {
|
||||
loadRaw(): string | null;
|
||||
saveRaw(s: string): void;
|
||||
removeRaw(): void;
|
||||
}
|
||||
|
||||
export const SCHEMA_VERSION = 1;
|
||||
|
||||
/** Browser localStorage adapter (guarded for non-browser / disabled storage). */
|
||||
export function browserStorage(): StorageAdapter {
|
||||
return {
|
||||
loadRaw() {
|
||||
try {
|
||||
return typeof localStorage !== "undefined" ? localStorage.getItem(STORAGE_KEY) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
saveRaw(s: string) {
|
||||
try {
|
||||
if (typeof localStorage !== "undefined") localStorage.setItem(STORAGE_KEY, s);
|
||||
} catch {
|
||||
/* quota / disabled — ignore; game continues in-memory */
|
||||
}
|
||||
},
|
||||
removeRaw() {
|
||||
try {
|
||||
if (typeof localStorage !== "undefined") localStorage.removeItem(STORAGE_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Validate envelope shape and value ranges; return null if malformed. */
|
||||
export function validateEnvelope(data: unknown): SaveEnvelope | null {
|
||||
if (!data || typeof data !== "object") return null;
|
||||
const e = data as Partial<SaveEnvelope>;
|
||||
if (e.schemaVersion !== SCHEMA_VERSION) return null;
|
||||
if (!e.state || typeof e.state !== "object") return null;
|
||||
const s = e.state as Partial<GameState>;
|
||||
if (s.schemaVersion !== 1) return null;
|
||||
if (!s.mode || !s.scenarioId || !SCENARIO_BY_ID[s.scenarioId]) return null;
|
||||
if (!Array.isArray(s.chambers) || s.chambers.length !== 12) return null;
|
||||
for (const c of s.chambers) {
|
||||
if (!c || typeof c !== "object") return null;
|
||||
for (const f of ["nutrient", "heat", "toxin", "producer", "grazer", "phage"] as const) {
|
||||
if (typeof c[f] !== "number" || c[f] < 0 || c[f] > 6 || !Number.isInteger(c[f])) return null;
|
||||
}
|
||||
}
|
||||
if (typeof s.turn !== "number" || s.turn < 0) return null;
|
||||
if (!s.loops || !s.sharedOwner || !s.lineage || !s.environmentActive) return null;
|
||||
if (!Array.isArray(s.actionLog)) return null;
|
||||
for (const a of s.actionLog as RotationAction[]) {
|
||||
if (!a || !["A", "B", "C"].includes(a.loop) || !["cw", "ccw"].includes(a.direction)) return null;
|
||||
}
|
||||
if (!["playing", "won", "collapsed", "expired"].includes(s.outcome as Outcome)) return null;
|
||||
if (!e.campaign || !Array.isArray(e.campaign.unlocked) || typeof e.campaign.inherited !== "object") return null;
|
||||
return e as SaveEnvelope;
|
||||
}
|
||||
|
||||
export function saveEnvelope(env: SaveEnvelope, store: StorageAdapter): void {
|
||||
store.saveRaw(canonicalStringify({ ...env, savedAt: Date.now() }));
|
||||
}
|
||||
|
||||
export function loadEnvelope(store: StorageAdapter): { env: SaveEnvelope } | { env: null } {
|
||||
const raw = store.loadRaw();
|
||||
if (!raw) return { env: null };
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
const env = validateEnvelope(parsed);
|
||||
return { env };
|
||||
} catch {
|
||||
return { env: null }; // malformed -> safe recovery (caller offers New Campaign / Retry)
|
||||
}
|
||||
}
|
||||
|
||||
export function clearSave(store: StorageAdapter): void {
|
||||
store.removeRaw();
|
||||
}
|
||||
|
||||
/** Replay a state's action log from its baseline + entry inheritance; must reproduce canonical state. */
|
||||
export function replayFromBaseline(state: GameState): GameState {
|
||||
const inheritance: InheritanceSet = {
|
||||
producer: [...state.inheritedAtStart.producer] as PressureId[],
|
||||
grazer: [...state.inheritedAtStart.grazer] as PressureId[],
|
||||
};
|
||||
let s = createScenarioState(state.scenarioId, state.mode, inheritance);
|
||||
for (const a of state.actionLog) {
|
||||
s = nextState(s, a).state;
|
||||
if (s.outcome !== "playing") break;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
export function emptyCampaign(): CampaignProgress {
|
||||
return {
|
||||
unlocked: [SCENARIOS[0]!.id],
|
||||
inherited: {},
|
||||
entrySnapshot: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function lineageIds(): LineageId[] {
|
||||
return ["producer", "grazer"];
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Adaptive Loop — board geometry. Three interlocking hexagonal rings (SPEC §4, §13).
|
||||
// Slots are placed at the vertices of three mutually-adjacent flat-top hexagons;
|
||||
// shared slots coincide at the ring overlaps. Pure data, no DOM.
|
||||
import type { LoopId } from "../domain/types";
|
||||
import { LOOPS } from "../domain/constants";
|
||||
|
||||
export interface Pt { x: number; y: number; }
|
||||
|
||||
// Three flat-top hexagon centers (mutually adjacent cluster), vertex radius R.
|
||||
const R = 78;
|
||||
const SQRT3 = Math.sqrt(3);
|
||||
// centers: A central-left, B right, C top — chosen so the three rings overlap
|
||||
// pairwise and read as interlocking from a single viewpoint.
|
||||
const CENTERS: Record<LoopId, Pt> = {
|
||||
A: { x: 150, y: 250 },
|
||||
B: { x: 150 + 1.5 * R, y: 250 - (R * SQRT3) / 2 },
|
||||
C: { x: 150, y: 250 - R * SQRT3 },
|
||||
};
|
||||
|
||||
function hexVertices(c: Pt, r: number): Pt[] {
|
||||
// flat-top: vertices at 0,60,...,300 degrees
|
||||
const v: Pt[] = [];
|
||||
for (let k = 0; k < 6; k++) {
|
||||
const a = (k * 60 * Math.PI) / 180;
|
||||
v.push({ x: c.x + r * Math.cos(a), y: c.y + r * Math.sin(a) });
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// Build a coordinate per slot by assigning each loop's vertex order, then dedup
|
||||
// shared slots to a single point (averaged) so overlaps coincide visually.
|
||||
function buildSlots(): { slots: Pt[]; polygons: Record<LoopId, Pt[]> } {
|
||||
const rawPerLoop: Record<LoopId, { slot: number; pt: Pt }[]> = { A: [], B: [], C: [] };
|
||||
(Object.keys(LOOPS) as LoopId[]).forEach((L) => {
|
||||
const verts = hexVertices(CENTERS[L], R);
|
||||
LOOPS[L].forEach((slot, i) => {
|
||||
rawPerLoop[L].push({ slot, pt: verts[i]! });
|
||||
});
|
||||
});
|
||||
// collect each slot's candidate points (a shared slot gets >1), average them
|
||||
const acc: Record<number, Pt[]> = {};
|
||||
(Object.keys(rawPerLoop) as LoopId[]).forEach((L) => {
|
||||
for (const e of rawPerLoop[L]) {
|
||||
(acc[e.slot] ??= []).push(e.pt);
|
||||
}
|
||||
});
|
||||
const slots: Pt[] = [];
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const pts = acc[i] ?? [{ x: 0, y: 0 }];
|
||||
const ax = pts.reduce((s, p) => s + p.x, 0) / pts.length;
|
||||
const ay = pts.reduce((s, p) => s + p.y, 0) / pts.length;
|
||||
slots[i] = { x: ax, y: ay };
|
||||
}
|
||||
const polygons = {} as Record<LoopId, Pt[]>;
|
||||
(Object.keys(LOOPS) as LoopId[]).forEach((L) => {
|
||||
polygons[L] = LOOPS[L].map((slot) => slots[slot]!);
|
||||
});
|
||||
return { slots, polygons };
|
||||
}
|
||||
|
||||
const built = buildSlots();
|
||||
export const SLOT_POS: Pt[] = built.slots;
|
||||
export const LOOP_POLYGONS: Record<LoopId, Pt[]> = built.polygons;
|
||||
|
||||
export const VIEWBOX = { w: 460, h: 420 };
|
||||
|
||||
export function loopCenter(L: LoopId): Pt {
|
||||
return CENTERS[L];
|
||||
}
|
||||
|
||||
/** Outlet direction unit vector at a slot (for flow arrow rendering). */
|
||||
export function outletVector(from: Pt, to: Pt): Pt {
|
||||
const dx = to.x - from.x;
|
||||
const dy = to.y - from.y;
|
||||
const len = Math.hypot(dx, dy) || 1;
|
||||
return { x: dx / len, y: dy / len };
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// Adaptive Loop — campaign/session controller (SPEC §10). Pure orchestration
|
||||
// over (GameState, CampaignProgress); the UI holds a Session and calls these.
|
||||
import type { GameState, LineageId, Mode, PressureId, RotationAction } from "./domain/types";
|
||||
import { LINEAGE_IDS, PRESSURE_IDS } from "./domain/types";
|
||||
import { createScenarioState } from "./domain/scenario";
|
||||
import { nextState } from "./domain/pipeline";
|
||||
import { SCENARIOS, SCENARIO_BY_ID } from "./content/scenarios";
|
||||
import type { InheritanceSet } from "./content/scenarios";
|
||||
import { emptyCampaign, type CampaignProgress } from "./persistence/save";
|
||||
|
||||
export interface Session {
|
||||
state: GameState;
|
||||
campaign: CampaignProgress;
|
||||
}
|
||||
|
||||
export function startCampaign(): Session {
|
||||
const campaign = emptyCampaign();
|
||||
const state = enterScenario(campaign, SCENARIOS[0]!.id, "campaign");
|
||||
return { state, campaign };
|
||||
}
|
||||
|
||||
/** Build a fresh game state for a scenario. Campaign mode uses cumulative
|
||||
* inherited traits (and records the entry snapshot); standalone uses a clean baseline. */
|
||||
export function enterScenario(campaign: CampaignProgress, scenarioId: string, mode: Mode): GameState {
|
||||
const inheritance: InheritanceSet =
|
||||
mode === "campaign"
|
||||
? { producer: [...(campaign.inherited.producer ?? [])], grazer: [...(campaign.inherited.grazer ?? [])] }
|
||||
: {};
|
||||
const state = createScenarioState(scenarioId, mode, inheritance);
|
||||
if (mode === "campaign" && !campaign.entrySnapshot[scenarioId]) {
|
||||
campaign.entrySnapshot[scenarioId] = {
|
||||
producer: [...(campaign.inherited.producer ?? [])] as PressureId[],
|
||||
grazer: [...(campaign.inherited.grazer ?? [])] as PressureId[],
|
||||
};
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
export interface CommitResult {
|
||||
session: Session;
|
||||
result: { state: GameState; events: import("./domain/types").GameEvent[] };
|
||||
}
|
||||
|
||||
export function commit(session: Session, action: RotationAction): CommitResult {
|
||||
const res = nextState(session.state, action);
|
||||
const next: Session = { state: res.state, campaign: session.campaign };
|
||||
return { session: next, result: res };
|
||||
}
|
||||
|
||||
/** Retry: restore the scenario-entry inheritance snapshot (clean baseline of this scenario). */
|
||||
export function retry(session: Session): Session {
|
||||
const snapshot = session.campaign.entrySnapshot[session.state.scenarioId] ?? {};
|
||||
const state = createScenarioState(session.state.scenarioId, session.state.mode, snapshot);
|
||||
return { state, campaign: session.campaign };
|
||||
}
|
||||
|
||||
/** Traits unlocked during this run that are not already inherited — eligible to preserve. */
|
||||
export function eligibleTraits(session: Session): { lineage: LineageId; pressure: PressureId }[] {
|
||||
const out: { lineage: LineageId; pressure: PressureId }[] = [];
|
||||
for (const lid of LINEAGE_IDS) {
|
||||
const inherited = new Set(session.campaign.inherited[lid] ?? []);
|
||||
for (const p of PRESSURE_IDS) {
|
||||
if (session.state.lineage[lid].unlocked[p] && !inherited.has(p)) {
|
||||
out.push({ lineage: lid, pressure: p });
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Preserve zero or one eligible trait into the cumulative campaign inheritance. */
|
||||
export function preserveTrait(campaign: CampaignProgress, trait: { lineage: LineageId; pressure: PressureId } | null): CampaignProgress {
|
||||
if (!trait) return campaign;
|
||||
const next: CampaignProgress = {
|
||||
unlocked: [...campaign.unlocked],
|
||||
inherited: {
|
||||
producer: [...(campaign.inherited.producer ?? [])] as PressureId[],
|
||||
grazer: [...(campaign.inherited.grazer ?? [])] as PressureId[],
|
||||
},
|
||||
entrySnapshot: { ...campaign.entrySnapshot },
|
||||
};
|
||||
next.inherited[trait.lineage] = [...new Set([...(next.inherited[trait.lineage] ?? []), trait.pressure])].sort() as PressureId[];
|
||||
return next;
|
||||
}
|
||||
|
||||
/** On a scenario win, unlock the next scenario (if any). */
|
||||
export function unlockNext(campaign: CampaignProgress, scenarioId: string): CampaignProgress {
|
||||
const idx = SCENARIO_BY_ID[scenarioId]?.index ?? 0;
|
||||
const nextSc = SCENARIOS.find((s) => s.index === idx + 1);
|
||||
if (!nextSc) return campaign;
|
||||
const unlocked = campaign.unlocked.includes(nextSc.id) ? campaign.unlocked : [...campaign.unlocked, nextSc.id];
|
||||
return { ...campaign, unlocked };
|
||||
}
|
||||
|
||||
/** The scenario the campaign should enter next (most recent unlocked progress). */
|
||||
export function nextScenarioId(campaign: CampaignProgress): string {
|
||||
const last = SCENARIOS.filter((s) => campaign.unlocked.includes(s.id)).slice(-1)[0];
|
||||
return last ? last.id : SCENARIOS[0]!.id;
|
||||
}
|
||||
|
||||
export function isCampaignVictory(session: Session): boolean {
|
||||
const last = SCENARIOS[SCENARIOS.length - 1]!;
|
||||
return session.state.scenarioId === last.id && session.state.outcome === "won";
|
||||
}
|
||||
|
||||
// Fix the startCampaign return shape (kept simple + correct below).
|
||||
export function newCampaignSession(): Session {
|
||||
const campaign = emptyCampaign();
|
||||
const state = enterScenario(campaign, SCENARIOS[0]!.id, "campaign");
|
||||
return { state, campaign };
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
/* Dark laboratory-glass palette (SPEC §13). */
|
||||
--bg: #070b0f;
|
||||
--bg-2: #0c131b;
|
||||
--panel: #0f1a24;
|
||||
--panel-2: #0b141d;
|
||||
--glass: #0a141e;
|
||||
--ink: #eaf1f8;
|
||||
--muted: #93a4b6;
|
||||
--line: #21303f;
|
||||
--line-2: #2c3f4f;
|
||||
--accent: #5fd3f0; /* producer / loops accent — AA on dark */
|
||||
--grazer: #f2c14e; /* grazer */
|
||||
--phage: #c77dff; /* phage */
|
||||
--nutrient: #7ee787; /* nutrient */
|
||||
--heat: #ff7b72; /* heat */
|
||||
--toxin: #d2a8ff; /* toxin */
|
||||
--immunity: #79c0ff; /* immunity */
|
||||
--good: #8fd17a;
|
||||
--bad: #ff6b6b;
|
||||
--warn: #e6c07b;
|
||||
--ring-a: #5fd3f0;
|
||||
--ring-b: #f2c14e;
|
||||
--ring-c: #c77dff;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { height: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
background:
|
||||
radial-gradient(1200px 700px at 50% -10%, #0e1a26 0%, var(--bg) 60%) fixed,
|
||||
var(--bg);
|
||||
color: var(--ink);
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.45;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
h1, h2, h3 { margin: 0 0 0.3em; line-height: 1.15; }
|
||||
h1.title { font-size: clamp(1.8rem, 5vw, 2.8rem); letter-spacing: 0.02em; }
|
||||
.muted { color: var(--muted); }
|
||||
.small { font-size: 0.85rem; }
|
||||
.tagline { margin: 0 0 1.2rem; }
|
||||
.sr-only {
|
||||
position: absolute !important; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
|
||||
}
|
||||
.skip-link {
|
||||
position: absolute; left: -9999px; top: 0; z-index: 100;
|
||||
background: var(--accent); color: #04121a; padding: 0.5rem 0.9rem; border-radius: 6px; font-weight: 600;
|
||||
}
|
||||
.skip-link:focus { left: 8px; top: 8px; }
|
||||
:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; border-radius: 4px; }
|
||||
|
||||
#app { max-width: 1180px; margin: 0 auto; padding: 1rem; }
|
||||
.screen { padding: 0.5rem 0; }
|
||||
|
||||
/* ---------- title ---------- */
|
||||
.title-screen { text-align: center; padding-top: 2.5rem; }
|
||||
.menu { display: flex; flex-direction: column; gap: 0.6rem; align-items: stretch; max-width: 24rem; margin: 1rem auto; }
|
||||
.help { max-width: 42rem; margin: 1.5rem auto 0; text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 0.8rem 1rem; }
|
||||
.help summary { cursor: pointer; font-weight: 600; }
|
||||
.help-body ul { margin: 0.5rem 0; padding-left: 1.2rem; }
|
||||
.help-body li { margin: 0.2rem 0; }
|
||||
|
||||
/* ---------- buttons ---------- */
|
||||
.btn {
|
||||
font: inherit; font-weight: 600;
|
||||
color: var(--ink); background: var(--panel);
|
||||
border: 1px solid var(--line); border-radius: 8px;
|
||||
padding: 0.6rem 0.9rem; cursor: pointer;
|
||||
transition: background 0.12s ease, border-color 0.12s ease, transform 0.05s ease;
|
||||
}
|
||||
.btn:hover { background: #15233200; background-color: #14222f; }
|
||||
.btn:active { transform: translateY(1px); }
|
||||
.btn.primary { background: var(--accent); color: #04121a; border-color: var(--accent); }
|
||||
.btn.primary:hover { background: #7cdef6; }
|
||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
|
||||
/* ---------- game layout ---------- */
|
||||
.topbar { display: flex; align-items: center; gap: 0.8rem; flex-wrap: wrap; margin-bottom: 0.6rem; }
|
||||
.topbar h2 { margin: 0; font-size: 1.15rem; }
|
||||
.badge { color: var(--muted); border: 1px solid var(--line); padding: 0.1rem 0.5rem; border-radius: 999px; font-size: 0.8rem; }
|
||||
.controls { margin-left: auto; display: flex; gap: 0.4rem; flex-wrap: wrap; }
|
||||
.layout {
|
||||
display: grid;
|
||||
grid-template-columns: 16rem minmax(0, 1fr) 19rem;
|
||||
gap: 1rem;
|
||||
align-items: start;
|
||||
}
|
||||
.rail { background: var(--panel-2); border: 1px solid var(--line); border-radius: 10px; padding: 0.8rem; }
|
||||
.stat-row { display: flex; justify-content: space-between; gap: 0.5rem; padding: 0.25rem 0; border-bottom: 1px dashed var(--line); font-size: 0.9rem; }
|
||||
.stat-row:last-child { border-bottom: 0; }
|
||||
.stat-label { color: var(--muted); }
|
||||
.stat-value { font-weight: 600; text-align: right; }
|
||||
|
||||
/* ---------- board ---------- */
|
||||
.board-wrap { background: var(--glass); border: 1px solid var(--line); border-radius: 12px; padding: 0.5rem; }
|
||||
.board { width: 100%; height: auto; display: block; }
|
||||
.loop-ring { fill: none; stroke-width: 4; opacity: 0.5; }
|
||||
.loop-a { stroke: var(--ring-a); }
|
||||
.loop-b { stroke: var(--ring-b); }
|
||||
.loop-c { stroke: var(--ring-c); }
|
||||
.loop-label { font-size: 26px; font-weight: 800; fill: var(--muted); opacity: 0.3; pointer-events: none; }
|
||||
.chamber { fill: #0d1924; stroke: var(--line); stroke-width: 2; }
|
||||
.chamber-group .chamber-pop { font-size: 13px; font-weight: 700; fill: var(--ink); }
|
||||
.sp-producer { fill: var(--accent); }
|
||||
.sp-grazer { fill: var(--grazer); }
|
||||
.sp-phage { fill: var(--phage); }
|
||||
.chamber-res { font-size: 10px; fill: var(--muted); }
|
||||
.chamber-delta { font-size: 10px; font-weight: 700; fill: var(--accent); }
|
||||
.fixture { font-size: 11px; font-weight: 700; }
|
||||
.fixture-nutrientInlet { fill: var(--nutrient); }
|
||||
.fixture-toxinInlet { fill: var(--toxin); }
|
||||
.fixture-heatSource { fill: var(--heat); }
|
||||
.fixture-drain { fill: var(--immunity); }
|
||||
.fixture-immuneNode { fill: var(--immunity); }
|
||||
.fixture-objectiveMarker { fill: var(--warn); }
|
||||
.flow-arrow { stroke-width: 3; opacity: 0.55; pointer-events: none; }
|
||||
.flow-nutrient { stroke: var(--nutrient); color: var(--nutrient); }
|
||||
.flow-toxin { stroke: var(--toxin); color: var(--toxin); stroke-dasharray: 4 3; }
|
||||
|
||||
.commit-bar { display: flex; gap: 0.5rem; margin-top: 0.6rem; flex-wrap: wrap; }
|
||||
.rotation-grid {
|
||||
display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.4rem; margin-top: 0.6rem;
|
||||
}
|
||||
.rot-btn { font-size: 0.85rem; padding: 0.5rem 0.3rem; }
|
||||
|
||||
/* ---------- right rail panels ---------- */
|
||||
.panel { background: var(--panel-2); border: 1px solid var(--line); border-radius: 10px; padding: 0.7rem 0.8rem; margin-bottom: 0.6rem; }
|
||||
.panel-h { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); margin-bottom: 0.4rem; }
|
||||
.lineage-row { display: grid; grid-template-columns: 5.5rem repeat(4, 1fr); gap: 0.3rem; align-items: center; margin-bottom: 0.4rem; }
|
||||
.lineage-name { font-size: 0.78rem; color: var(--muted); }
|
||||
.pressure-cell {
|
||||
display: flex; flex-direction: column; align-items: center; gap: 1px;
|
||||
border: 1px solid var(--line); border-radius: 6px; padding: 0.2rem 0; font-size: 0.75rem;
|
||||
background: #0a141d;
|
||||
}
|
||||
.pressure-cell.unlocked { border-color: var(--good); background: #0f2018; }
|
||||
.pressure-glyph { font-size: 0.95rem; }
|
||||
.pressure-val { font-weight: 700; }
|
||||
.adapted-tag { color: var(--good); font-size: 0.7rem; }
|
||||
.in-game-help { margin: 0 0 0.6rem; }
|
||||
.env-row { font-size: 0.78rem; color: var(--warn); margin-top: 0.3rem; }
|
||||
.preview-box .outcome { font-weight: 700; }
|
||||
.outcome-won { color: var(--good); }
|
||||
.outcome-collapsed, .outcome-expired { color: var(--bad); }
|
||||
.preview-events { margin: 0.3rem 0 0; padding-left: 1.1rem; font-size: 0.78rem; }
|
||||
.event-box { max-height: 16rem; overflow: auto; }
|
||||
.event-list { margin: 0; padding-left: 1.1rem; font-size: 0.78rem; }
|
||||
.event-list li { margin: 0.15rem 0; }
|
||||
.event-outcome { font-weight: 700; color: var(--accent); }
|
||||
|
||||
/* ---------- scenario pick / trait ---------- */
|
||||
.scenario-list { display: flex; flex-direction: column; gap: 0.5rem; max-width: 30rem; margin: 1rem auto; }
|
||||
.scenario-item { border: 1px solid var(--line); border-radius: 8px; padding: 0.4rem 0.6rem; }
|
||||
.trait-screen { text-align: center; padding-top: 2rem; }
|
||||
|
||||
/* ---------- responsive ---------- */
|
||||
@media (max-width: 920px) {
|
||||
.layout { grid-template-columns: 1fr; }
|
||||
.rail-left, .rail-right { order: 2; }
|
||||
.board-wrap { order: 1; }
|
||||
}
|
||||
@media (max-width: 390px) {
|
||||
#app { padding: 0.4rem; }
|
||||
h1.title { font-size: 1.5rem; }
|
||||
.rot-btn { font-size: 0.78rem; padding: 0.45rem 0.1rem; }
|
||||
.lineage-row { grid-template-columns: 4.6rem repeat(4, 1fr); }
|
||||
}
|
||||
/* 200% zoom: ensure controls stay reachable and labels readable */
|
||||
@media (min-resolution: 1.9dppx) {
|
||||
.controls { width: 100%; }
|
||||
.btn { font-size: 1rem; }
|
||||
}
|
||||
|
||||
/* ---------- reduced motion ---------- */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* { transition: none !important; animation: none !important; }
|
||||
.btn:active { transform: none; }
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
Reference in new issue
Block a user