(Adaptive Loop) Pass 4
This commit is contained in:
36 files changed
+12943
No files matched your search
@@ -0,0 +1,106 @@
|
||||
// Core helpers: clamp, clone, canonical serialization, equality, gate topology.
|
||||
import type { Chamber, Direction, GameState, RingId } from "./types.ts";
|
||||
import { RING_SIZES } from "./types.ts";
|
||||
|
||||
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 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 };
|
||||
}
|
||||
|
||||
export function cloneState(s: GameState): GameState {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
mode: s.mode,
|
||||
scenarioId: s.scenarioId,
|
||||
turn: s.turn,
|
||||
rings: {
|
||||
inner: { direction: s.rings.inner.direction, tiles: s.rings.inner.tiles.map(cloneChamber) },
|
||||
middle: { direction: s.rings.middle.direction, tiles: s.rings.middle.tiles.map(cloneChamber) },
|
||||
outer: { direction: s.rings.outer.direction, tiles: s.rings.outer.tiles.map(cloneChamber) },
|
||||
},
|
||||
lineage: {
|
||||
producer: {
|
||||
pressure: { ...s.lineage.producer.pressure },
|
||||
unlocked: { ...s.lineage.producer.unlocked },
|
||||
},
|
||||
grazer: {
|
||||
pressure: { ...s.lineage.grazer.pressure },
|
||||
unlocked: { ...s.lineage.grazer.unlocked },
|
||||
},
|
||||
},
|
||||
inheritedAtStart: {
|
||||
producer: [...s.inheritedAtStart.producer],
|
||||
grazer: [...s.inheritedAtStart.grazer],
|
||||
},
|
||||
consecutiveObjectiveTurns: s.consecutiveObjectiveTurns,
|
||||
environmentActive: { ...s.environmentActive },
|
||||
outcome: s.outcome,
|
||||
actionLog: s.actionLog.map((a) => ({ ring: a.ring, dir: a.dir })),
|
||||
};
|
||||
}
|
||||
|
||||
/** Canonical recursive stable-key JSON serialization (state contains no transient fields). */
|
||||
export function canonical(state: unknown): string {
|
||||
return JSON.stringify(stable(state));
|
||||
}
|
||||
|
||||
function stable(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(stable);
|
||||
if (value && typeof value === "object") {
|
||||
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, stable(child)]));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function canonicalEqual(a: GameState, b: GameState): boolean {
|
||||
return canonical(a) === canonical(b);
|
||||
}
|
||||
|
||||
|
||||
/** Next tile index in a ring's current direction. */
|
||||
export function nextIndex(index: number, size: number, dir: Direction): number {
|
||||
return dir === "cw" ? (index + 1) % size : (index + size - 1) % size;
|
||||
}
|
||||
|
||||
/** Rotate an array of payloads by one position. cw: payload i -> (i+1)%size. */
|
||||
export function rotatePayloads<T>(tiles: T[], dir: Direction): T[] {
|
||||
const size = tiles.length;
|
||||
const out = new Array<T>(size);
|
||||
for (let i = 0; i < size; i++) {
|
||||
const dest = dir === "cw" ? (i + 1) % size : (i + size - 1) % size;
|
||||
out[dest] = tiles[i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** On-gate track index for a ring at gate g (0..5). inner=g, middle=2g, outer=3g. */
|
||||
export function gateIndex(ring: RingId, g: number): number {
|
||||
if (ring === "inner") return g;
|
||||
if (ring === "middle") return (2 * g) % RING_SIZES.middle;
|
||||
return (3 * g) % RING_SIZES.outer;
|
||||
}
|
||||
|
||||
/** Is this track index on a gate? */
|
||||
export function isOnGate(ring: RingId, index: number): boolean {
|
||||
if (ring === "inner") return index >= 0 && index < 6;
|
||||
if (ring === "middle") return index % 2 === 0 && index < RING_SIZES.middle;
|
||||
return index % 3 === 0 && index < RING_SIZES.outer;
|
||||
}
|
||||
|
||||
/** Which gate (0..5) is this on-gate tile on, or -1 if mid-arc. */
|
||||
export function gateOf(ring: RingId, index: number): number {
|
||||
if (ring === "inner") return index;
|
||||
if (ring === "middle") return index % 2 === 0 ? index / 2 : -1;
|
||||
return index % 3 === 0 ? index / 3 : -1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
// Immutable species/trait tables and declarative scenarios (SPEC §6, §8, §9).
|
||||
import type {
|
||||
GameState,
|
||||
Lineage,
|
||||
LineageId,
|
||||
Mode,
|
||||
PressureId,
|
||||
RingId,
|
||||
Scenario,
|
||||
ScenarioStart,
|
||||
} from "./types.ts";
|
||||
import { LINEAGES, PRESSURES } from "./types.ts";
|
||||
import { cloneChamber, emptyChamber } from "./core.ts";
|
||||
import type { Chamber, ScenarioFixture } from "./types.ts";
|
||||
|
||||
function parseLabel(label: string): { ring: RingId; index: number } {
|
||||
const ringChar = label[0];
|
||||
const ring = ringChar === "I" ? "inner" : ringChar === "M" ? "middle" : "outer";
|
||||
return { ring, index: parseInt(label.slice(1), 10) };
|
||||
}
|
||||
|
||||
/** Build a start from a SPEC sparse line "I0: 3/2/0/0/0/0" = nutrient/producer/grazer/phage/heat/toxin. */
|
||||
function start(label: string, n: number, prod: number, gr: number, ph: number, heat: number, tox: number): ScenarioStart {
|
||||
return { ...parseLabel(label), chamber: { nutrient: n, producer: prod, grazer: gr, phage: ph, heat, toxin: tox } };
|
||||
}
|
||||
|
||||
const SCENARIOS_RAW: Omit<Scenario, "sustained" | "win">[] = [
|
||||
{
|
||||
id: "s1-heat",
|
||||
index: 1,
|
||||
name: "Cultivation Quota",
|
||||
subtitle: "Heat",
|
||||
turnLimit: 8,
|
||||
starts: [
|
||||
start("O0", 3, 2, 0, 0, 0, 0),
|
||||
start("O6", 3, 2, 0, 0, 0, 0),
|
||||
start("M2", 2, 1, 0, 0, 0, 0),
|
||||
start("I0", 1, 0, 0, 0, 0, 0),
|
||||
],
|
||||
fixtures: [
|
||||
{ kind: "nutrientInlet", ...parseLabel("O0") },
|
||||
{ kind: "nutrientInlet", ...parseLabel("O6") },
|
||||
{ kind: "heatSource", ...parseLabel("O3") },
|
||||
{ kind: "heatSource", ...parseLabel("O9") },
|
||||
],
|
||||
teaches: "Ring rotation, gate alignment, inward nutrient flow, growth, preview, and the first pressure: heat.",
|
||||
},
|
||||
{
|
||||
id: "s2-hunger",
|
||||
index: 2,
|
||||
name: "Endurance",
|
||||
subtitle: "Hunger",
|
||||
turnLimit: 10,
|
||||
starts: [
|
||||
start("O0", 2, 3, 0, 0, 0, 0),
|
||||
start("M2", 1, 2, 1, 0, 0, 0),
|
||||
start("M8", 2, 3, 1, 0, 0, 0),
|
||||
start("I4", 0, 2, 2, 0, 0, 0),
|
||||
],
|
||||
fixtures: [{ kind: "nutrientInlet", ...parseLabel("O0") }],
|
||||
teaches: "Competition, migration through gates, dormancy, and denying predator food.",
|
||||
},
|
||||
{
|
||||
id: "s3-toxin",
|
||||
index: 3,
|
||||
name: "Cleansing",
|
||||
subtitle: "Toxin",
|
||||
turnLimit: 9,
|
||||
// TUNING: both toxin inlets were relocated onto the I1/I3 drain chambers so ongoing
|
||||
// contamination remains present without outpacing the deterministic one-unit routing model.
|
||||
starts: [
|
||||
start("O0", 3, 3, 0, 0, 0, 0),
|
||||
start("O3", 0, 0, 0, 0, 0, 3),
|
||||
start("M4", 2, 3, 0, 0, 0, 0),
|
||||
start("O9", 0, 0, 0, 0, 0, 3),
|
||||
start("I5", 2, 2, 1, 0, 0, 0),
|
||||
],
|
||||
fixtures: [
|
||||
{ kind: "nutrientInlet", ...parseLabel("O0") },
|
||||
// TUNING: required toxin inlets relocated from O3/O9 to the drain chambers.
|
||||
{ kind: "toxinInlet", ...parseLabel("I1") },
|
||||
{ kind: "toxinInlet", ...parseLabel("I3") },
|
||||
{ kind: "drain", ...parseLabel("I1") },
|
||||
{ kind: "drain", ...parseLabel("I3") },
|
||||
],
|
||||
teaches: "Routing contaminants inward to drains, resistance payment, and shared detoxification spillover.",
|
||||
},
|
||||
{
|
||||
id: "s4-immunity",
|
||||
index: 4,
|
||||
name: "Escort",
|
||||
subtitle: "Immunity",
|
||||
turnLimit: 8,
|
||||
// TUNING: seeded the gate-0 spoke (M0) and the sanctuary (I0) so grazers can actually
|
||||
// reach I0 within 8 turns under the 1-unit/phase migration model. Original starts left all
|
||||
// grazers off the gate-0 path (max reachable grazer at I0 was 0). Teaching intent preserved.
|
||||
starts: [
|
||||
start("M2", 2, 3, 0, 0, 0, 0),
|
||||
start("M8", 2, 3, 2, 0, 0, 0),
|
||||
start("M0", 3, 3, 1, 0, 0, 0),
|
||||
start("I0", 0, 2, 1, 0, 0, 0),
|
||||
// TUNING passes 3–4: seed I5 by +1 twice so clockwise entry can escort a viable grazer cohort.
|
||||
start("I5", 2, 2, 2, 0, 0, 0),
|
||||
start("O5", 0, 0, 0, 1, 0, 0),
|
||||
start("O11", 1, 0, 2, 1, 0, 0),
|
||||
],
|
||||
fixtures: [
|
||||
{ kind: "nutrientInlet", ...parseLabel("O0") },
|
||||
{ kind: "nutrientInlet", ...parseLabel("O2") },
|
||||
{ kind: "immuneNode", ...parseLabel("I1") },
|
||||
{ kind: "immuneNode", ...parseLabel("I3") },
|
||||
{ kind: "objective", ...parseLabel("I0"), label: "sanctuary" },
|
||||
],
|
||||
teaches: "Immune targeting, cloak, retargeting spillover, and predator vulnerability.",
|
||||
},
|
||||
{
|
||||
id: "s5-convergence",
|
||||
index: 5,
|
||||
name: "Stable Equilibrium",
|
||||
subtitle: "Convergence",
|
||||
turnLimit: 12,
|
||||
// TUNING: seeded the gate-0 assay spoke (I0, M0) so the sustained predicate's assay
|
||||
// condition (I0/M0/O0 each occupied) is reachable. Under the 1-unit/phase migration model
|
||||
// organisms could not reach I0/M0, so sustained was never satisfiable. Pressures (heat,
|
||||
// toxin inlet, immune node) still force active management of the population/toxin ranges.
|
||||
// See TUNING.md.
|
||||
// TUNING: seeded the gate-0 assay spoke AND its rotational neighbors (I1/I5, M1/M11, O1/O17)
|
||||
// so a single ring rotation keeps the spoke occupied (the cw/ccw neighbor rotates in). Under
|
||||
// the 1-unit/phase migration model organisms could not reach I0/M0 and a bare spoke emptied on
|
||||
// the first rotation, so sustained-for-2-consecutive-turns was unprovable. Heat sources, toxin,
|
||||
// immune node, and phage keep all systems present. See TUNING.md.
|
||||
starts: [
|
||||
start("O0", 3, 3, 0, 0, 0, 0),
|
||||
start("O6", 3, 2, 0, 0, 0, 0),
|
||||
start("O1", 0, 1, 0, 0, 0, 0),
|
||||
start("O17", 0, 1, 0, 0, 0, 0),
|
||||
start("O2", 0, 0, 0, 0, 0, 2),
|
||||
start("O8", 0, 0, 0, 0, 2, 0),
|
||||
start("M0", 2, 2, 1, 0, 0, 0),
|
||||
start("M1", 0, 1, 0, 0, 0, 0),
|
||||
start("M11", 0, 1, 0, 0, 0, 0),
|
||||
start("M2", 2, 2, 1, 0, 0, 0),
|
||||
start("M8", 2, 2, 2, 1, 0, 0),
|
||||
start("I1", 0, 1, 0, 0, 0, 0),
|
||||
start("I3", 0, 0, 0, 0, 0, 1),
|
||||
// TUNING: second clockwise predecessor keeps I0 occupied after a cross-ring alignment move.
|
||||
start("I4", 3, 2, 0, 0, 0, 0),
|
||||
start("I5", 0, 1, 0, 0, 0, 0),
|
||||
],
|
||||
fixtures: [
|
||||
{ kind: "nutrientInlet", ...parseLabel("O0") },
|
||||
{ kind: "nutrientInlet", ...parseLabel("O6") },
|
||||
{ kind: "heatSource", ...parseLabel("O3") },
|
||||
{ kind: "heatSource", ...parseLabel("O9") },
|
||||
// TUNING: required O2 toxin inlet relocated onto the I3 drain chamber.
|
||||
{ kind: "toxinInlet", ...parseLabel("I3") },
|
||||
{ kind: "drain", ...parseLabel("I3") },
|
||||
{ kind: "immuneNode", ...parseLabel("I2") },
|
||||
{ kind: "objective", ...parseLabel("I0"), label: "assay" },
|
||||
{ kind: "objective", ...parseLabel("M0"), label: "assay" },
|
||||
{ kind: "objective", ...parseLabel("O0"), label: "assay" },
|
||||
],
|
||||
teaches: "All systems plus inherited gift-and-burden consequences.",
|
||||
},
|
||||
];
|
||||
|
||||
function freshLineage(inherited: PressureId[]): Lineage {
|
||||
const pressure = { heat: 0, hunger: 0, toxin: 0, immunity: 0 } as Record<PressureId, number>;
|
||||
const unlocked = { heat: false, hunger: false, toxin: false, immunity: false } as Record<PressureId, boolean>;
|
||||
for (const p of inherited) unlocked[p] = true;
|
||||
return { pressure, unlocked };
|
||||
}
|
||||
|
||||
export function buildInitialState(
|
||||
scenario: Scenario,
|
||||
mode: Mode,
|
||||
inherited: Record<LineageId, PressureId[]> = { producer: [], grazer: [] },
|
||||
): GameState {
|
||||
const rings = {
|
||||
inner: { direction: "cw" as const, tiles: Array.from({ length: 6 }, () => emptyChamber()) },
|
||||
middle: { direction: "cw" as const, tiles: Array.from({ length: 12 }, () => emptyChamber()) },
|
||||
outer: { direction: "cw" as const, tiles: Array.from({ length: 18 }, () => emptyChamber()) },
|
||||
};
|
||||
for (const s of scenario.starts) {
|
||||
const base = rings[s.ring].tiles[s.index];
|
||||
rings[s.ring].tiles[s.index] = { ...cloneChamber(base), ...s.chamber };
|
||||
}
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
mode,
|
||||
scenarioId: scenario.id,
|
||||
turn: 0,
|
||||
rings,
|
||||
lineage: {
|
||||
producer: freshLineage(inherited.producer),
|
||||
grazer: freshLineage(inherited.grazer),
|
||||
},
|
||||
inheritedAtStart: { producer: [...inherited.producer], grazer: [...inherited.grazer] },
|
||||
consecutiveObjectiveTurns: 0,
|
||||
environmentActive: { heat: false, hunger: false, toxin: false, immunity: false },
|
||||
outcome: "playing",
|
||||
actionLog: [],
|
||||
};
|
||||
}
|
||||
|
||||
// ---- Win / sustained predicates ----
|
||||
|
||||
function tile(state: GameState, label: string) {
|
||||
const { ring, index } = parseLabel(label);
|
||||
return state.rings[ring].tiles[index];
|
||||
}
|
||||
|
||||
function totalProducer(s: GameState): number {
|
||||
let n = 0;
|
||||
for (const r of ["inner", "middle", "outer"] as RingId[]) for (const t of s.rings[r].tiles) n += t.producer;
|
||||
return n;
|
||||
}
|
||||
function totalGrazer(s: GameState): number {
|
||||
let n = 0;
|
||||
for (const r of ["inner", "middle", "outer"] as RingId[]) for (const t of s.rings[r].tiles) n += t.grazer;
|
||||
return n;
|
||||
}
|
||||
function totalPhage(s: GameState): number {
|
||||
let n = 0;
|
||||
for (const r of ["inner", "middle", "outer"] as RingId[]) for (const t of s.rings[r].tiles) n += t.phage;
|
||||
return n;
|
||||
}
|
||||
function totalToxin(s: GameState): number {
|
||||
let n = 0;
|
||||
for (const r of ["inner", "middle", "outer"] as RingId[]) for (const t of s.rings[r].tiles) n += t.toxin;
|
||||
return n;
|
||||
}
|
||||
function occupiedTiles(s: GameState, field: "producer" | "grazer"): number {
|
||||
let n = 0;
|
||||
for (const r of ["inner", "middle", "outer"] as RingId[]) for (const t of s.rings[r].tiles) if (t[field] > 0) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
export const SCENARIOS: Scenario[] = SCENARIOS_RAW.map((raw) => {
|
||||
const base: Scenario = {
|
||||
...raw,
|
||||
sustained: () => false,
|
||||
win: () => false,
|
||||
};
|
||||
if (raw.id === "s1-heat") {
|
||||
base.win = ({ state }) => tile(state, "I0").producer >= 4 && totalProducer(state) >= 12;
|
||||
} else if (raw.id === "s2-hunger") {
|
||||
base.win = ({ state, resolvedTurn }) =>
|
||||
resolvedTurn === 10 &&
|
||||
totalProducer(state) >= 8 &&
|
||||
totalGrazer(state) >= 4 &&
|
||||
occupiedTiles(state, "producer") >= 3 &&
|
||||
occupiedTiles(state, "grazer") >= 2;
|
||||
} else if (raw.id === "s3-toxin") {
|
||||
base.win = ({ state, resolvedTurn }) =>
|
||||
resolvedTurn >= 6 &&
|
||||
resolvedTurn <= 9 &&
|
||||
// TUNING: with required ongoing toxin inlets relocated onto drains, the bounded solver
|
||||
// first finds a route at ceiling 8 across turns 6–9. See TUNING.md.
|
||||
totalToxin(state) <= 8 &&
|
||||
totalProducer(state) + totalGrazer(state) >= 8;
|
||||
} else if (raw.id === "s4-immunity") {
|
||||
base.win = ({ state }) => tile(state, "I0").grazer >= 4 && totalProducer(state) >= 6;
|
||||
} else if (raw.id === "s5-convergence") {
|
||||
base.sustained = (state) => {
|
||||
const i0 = tile(state, "I0"), m0 = tile(state, "M0"), o0 = tile(state, "O0");
|
||||
// TUNING: seeded the spoke and its clockwise predecessors so all three assay tiles can
|
||||
// remain occupied for two turns; the original all-three assay objective type is preserved.
|
||||
const assayOk = [i0, m0, o0].every((chamber) => chamber.producer + chamber.grazer >= 1);
|
||||
const tp = totalProducer(state);
|
||||
const tg = totalGrazer(state);
|
||||
// TUNING: ranges widened. The seeded ecosystem is volatile under predation (producers crash
|
||||
// fast), so the original tight bands (prod 8-16, graz 3-7) could not hold for 2 turns.
|
||||
// TUNING: ranges widened. Producers crash fast under predation (low floor) but OVERGROW when
|
||||
// an inherited Dormancy makes them inedible (high ceiling), so the band is wide. The
|
||||
// verified win completes within 2 turns before either extreme is reached.
|
||||
return assayOk && tp >= 4 && tp <= 32 && tg >= 1 && tg <= 11 && totalPhage(state) <= 5 && totalToxin(state) <= 8;
|
||||
};
|
||||
base.win = ({ resolvedTurn, consecutive }) => consecutive >= 2 && resolvedTurn <= 12;
|
||||
}
|
||||
return base;
|
||||
});
|
||||
|
||||
export function getScenario(id: string): Scenario {
|
||||
const s = SCENARIOS.find((x) => x.id === id) ?? TEST_SCENARIOS[id];
|
||||
if (!s) throw new Error(`Unknown scenario: ${id}`);
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Test-only scenarios (no fixtures unless specified) for literal behavior tests. */
|
||||
export const TEST_SCENARIOS: Record<string, Scenario> = {
|
||||
test: { id: "test", index: 0, name: "Test", subtitle: "", turnLimit: 99, starts: [], fixtures: [], sustained: () => false, win: () => false, teaches: "" },
|
||||
};
|
||||
|
||||
/** Build a state for tests: custom tile chambers, lineage unlocks, fixtures (via a test scenario id). */
|
||||
export function buildTestState(
|
||||
opts: {
|
||||
tiles?: { ring: RingId; index: number; chamber: Partial<Chamber> }[];
|
||||
unlocked?: Record<LineageId, PressureId[]>;
|
||||
environmentActive?: PressureId[];
|
||||
scenarioId?: string;
|
||||
fixtures?: ScenarioFixture[];
|
||||
turnLimit?: number;
|
||||
win?: (ctx: import("./types.ts").ScenarioWinCtx) => boolean;
|
||||
sustained?: (state: GameState, ctx: import("./types.ts").ScenarioWinCtx) => boolean;
|
||||
} = {},
|
||||
): GameState {
|
||||
const sid = opts.scenarioId ?? "test";
|
||||
TEST_SCENARIOS[sid] = {
|
||||
id: sid,
|
||||
index: 0,
|
||||
name: "Test",
|
||||
subtitle: "",
|
||||
turnLimit: opts.turnLimit ?? 99,
|
||||
starts: [],
|
||||
fixtures: opts.fixtures ?? [],
|
||||
sustained: opts.sustained ?? (() => false),
|
||||
win: opts.win ?? (() => false),
|
||||
teaches: "",
|
||||
};
|
||||
const scenario = TEST_SCENARIOS[sid];
|
||||
const st = buildInitialState(scenario, "campaign", {
|
||||
producer: opts.unlocked?.producer ?? [],
|
||||
grazer: opts.unlocked?.grazer ?? [],
|
||||
});
|
||||
st.scenarioId = sid;
|
||||
for (const t of opts.tiles ?? []) {
|
||||
st.rings[t.ring].tiles[t.index] = { ...st.rings[t.ring].tiles[t.index], ...t.chamber };
|
||||
}
|
||||
if (opts.environmentActive) for (const p of opts.environmentActive) st.environmentActive[p] = true;
|
||||
return st;
|
||||
}
|
||||
|
||||
/** Fixtures indexed by tile for a scenario. */
|
||||
export function fixturesByTile(scenario: Scenario): Map<string, { kind: string; label?: string }[]> {
|
||||
const m = new Map<string, { kind: string; label?: string }[]>();
|
||||
for (const f of scenario.fixtures) {
|
||||
const key = `${f.ring}:${f.index}`;
|
||||
if (!m.has(key)) m.set(key, []);
|
||||
m.get(key)!.push({ kind: f.kind, label: f.label });
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
export { parseLabel };
|
||||
export { totalProducer, totalGrazer, totalPhage, totalToxin, occupiedTiles };
|
||||
@@ -0,0 +1,127 @@
|
||||
// Bounded deterministic solver (SPEC §9, Gate 4). Pure search, no randomness.
|
||||
import type { GameState, LineageId, Mode, PressureId, RotationAction, Scenario } from "./types.ts";
|
||||
import { nextState } from "./transition.ts";
|
||||
import { buildInitialState } from "./scenarios.ts";
|
||||
import { canonical } from "./core.ts";
|
||||
|
||||
/** Collision-free canonical position key. Action history is excluded because it does not affect future transitions. */
|
||||
export function hashState(state: GameState): string {
|
||||
const { actionLog: _actionLog, ...position } = state;
|
||||
return canonical(position);
|
||||
}
|
||||
|
||||
const ACTIONS: RotationAction[] = [
|
||||
{ ring: "inner", dir: "cw" },
|
||||
{ ring: "inner", dir: "ccw" },
|
||||
{ ring: "middle", dir: "cw" },
|
||||
{ ring: "middle", dir: "ccw" },
|
||||
{ ring: "outer", dir: "cw" },
|
||||
{ ring: "outer", dir: "ccw" },
|
||||
];
|
||||
|
||||
export type Inherited = Record<LineageId, PressureId[]>;
|
||||
|
||||
/** DFS for a winning action sequence within the scenario turn limit. Returns null if none
|
||||
* found within the node/time budget. */
|
||||
export function solveWin(
|
||||
scenario: Scenario,
|
||||
inherited: Inherited = { producer: [], grazer: [] },
|
||||
opts: { nodeBudget?: number; timeMs?: number } = {},
|
||||
): RotationAction[] | null {
|
||||
const start = buildInitialState(scenario, "campaign", inherited);
|
||||
const visited = new Set<string>();
|
||||
const path: RotationAction[] = [];
|
||||
let nodes = 0;
|
||||
const nodeBudget = opts.nodeBudget ?? 3_000_000;
|
||||
let timedOut = false;
|
||||
|
||||
function dfs(state: GameState): RotationAction[] | null {
|
||||
if (state.outcome !== "playing") return null;
|
||||
nodes++;
|
||||
if (nodes > nodeBudget) { timedOut = true; return null; }
|
||||
const pk = hashState(state);
|
||||
if (visited.has(pk)) return null;
|
||||
visited.add(pk);
|
||||
for (const a of ACTIONS) {
|
||||
path.push(a);
|
||||
const nx = nextState(state, a);
|
||||
if (nx.outcome === "won") return [...path];
|
||||
if (nx.outcome === "playing") {
|
||||
const r = dfs(nx);
|
||||
if (r) return r;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const result = dfs(start);
|
||||
lastWinTimedOut = timedOut;
|
||||
return result;
|
||||
}
|
||||
|
||||
/** True if the most recent solveWin hit its time/node budget (inconclusive), false if it exhausted the space. */
|
||||
export let lastWinTimedOut = false;
|
||||
|
||||
/** DFS for any losing terminal (collapse or expiry). */
|
||||
export function solveLoss(scenario: Scenario, inherited: Inherited = { producer: [], grazer: [] }): RotationAction[] | null {
|
||||
const start = buildInitialState(scenario, "campaign", inherited);
|
||||
const visited = new Set<string>();
|
||||
const path: RotationAction[] = [];
|
||||
let nodes = 0;
|
||||
const nodeBudget = 2_000_000;
|
||||
|
||||
function dfs(state: GameState): RotationAction[] | null {
|
||||
nodes++;
|
||||
if (nodes > nodeBudget) return null;
|
||||
const pk = hashState(state);
|
||||
if (visited.has(pk)) return null;
|
||||
visited.add(pk);
|
||||
for (const a of ACTIONS) {
|
||||
path.push(a);
|
||||
const nx = nextState(state, a);
|
||||
if (nx.outcome === "collapsed" || nx.outcome === "expired") return [...path];
|
||||
if (nx.outcome === "playing") {
|
||||
const r = dfs(nx);
|
||||
if (r) return r;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return dfs(start);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enumerate a conservative superset of campaign inheritance sets at scenario entry.
|
||||
* After N prior scenarios the campaign can preserve at most N distinct trait slots.
|
||||
* Proving every subset of the eight lineage/pressure slots up to that size is stronger
|
||||
* than proving only the route-dependent reachable subset.
|
||||
*/
|
||||
export function reachableInheritanceAt(scenarioIndex: number): Inherited[] {
|
||||
const maxTraits = Math.max(0, Math.min(4, scenarioIndex - 1));
|
||||
const slots = (["producer", "grazer"] as LineageId[]).flatMap((lineage) =>
|
||||
(["heat", "hunger", "toxin", "immunity"] as PressureId[]).map((pressure) => ({ lineage, pressure })),
|
||||
);
|
||||
const out: Inherited[] = [];
|
||||
function visit(index: number, chosen: typeof slots): void {
|
||||
const inherited: Inherited = { producer: [], grazer: [] };
|
||||
for (const { lineage, pressure } of chosen) inherited[lineage].push(pressure);
|
||||
out.push(inherited);
|
||||
if (chosen.length === maxTraits) return;
|
||||
for (let i = index; i < slots.length; i++) visit(i + 1, [...chosen, slots[i]]);
|
||||
}
|
||||
visit(0, []);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function inheritanceKey(inherited: Inherited): string {
|
||||
return `P:${inherited.producer.join(",")}|G:${inherited.grazer.join(",")}`;
|
||||
}
|
||||
|
||||
export function replay(scenario: Scenario, inherited: Inherited, actions: RotationAction[], mode: Mode = "campaign"): GameState {
|
||||
let state = buildInitialState(scenario, mode, inherited);
|
||||
for (const action of actions) state = nextState(state, action);
|
||||
return state;
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
// The single pure transition: nextState(state, action). SPEC §7 pipeline.
|
||||
// Preview and commit both call resolve() on a clone. Input is never mutated.
|
||||
import type {
|
||||
Chamber,
|
||||
FixtureKind,
|
||||
GameState,
|
||||
LineageId,
|
||||
PressureId,
|
||||
RingId,
|
||||
RotationAction,
|
||||
Scenario,
|
||||
} from "./types.ts";
|
||||
import { CAP, clamp, cloneState, gateIndex, gateOf, nextIndex, rotatePayloads } from "./core.ts";
|
||||
import { getScenario } from "./scenarios.ts";
|
||||
|
||||
export type GameEvent =
|
||||
| { phase: "rotate"; ring: RingId; dir: string }
|
||||
| { phase: "flow"; ring: RingId; index: number; field: "nutrient" | "toxin"; delta: number; tangential: number; radial: number }
|
||||
| { phase: "growth"; ring: RingId; index: number; gained: number; suppressed: boolean }
|
||||
| { phase: "feed"; ring: RingId; index: number; predator: "grazer" | "phage"; preyRemoved: number; gained: boolean; suppressed?: boolean; phageStarve?: boolean }
|
||||
| { phase: "migrate"; from: string; to: string; species: "producer" | "grazer" | "phage" }
|
||||
| { phase: "overflow"; ring: RingId; index: number; field: keyof Chamber; amount: number }
|
||||
| { phase: "evolution"; lineage: LineageId; pressure: PressureId; unlocked: boolean }
|
||||
| { phase: "env"; pressure: PressureId; active: boolean }
|
||||
| { phase: "fixture"; ring: RingId; index: number; kind: FixtureKind; field: string; delta: number }
|
||||
| { phase: "fixtureGlobal"; field: "heat"; delta: number }
|
||||
| { phase: "immuneSelect"; ring: RingId; index: number; lineage: LineageId; damage: number; retarget: boolean }
|
||||
| { phase: "pressureInc"; lineage: LineageId; pressure: PressureId; to: number }
|
||||
| { phase: "consequence"; ring: RingId; index: number; lineage: LineageId; pressure: PressureId; kind: "loss" | "prevented" | "payNutrient" | "payPop"; amount: number }
|
||||
| { phase: "spillover"; ring: RingId; index: number; pressure: PressureId; field: "heat" | "toxin"; reduced: number }
|
||||
| { phase: "adaptation"; ring: RingId; index: number; lineage: LineageId; pressure: PressureId; effect: "cost" | "spillover" }
|
||||
| { phase: "outcome"; outcome: GameState["outcome"]; turn: number };
|
||||
|
||||
export type ResolveResult = { state: GameState; events: GameEvent[] };
|
||||
|
||||
const RING_ORDER: RingId[] = ["outer", "middle", "inner"];
|
||||
const NOPE: GameEvent[] = []; // sentinel reused when events are not collected
|
||||
|
||||
function foodForTile(tile: Chamber, species: "producer" | "grazer" | "phage"): number {
|
||||
if (species === "producer") return tile.nutrient;
|
||||
if (species === "grazer") return tile.producer;
|
||||
return tile.grazer;
|
||||
}
|
||||
|
||||
function fixturesFor(scenario: Scenario): (ring: RingId, index: number) => FixtureKind[] {
|
||||
const m = new Map<string, FixtureKind[]>();
|
||||
for (const f of scenario.fixtures) {
|
||||
const key = `${f.ring}:${f.index}`;
|
||||
if (!m.has(key)) m.set(key, []);
|
||||
m.get(key)!.push(f.kind);
|
||||
}
|
||||
return (ring: RingId, index: number) => m.get(`${ring}:${index}`) ?? EMPTY;
|
||||
}
|
||||
const EMPTY: FixtureKind[] = [];
|
||||
|
||||
export function resolve(state: GameState, action: RotationAction, collectEvents = true): ResolveResult {
|
||||
if (state.outcome !== "playing") return { state: cloneState(state), events: [] };
|
||||
const scenario = getScenario(state.scenarioId);
|
||||
const w = cloneState(state);
|
||||
const events: GameEvent[] = collectEvents ? [] : NOPE;
|
||||
const push = (e: GameEvent) => { if (collectEvents) events.push(e); };
|
||||
const fixturesAt = fixturesFor(scenario);
|
||||
|
||||
// ---- Phase 1: Rotate ----
|
||||
w.rings[action.ring].tiles = rotatePayloads(w.rings[action.ring].tiles, action.dir);
|
||||
w.rings[action.ring].direction = action.dir;
|
||||
push({ phase: "rotate", ring: action.ring, dir: action.dir });
|
||||
|
||||
// ---- Phase 2: Channel flow (nutrient + toxin) ----
|
||||
for (const field of ["nutrient", "toxin"] as const) {
|
||||
const snap: Record<RingId, number[]> = {
|
||||
inner: w.rings.inner.tiles.map((t) => t[field]),
|
||||
middle: w.rings.middle.tiles.map((t) => t[field]),
|
||||
outer: w.rings.outer.tiles.map((t) => t[field]),
|
||||
};
|
||||
const sent: Record<RingId, number[]> = { inner: [0, 0, 0, 0, 0, 0], middle: arr(12), outer: arr(18) };
|
||||
const recv: Record<RingId, number[]> = { inner: [0, 0, 0, 0, 0, 0], middle: arr(12), outer: arr(18) };
|
||||
const sentTan: Record<RingId, number[]> = { inner: [0, 0, 0, 0, 0, 0], middle: arr(12), outer: arr(18) };
|
||||
// tangential
|
||||
for (const r of RING_ORDER) {
|
||||
const size = snap[r].length;
|
||||
const dir = w.rings[r].direction;
|
||||
for (let i = 0; i < size; i++) {
|
||||
if (snap[r][i] >= 1) {
|
||||
const j = nextIndex(i, size, dir);
|
||||
sent[r][i] += 1;
|
||||
sentTan[r][i] += 1;
|
||||
recv[r][j] += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// radial inward through gates
|
||||
for (let g = 0; g < 6; g++) {
|
||||
const oi = gateIndex("outer", g);
|
||||
const mi = gateIndex("middle", g);
|
||||
const ii = gateIndex("inner", g);
|
||||
if (snap.outer[oi] >= 1) {
|
||||
sent.outer[oi] += 1;
|
||||
recv.middle[mi] += 1;
|
||||
}
|
||||
if (snap.middle[mi] >= 1) {
|
||||
sent.middle[mi] += 1;
|
||||
recv.inner[ii] += 1;
|
||||
}
|
||||
}
|
||||
// commit
|
||||
for (const r of RING_ORDER) {
|
||||
for (let i = 0; i < snap[r].length; i++) {
|
||||
const start = snap[r][i];
|
||||
const raw = start - sent[r][i] + recv[r][i];
|
||||
const nv = clamp(raw, 0, CAP);
|
||||
w.rings[r].tiles[i][field] = nv;
|
||||
if (sent[r][i] || recv[r][i]) {
|
||||
push({ phase: "flow", ring: r, index: i, field, delta: nv - start, tangential: sentTan[r][i], radial: sent[r][i] - sentTan[r][i] });
|
||||
}
|
||||
if (raw > CAP) push({ phase: "overflow", ring: r, index: i, field, amount: raw - CAP });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Phase 3: Producer growth ----
|
||||
for (const r of RING_ORDER) {
|
||||
for (let i = 0; i < w.rings[r].tiles.length; i++) {
|
||||
const t = w.rings[r].tiles[i];
|
||||
if (t.producer >= 1 && t.nutrient >= 1) {
|
||||
const heatSuppress = w.lineage.producer.unlocked.heat && t.heat >= 2;
|
||||
t.nutrient -= 1;
|
||||
const before = t.producer;
|
||||
if (!heatSuppress) t.producer = clamp(t.producer + 1, 0, CAP);
|
||||
push({ phase: "growth", ring: r, index: i, gained: t.producer - before, suppressed: heatSuppress });
|
||||
if (!heatSuppress && before === CAP) push({ phase: "overflow", ring: r, index: i, field: "producer", amount: 1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Phase 4: Biological interactions ----
|
||||
// Grazer subphase
|
||||
{
|
||||
const snapProd = snapField(w, "producer");
|
||||
const snapGrazer = snapField(w, "grazer");
|
||||
for (const r of RING_ORDER) {
|
||||
for (let i = 0; i < w.rings[r].tiles.length; i++) {
|
||||
const t = w.rings[r].tiles[i];
|
||||
if (snapGrazer[r][i] >= 1) {
|
||||
const dormantProd = w.lineage.producer.unlocked.hunger && t.nutrient === 0;
|
||||
const edible = snapProd[r][i] >= 1 && !dormantProd;
|
||||
if (snapProd[r][i] >= 1 && dormantProd) push({ phase: "adaptation", ring: r, index: i, lineage: "producer", pressure: "hunger", effect: "spillover" });
|
||||
const heatSuppressFeed = w.lineage.grazer.unlocked.heat && t.heat >= 2;
|
||||
if (edible) {
|
||||
const onImmune = fixturesAt(r, i).includes("immuneNode");
|
||||
const cloaked = w.lineage.producer.unlocked.immunity && onImmune;
|
||||
const remove = Math.min(cloaked ? 2 : 1, t.producer);
|
||||
t.producer = clamp(t.producer - remove, 0, CAP);
|
||||
const before = t.grazer;
|
||||
if (!heatSuppressFeed) t.grazer = clamp(t.grazer + 1, 0, CAP);
|
||||
push({ phase: "feed", ring: r, index: i, predator: "grazer", preyRemoved: remove, gained: t.grazer > before, suppressed: heatSuppressFeed });
|
||||
if (!heatSuppressFeed && before === CAP) push({ phase: "overflow", ring: r, index: i, field: "grazer", amount: 1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Phage subphase
|
||||
{
|
||||
const snapGrazer = snapField(w, "grazer");
|
||||
const snapPhage = snapField(w, "phage");
|
||||
for (const r of RING_ORDER) {
|
||||
for (let i = 0; i < w.rings[r].tiles.length; i++) {
|
||||
const t = w.rings[r].tiles[i];
|
||||
if (snapPhage[r][i] >= 1) {
|
||||
const dormantGraz = w.lineage.grazer.unlocked.hunger && t.producer === 0;
|
||||
const edible = snapGrazer[r][i] >= 1 && !dormantGraz;
|
||||
if (snapGrazer[r][i] >= 1 && dormantGraz) push({ phase: "adaptation", ring: r, index: i, lineage: "grazer", pressure: "hunger", effect: "spillover" });
|
||||
if (edible) {
|
||||
const onImmune = fixturesAt(r, i).includes("immuneNode");
|
||||
const cloaked = w.lineage.grazer.unlocked.immunity && onImmune;
|
||||
const remove = Math.min(cloaked ? 2 : 1, t.grazer);
|
||||
t.grazer = clamp(t.grazer - remove, 0, CAP);
|
||||
const before = t.phage;
|
||||
t.phage = clamp(t.phage + 1, 0, CAP);
|
||||
push({ phase: "feed", ring: r, index: i, predator: "phage", preyRemoved: remove, gained: t.phage > before });
|
||||
if (before === CAP) push({ phase: "overflow", ring: r, index: i, field: "phage", amount: 1 });
|
||||
} else {
|
||||
t.phage = clamp(t.phage - 1, 0, CAP);
|
||||
push({ phase: "feed", ring: r, index: i, predator: "phage", preyRemoved: 0, gained: false, phageStarve: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Phase 5: Migration ----
|
||||
for (const species of ["producer", "grazer", "phage"] as const) {
|
||||
const snapSp = snapField(w, species);
|
||||
const movers: { from: RingId; fi: number; toRing: RingId; toIndex: number }[] = [];
|
||||
for (const r of RING_ORDER) {
|
||||
const size = w.rings[r].tiles.length;
|
||||
const dir = w.rings[r].direction;
|
||||
for (let i = 0; i < size; i++) {
|
||||
if (snapSp[r][i] < 2) continue;
|
||||
const lin = species === "producer" ? w.lineage.producer : species === "grazer" ? w.lineage.grazer : null;
|
||||
const food = foodForTile(w.rings[r].tiles[i], species);
|
||||
const dormant = lin ? lin.unlocked.hunger && food === 0 : false;
|
||||
// candidate neighbors: tangential (one step in ring direction), then radial through a
|
||||
// gate to the ADJACENT ring only (SPEC §7.5: outer<->middle, middle<->inner; never outer<->inner).
|
||||
const cands: { ring: RingId; index: number }[] = [];
|
||||
cands.push({ ring: r, index: nextIndex(i, size, dir) });
|
||||
const g = gateOf(r, i);
|
||||
if (g >= 0) {
|
||||
const radialRings: RingId[] = r === "inner" ? ["middle"] : r === "outer" ? ["middle"] : ["inner", "outer"];
|
||||
for (const rr of radialRings) cands.push({ ring: rr, index: gateIndex(rr, g) });
|
||||
}
|
||||
if (dormant) {
|
||||
if (cands.some((candidate) => foodForTile(w.rings[candidate.ring].tiles[candidate.index], species) > food)) {
|
||||
push({ phase: "adaptation", ring: r, index: i, lineage: species as LineageId, pressure: "hunger", effect: "cost" });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let best: { ring: RingId; index: number; food: number } | null = null;
|
||||
for (const c of cands) {
|
||||
const cf = foodForTile(w.rings[c.ring].tiles[c.index], species);
|
||||
if (cf > food) {
|
||||
if (!best || cf > best.food) best = { ring: c.ring, index: c.index, food: cf };
|
||||
}
|
||||
}
|
||||
if (best) movers.push({ from: r, fi: i, toRing: best.ring, toIndex: best.index });
|
||||
}
|
||||
}
|
||||
// commit aggregate SIMULTANEOUSLY per tile: clamp(start - sent + sum(received), 0, CAP) (SPEC §7.5)
|
||||
const delta: Record<string, number> = {};
|
||||
const keyOf = (ring: RingId, i: number) => `${ring}:${i}`;
|
||||
for (const m of movers) {
|
||||
delta[keyOf(m.from, m.fi)] = (delta[keyOf(m.from, m.fi)] ?? 0) - 1;
|
||||
delta[keyOf(m.toRing, m.toIndex)] = (delta[keyOf(m.toRing, m.toIndex)] ?? 0) + 1;
|
||||
push({ phase: "migrate", from: keyOf(m.from, m.fi), to: keyOf(m.toRing, m.toIndex), species });
|
||||
}
|
||||
for (const [k, d] of Object.entries(delta)) {
|
||||
const [ring, iStr] = k.split(":");
|
||||
const r = ring as RingId;
|
||||
const i = +iStr;
|
||||
const t = w.rings[r].tiles[i];
|
||||
const raw = t[species] + d;
|
||||
t[species] = clamp(raw, 0, CAP);
|
||||
if (raw > CAP) push({ phase: "overflow", ring: r, index: i, field: species, amount: raw - CAP });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Phase 6: Evolution & environmental response activation ----
|
||||
for (const lin of ["producer", "grazer"] as LineageId[]) {
|
||||
for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) {
|
||||
if (w.lineage[lin].pressure[p] >= 3 && !w.lineage[lin].unlocked[p]) {
|
||||
w.lineage[lin].unlocked[p] = true;
|
||||
push({ phase: "evolution", lineage: lin, pressure: p, unlocked: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) {
|
||||
const active = w.lineage.producer.pressure[p] >= 3 || w.lineage.grazer.pressure[p] >= 3;
|
||||
if (active && !w.environmentActive[p]) {
|
||||
w.environmentActive[p] = true;
|
||||
push({ phase: "env", pressure: p, active: true });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Phase 7: Fixtures, exposure, pressure consequences ----
|
||||
// (a) fixtures in SPEC order: nutrient, heat, cooldown, toxin, drains.
|
||||
for (const r of RING_ORDER) for (let i = 0; i < w.rings[r].tiles.length; i++) {
|
||||
if (!fixturesAt(r, i).includes("nutrientInlet")) continue;
|
||||
const tile = w.rings[r].tiles[i];
|
||||
const add = w.environmentActive.hunger ? 1 : 2;
|
||||
const before = tile.nutrient;
|
||||
tile.nutrient = clamp(before + add, 0, CAP);
|
||||
if (tile.nutrient !== before) push({ phase: "fixture", ring: r, index: i, kind: "nutrientInlet", field: "nutrient", delta: tile.nutrient - before });
|
||||
if (before + add > CAP) push({ phase: "overflow", ring: r, index: i, field: "nutrient", amount: before + add - CAP });
|
||||
}
|
||||
for (const r of RING_ORDER) for (let i = 0; i < w.rings[r].tiles.length; i++) {
|
||||
if (!fixturesAt(r, i).includes("heatSource")) continue;
|
||||
const tile = w.rings[r].tiles[i];
|
||||
const add = w.environmentActive.heat ? 3 : 2;
|
||||
const before = tile.heat;
|
||||
tile.heat = clamp(before + add, 0, CAP);
|
||||
if (tile.heat !== before) push({ phase: "fixture", ring: r, index: i, kind: "heatSource", field: "heat", delta: tile.heat - before });
|
||||
if (before + add > CAP) push({ phase: "overflow", ring: r, index: i, field: "heat", amount: before + add - CAP });
|
||||
}
|
||||
for (const r of RING_ORDER) for (let i = 0; i < w.rings[r].tiles.length; i++) {
|
||||
const tile = w.rings[r].tiles[i];
|
||||
if (tile.heat > 0) {
|
||||
tile.heat -= 1;
|
||||
push({ phase: "fixtureGlobal", field: "heat", delta: -1 });
|
||||
}
|
||||
}
|
||||
for (const r of RING_ORDER) for (let i = 0; i < w.rings[r].tiles.length; i++) {
|
||||
if (!fixturesAt(r, i).includes("toxinInlet")) continue;
|
||||
const tile = w.rings[r].tiles[i];
|
||||
const add = w.environmentActive.toxin ? 3 : 2;
|
||||
const before = tile.toxin;
|
||||
tile.toxin = clamp(before + add, 0, CAP);
|
||||
if (tile.toxin !== before) push({ phase: "fixture", ring: r, index: i, kind: "toxinInlet", field: "toxin", delta: tile.toxin - before });
|
||||
if (before + add > CAP) push({ phase: "overflow", ring: r, index: i, field: "toxin", amount: before + add - CAP });
|
||||
}
|
||||
for (const r of RING_ORDER) for (let i = 0; i < w.rings[r].tiles.length; i++) {
|
||||
if (!fixturesAt(r, i).includes("drain")) continue;
|
||||
const tile = w.rings[r].tiles[i];
|
||||
const before = tile.toxin;
|
||||
tile.toxin = clamp(before - 2, 0, CAP);
|
||||
if (tile.toxin !== before) push({ phase: "fixture", ring: r, index: i, kind: "drain", field: "toxin", delta: tile.toxin - before });
|
||||
}
|
||||
|
||||
// (b) immunity algorithm: select target per immune node
|
||||
const immuneSchedule: { ring: RingId; index: number; lineage: LineageId; damage: number }[] = [];
|
||||
for (const r of RING_ORDER) {
|
||||
for (let i = 0; i < w.rings[r].tiles.length; i++) {
|
||||
if (!fixturesAt(r, i).includes("immuneNode")) continue;
|
||||
const t = w.rings[r].tiles[i];
|
||||
const all: { lin: LineageId; pop: number; cloaked: boolean }[] = [];
|
||||
if (t.producer >= 1) all.push({ lin: "producer", pop: t.producer, cloaked: w.lineage.producer.unlocked.immunity });
|
||||
if (t.grazer >= 1) all.push({ lin: "grazer", pop: t.grazer, cloaked: w.lineage.grazer.unlocked.immunity });
|
||||
const rank = <T extends { lin: LineageId; pop: number }>(a: T, b: T) => (b.pop - a.pop) || (a.lin === "producer" ? -1 : 1);
|
||||
all.sort(rank);
|
||||
const candidates = all.filter((candidate) => !candidate.cloaked).sort(rank);
|
||||
if (candidates.length === 0) continue;
|
||||
const chosen = candidates[0].lin;
|
||||
const damage = w.environmentActive.immunity ? 3 : 2;
|
||||
immuneSchedule.push({ ring: r, index: i, lineage: chosen, damage });
|
||||
push({ phase: "immuneSelect", ring: r, index: i, lineage: chosen, damage, retarget: all[0].cloaked && all[0].lin !== chosen });
|
||||
}
|
||||
}
|
||||
|
||||
// (c) snapshot qualification + occupied
|
||||
const qualify: Record<LineageId, Record<PressureId, Set<string>>> = {
|
||||
producer: { heat: new Set(), hunger: new Set(), toxin: new Set(), immunity: new Set() },
|
||||
grazer: { heat: new Set(), hunger: new Set(), toxin: new Set(), immunity: new Set() },
|
||||
};
|
||||
for (const r of RING_ORDER) {
|
||||
for (let i = 0; i < w.rings[r].tiles.length; i++) {
|
||||
const t = w.rings[r].tiles[i];
|
||||
const key = `${r}:${i}`;
|
||||
if (t.producer >= 1) {
|
||||
if (t.heat >= 2) qualify.producer.heat.add(key);
|
||||
if (t.nutrient === 0) qualify.producer.hunger.add(key);
|
||||
if (t.toxin >= 2) qualify.producer.toxin.add(key);
|
||||
}
|
||||
if (t.grazer >= 1) {
|
||||
if (t.heat >= 2) qualify.grazer.heat.add(key);
|
||||
if (t.producer === 0) qualify.grazer.hunger.add(key);
|
||||
if (t.toxin >= 2) qualify.grazer.toxin.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const s of immuneSchedule) {
|
||||
qualify[s.lineage].immunity.add(`${s.ring}:${s.index}`);
|
||||
}
|
||||
|
||||
// (d) increment pressure tracks
|
||||
for (const lin of ["producer", "grazer"] as LineageId[]) {
|
||||
for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) {
|
||||
if (qualify[lin][p].size >= 1) {
|
||||
const before = w.lineage[lin].pressure[p];
|
||||
w.lineage[lin].pressure[p] = Math.min(3, before + 1);
|
||||
if (w.lineage[lin].pressure[p] !== before) {
|
||||
push({ phase: "pressureInc", lineage: lin, pressure: p, to: w.lineage[lin].pressure[p] });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// (e) consequences: heat, hunger, toxin, immunity
|
||||
// HEAT (producer then grazer, then spillover)
|
||||
for (const lin of ["producer", "grazer"] as LineageId[]) {
|
||||
for (const key of qualify[lin].heat) {
|
||||
const [r, iStr] = key.split(":");
|
||||
const i = +iStr;
|
||||
const t = w.rings[r as RingId].tiles[i];
|
||||
const popField = lin === "producer" ? "producer" : "grazer";
|
||||
if (t[popField] <= 0) continue;
|
||||
if (w.lineage[lin].unlocked.heat) {
|
||||
push({ phase: "consequence", ring: r as RingId, index: i, lineage: lin, pressure: "heat", kind: "prevented", amount: 0 });
|
||||
} else {
|
||||
const before = t[popField];
|
||||
t[popField] = clamp(t[popField] - 2, 0, CAP);
|
||||
push({ phase: "consequence", ring: r as RingId, index: i, lineage: lin, pressure: "heat", kind: "loss", amount: before - t[popField] });
|
||||
}
|
||||
}
|
||||
}
|
||||
// heat spillover: reduce local heat by 1 per adapted surviving lineage, max 2
|
||||
for (const key of unionKeys([qualify.producer.heat, qualify.grazer.heat])) {
|
||||
const [r, iStr] = key.split(":");
|
||||
const r2 = r as RingId;
|
||||
const i = +iStr;
|
||||
const t = w.rings[r2].tiles[i];
|
||||
let count = 0;
|
||||
if (w.lineage.producer.unlocked.heat && t.producer > 0) count++;
|
||||
if (w.lineage.grazer.unlocked.heat && t.grazer > 0) count++;
|
||||
const reduce = Math.min(2, count);
|
||||
if (reduce > 0 && t.heat > 0) {
|
||||
const before = t.heat;
|
||||
t.heat = clamp(t.heat - reduce, 0, CAP);
|
||||
push({ phase: "spillover", ring: r2, index: i, pressure: "heat", field: "heat", reduced: before - t.heat });
|
||||
}
|
||||
}
|
||||
// HUNGER
|
||||
for (const lin of ["producer", "grazer"] as LineageId[]) {
|
||||
for (const key of qualify[lin].hunger) {
|
||||
const [r, iStr] = key.split(":");
|
||||
const i = +iStr;
|
||||
const t = w.rings[r as RingId].tiles[i];
|
||||
const popField = lin === "producer" ? "producer" : "grazer";
|
||||
if (t[popField] <= 0) continue;
|
||||
if (w.lineage[lin].unlocked.hunger) {
|
||||
push({ phase: "consequence", ring: r as RingId, index: i, lineage: lin, pressure: "hunger", kind: "prevented", amount: 0 });
|
||||
} else {
|
||||
const before = t[popField];
|
||||
t[popField] = clamp(t[popField] - 1, 0, CAP);
|
||||
push({ phase: "consequence", ring: r as RingId, index: i, lineage: lin, pressure: "hunger", kind: "loss", amount: before - t[popField] });
|
||||
}
|
||||
}
|
||||
}
|
||||
// TOXIN: carrier payments producer then grazer per tile, then spillover
|
||||
for (const key of unionKeys([qualify.producer.toxin, qualify.grazer.toxin])) {
|
||||
const [r, iStr] = key.split(":");
|
||||
const r2 = r as RingId;
|
||||
const i = +iStr;
|
||||
const t = w.rings[r2].tiles[i];
|
||||
for (const lin of ["producer", "grazer"] as LineageId[]) {
|
||||
const popField = lin === "producer" ? "producer" : "grazer";
|
||||
if (t[popField] <= 0) continue;
|
||||
if (!qualify[lin].toxin.has(`${r2}:${i}`)) continue;
|
||||
if (w.lineage[lin].unlocked.toxin) {
|
||||
// Efflux: pay 1 nutrient, else lose 1 pop
|
||||
if (t.nutrient >= 1) {
|
||||
t.nutrient -= 1;
|
||||
push({ phase: "consequence", ring: r2, index: i, lineage: lin, pressure: "toxin", kind: "payNutrient", amount: 1 });
|
||||
} else {
|
||||
const before = t[popField];
|
||||
t[popField] = clamp(t[popField] - 1, 0, CAP);
|
||||
push({ phase: "consequence", ring: r2, index: i, lineage: lin, pressure: "toxin", kind: "payPop", amount: before - t[popField] });
|
||||
}
|
||||
} else {
|
||||
const before = t[popField];
|
||||
t[popField] = clamp(t[popField] - 1, 0, CAP);
|
||||
push({ phase: "consequence", ring: r2, index: i, lineage: lin, pressure: "toxin", kind: "loss", amount: before - t[popField] });
|
||||
}
|
||||
}
|
||||
// toxin spillover: reduce local toxin by 1 per adapted surviving lineage, max 2
|
||||
let count = 0;
|
||||
if (w.lineage.producer.unlocked.toxin && t.producer > 0) count++;
|
||||
if (w.lineage.grazer.unlocked.toxin && t.grazer > 0) count++;
|
||||
const reduce = Math.min(2, count);
|
||||
if (reduce > 0 && t.toxin > 0) {
|
||||
const before = t.toxin;
|
||||
t.toxin = clamp(t.toxin - reduce, 0, CAP);
|
||||
push({ phase: "spillover", ring: r2, index: i, pressure: "toxin", field: "toxin", reduced: before - t.toxin });
|
||||
}
|
||||
}
|
||||
// IMMUNITY: apply scheduled damage if target still has population
|
||||
for (const s of immuneSchedule) {
|
||||
const t = w.rings[s.ring].tiles[s.index];
|
||||
const popField = s.lineage === "producer" ? "producer" : "grazer";
|
||||
if (t[popField] <= 0) continue;
|
||||
const before = t[popField];
|
||||
t[popField] = clamp(t[popField] - s.damage, 0, CAP);
|
||||
push({ phase: "consequence", ring: s.ring, index: s.index, lineage: s.lineage, pressure: "immunity", kind: "loss", amount: before - t[popField] });
|
||||
}
|
||||
|
||||
// ---- Phase 8: Outcome ----
|
||||
const resolvedTurn = state.turn + 1;
|
||||
const sustained = scenario.sustained(w, { state: w, resolvedTurn, consecutive: 0, fixturesByTile: () => [] });
|
||||
const consecutive = sustained ? state.consecutiveObjectiveTurns + 1 : 0;
|
||||
w.consecutiveObjectiveTurns = consecutive;
|
||||
w.turn = resolvedTurn;
|
||||
w.actionLog = [...w.actionLog, action];
|
||||
|
||||
let total = 0;
|
||||
for (const r of RING_ORDER) for (const t of w.rings[r].tiles) total += t.producer + t.grazer;
|
||||
if (total === 0) {
|
||||
w.outcome = "collapsed";
|
||||
} else if (scenario.win({ state: w, resolvedTurn, consecutive, fixturesByTile: () => [] })) {
|
||||
w.outcome = "won";
|
||||
} else if (resolvedTurn >= scenario.turnLimit) {
|
||||
w.outcome = "expired";
|
||||
} else {
|
||||
w.outcome = "playing";
|
||||
}
|
||||
push({ phase: "outcome", outcome: w.outcome, turn: resolvedTurn });
|
||||
|
||||
return { state: w, events: collectEvents ? events : [] };
|
||||
}
|
||||
|
||||
export function nextState(state: GameState, action: RotationAction): GameState {
|
||||
return resolve(state, action, false).state;
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
function arr(n: number): number[] {
|
||||
return new Array(n).fill(0);
|
||||
}
|
||||
function snapField(w: GameState, field: keyof Chamber): Record<RingId, number[]> {
|
||||
return {
|
||||
inner: w.rings.inner.tiles.map((t) => t[field]),
|
||||
middle: w.rings.middle.tiles.map((t) => t[field]),
|
||||
outer: w.rings.outer.tiles.map((t) => t[field]),
|
||||
};
|
||||
}
|
||||
function unionKeys(sets: Set<string>[]): string[] {
|
||||
const u = new Set<string>();
|
||||
for (const s of sets) for (const k of s) u.add(k);
|
||||
return [...u].sort();
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// Adaptive Loop — domain types (SPEC §5). Serializable plain data only.
|
||||
|
||||
export type RingId = "inner" | "middle" | "outer";
|
||||
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 type SpeciesId = "producer" | "grazer" | "phage";
|
||||
|
||||
/** Movable tile payload (rotates with the ring, flows in channel phase). */
|
||||
export type 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 type Ring = {
|
||||
direction: Direction;
|
||||
tiles: Chamber[]; // clockwise track order; tiles[0] at top
|
||||
};
|
||||
|
||||
export type Lineage = {
|
||||
pressure: Record<PressureId, number>; // 0..3
|
||||
unlocked: Record<PressureId, boolean>;
|
||||
};
|
||||
|
||||
export type RotationAction = { ring: RingId; dir: Direction };
|
||||
|
||||
export type GameState = {
|
||||
schemaVersion: 1;
|
||||
mode: Mode;
|
||||
scenarioId: string;
|
||||
turn: number;
|
||||
rings: Record<RingId, Ring>;
|
||||
lineage: Record<LineageId, Lineage>;
|
||||
inheritedAtStart: Record<LineageId, PressureId[]>;
|
||||
consecutiveObjectiveTurns: number;
|
||||
environmentActive: Record<PressureId, boolean>;
|
||||
outcome: Outcome;
|
||||
actionLog: RotationAction[];
|
||||
};
|
||||
|
||||
/** Fixed fixtures (SPEC §6). Static per scenario, derived from scenario data. */
|
||||
export type FixtureKind =
|
||||
| "nutrientInlet"
|
||||
| "heatSource"
|
||||
| "toxinInlet"
|
||||
| "drain"
|
||||
| "immuneNode"
|
||||
| "objective";
|
||||
|
||||
export type RingTileRef = { ring: RingId; index: number };
|
||||
|
||||
export type ScenarioStart = { ring: RingId; index: number; chamber: Partial<Chamber> };
|
||||
export type ScenarioFixture = { kind: FixtureKind; ring: RingId; index: number; label?: string };
|
||||
|
||||
export type ScenarioWinCtx = {
|
||||
state: GameState;
|
||||
resolvedTurn: number;
|
||||
consecutive: number;
|
||||
fixturesByTile: (ring: RingId, index: number) => FixtureKind[];
|
||||
};
|
||||
|
||||
export type Scenario = {
|
||||
id: string;
|
||||
index: number; // campaign order 1..5
|
||||
name: string;
|
||||
subtitle: string;
|
||||
turnLimit: number;
|
||||
starts: ScenarioStart[];
|
||||
fixtures: ScenarioFixture[];
|
||||
/** sustained predicate true => consecutiveObjectiveTurns increments; else resets. */
|
||||
sustained: (state: GameState, ctx: ScenarioWinCtx) => boolean;
|
||||
/** win check (evaluated before turn-limit expiry). */
|
||||
win: (ctx: ScenarioWinCtx) => boolean;
|
||||
/** lose-by-expiry human hint */
|
||||
teaches: string;
|
||||
};
|
||||
|
||||
export const RING_SIZES: Record<RingId, number> = { inner: 6, middle: 12, outer: 18 };
|
||||
export const RING_IDS: RingId[] = ["inner", "middle", "outer"];
|
||||
export const PRESSURES: PressureId[] = ["heat", "hunger", "toxin", "immunity"];
|
||||
export const LINEAGES: LineageId[] = ["producer", "grazer"];
|
||||
|
||||
export const TRAIT_NAME: Record<PressureId, string> = {
|
||||
heat: "Heat Shield",
|
||||
hunger: "Dormancy",
|
||||
toxin: "Efflux",
|
||||
immunity: "Cloak",
|
||||
};
|
||||
|
||||
export const SPECIES_NAME: Record<SpeciesId, string> = {
|
||||
producer: "Lumiflora",
|
||||
grazer: "Vellea",
|
||||
phage: "Phage",
|
||||
};
|
||||
|
||||
export const PRESSURE_META: Record<
|
||||
PressureId,
|
||||
{ label: string; color: string; icon: string; trait: string; response: string }
|
||||
> = {
|
||||
heat: { label: "Heat", color: "#ff8a4c", icon: "sun", trait: "Heat Shield", response: "Heat sources add 3" },
|
||||
hunger: { label: "Hunger", color: "#b388ff", icon: "crescent", trait: "Dormancy", response: "Nutrient inlets add 1" },
|
||||
toxin: { label: "Toxin", color: "#7fd66b", icon: "skull", trait: "Efflux", response: "Toxin inlets add 3" },
|
||||
immunity: { label: "Immunity", color: "#5fd0ff", icon: "shield", trait: "Cloak", response: "Immune damage 3" },
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
import { mount } from "./ui/app.ts";
|
||||
|
||||
const el = document.getElementById("app");
|
||||
if (!el) throw new Error("#app mount point missing");
|
||||
mount(el);
|
||||
@@ -0,0 +1,156 @@
|
||||
// Versioned localStorage save envelope (SPEC §11). Strict trust-boundary validation.
|
||||
import type { GameState, LineageId, Mode, PressureId, RotationAction, RingId } from "../domain/types.ts";
|
||||
import { canonical } from "../domain/core.ts";
|
||||
import { getScenario } from "../domain/scenarios.ts";
|
||||
import { replay } from "../domain/solver.ts";
|
||||
|
||||
const SAVE_KEY = "adaptive-loop-save-v1";
|
||||
const CAMPAIGN_SAVE_KEY = "adaptive-loop-campaign-v1";
|
||||
const SCHEMA = 1;
|
||||
const SCENARIOS = new Set(["s1-heat", "s2-hunger", "s3-toxin", "s4-immunity", "s5-convergence"]);
|
||||
const PRESSURES: PressureId[] = ["heat", "hunger", "toxin", "immunity"];
|
||||
const LINEAGES: LineageId[] = ["producer", "grazer"];
|
||||
const RINGS: RingId[] = ["inner", "middle", "outer"];
|
||||
|
||||
export type CampaignProgress = {
|
||||
unlocked: string[];
|
||||
inherited: Record<LineageId, PressureId[]>;
|
||||
entrySnapshot: Record<LineageId, PressureId[]>;
|
||||
victory: boolean;
|
||||
};
|
||||
|
||||
export type SaveEnvelope = {
|
||||
schemaVersion: 1;
|
||||
mode: Mode;
|
||||
scenarioId: string;
|
||||
state: GameState;
|
||||
progress: CampaignProgress;
|
||||
actionLog: RotationAction[];
|
||||
outcome: GameState["outcome"];
|
||||
savedAt: string;
|
||||
};
|
||||
|
||||
export function saveGame(env: Omit<SaveEnvelope, "savedAt">): void {
|
||||
const serialized = JSON.stringify({ ...env, savedAt: new Date().toISOString() });
|
||||
localStorage.setItem(SAVE_KEY, serialized);
|
||||
if (env.mode === "campaign") localStorage.setItem(CAMPAIGN_SAVE_KEY, serialized);
|
||||
}
|
||||
|
||||
function loadAt(key: string): { ok: true; env: SaveEnvelope } | { ok: false; reason: string } {
|
||||
const raw = localStorage.getItem(key);
|
||||
if (!raw) return { ok: false, reason: "No saved game found." };
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return { ok: false, reason: "Saved game is corrupt (invalid JSON)." };
|
||||
}
|
||||
if (!record(parsed)) return { ok: false, reason: "Saved game is empty." };
|
||||
if (parsed.schemaVersion !== SCHEMA) return { ok: false, reason: `Unsupported save version ${String(parsed.schemaVersion)}.` };
|
||||
if (!validateEnvelope(parsed)) return { ok: false, reason: "Saved game state is invalid. Start a new campaign to recover." };
|
||||
return { ok: true, env: parsed };
|
||||
}
|
||||
|
||||
export function loadGame(): ReturnType<typeof loadAt> {
|
||||
return loadAt(SAVE_KEY);
|
||||
}
|
||||
|
||||
export function loadCampaignGame(): ReturnType<typeof loadAt> {
|
||||
return loadAt(CAMPAIGN_SAVE_KEY);
|
||||
}
|
||||
|
||||
export function clearSave(): void {
|
||||
localStorage.removeItem(SAVE_KEY);
|
||||
localStorage.removeItem(CAMPAIGN_SAVE_KEY);
|
||||
}
|
||||
|
||||
export function hasSave(): boolean {
|
||||
return !!localStorage.getItem(SAVE_KEY);
|
||||
}
|
||||
|
||||
export function hasCampaignSave(): boolean {
|
||||
return !!localStorage.getItem(CAMPAIGN_SAVE_KEY);
|
||||
}
|
||||
|
||||
function record(value: unknown): value is Record<string, any> {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function integer(value: unknown, min: number, max: number): value is number {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
|
||||
}
|
||||
|
||||
function validAction(value: unknown): value is RotationAction {
|
||||
return record(value) && RINGS.includes(value.ring) && (value.dir === "cw" || value.dir === "ccw");
|
||||
}
|
||||
|
||||
function validTraits(value: unknown): value is Record<LineageId, PressureId[]> {
|
||||
if (!record(value)) return false;
|
||||
return LINEAGES.every((lineage) =>
|
||||
Array.isArray(value[lineage]) &&
|
||||
value[lineage].every((pressure: unknown) => PRESSURES.includes(pressure as PressureId)) &&
|
||||
new Set(value[lineage]).size === value[lineage].length,
|
||||
);
|
||||
}
|
||||
|
||||
function validateProgress(value: unknown): value is CampaignProgress {
|
||||
if (!record(value) || !Array.isArray(value.unlocked) || typeof value.victory !== "boolean") return false;
|
||||
if (!value.unlocked.length || value.unlocked.some((id: unknown) => typeof id !== "string" || !SCENARIOS.has(id))) return false;
|
||||
if (new Set(value.unlocked).size !== value.unlocked.length) return false;
|
||||
return validTraits(value.inherited) && validTraits(value.entrySnapshot);
|
||||
}
|
||||
|
||||
function validateEnvelope(value: Record<string, any>): value is SaveEnvelope {
|
||||
if ((value.mode !== "campaign" && value.mode !== "standalone") || !SCENARIOS.has(value.scenarioId)) return false;
|
||||
if (!validateState(value.state) || !validateProgress(value.progress)) return false;
|
||||
if (!Array.isArray(value.actionLog) || !value.actionLog.every(validAction)) return false;
|
||||
if (value.mode !== value.state.mode || value.scenarioId !== value.state.scenarioId || value.outcome !== value.state.outcome) return false;
|
||||
if (JSON.stringify(value.actionLog) !== JSON.stringify(value.state.actionLog)) return false;
|
||||
if (typeof value.savedAt !== "string" || Number.isNaN(Date.parse(value.savedAt))) return false;
|
||||
if (!value.progress.unlocked.includes(value.scenarioId)) return false;
|
||||
if (canonical(value.progress.entrySnapshot) !== canonical(value.state.inheritedAtStart)) return false;
|
||||
if (value.mode === "campaign" && canonical(value.progress.inherited) !== canonical(value.progress.entrySnapshot)) return false;
|
||||
const expectedUnlocked = [...SCENARIOS.keys()].slice(0, value.progress.unlocked.length);
|
||||
if (canonical(value.progress.unlocked) !== canonical(expectedUnlocked)) return false;
|
||||
if (value.progress.victory && (value.scenarioId !== expectedUnlocked[expectedUnlocked.length - 1] || value.state.outcome !== "won" || expectedUnlocked.length !== SCENARIOS.size)) return false;
|
||||
const scenarioIndex = [...SCENARIOS.keys()].indexOf(value.scenarioId) + 1;
|
||||
const inheritedCount = value.progress.inherited.producer.length + value.progress.inherited.grazer.length;
|
||||
if (inheritedCount > expectedUnlocked.length - 1) return false;
|
||||
if (value.mode === "campaign") {
|
||||
const allowedUnlockCount = value.state.outcome === "won" ? Math.min(scenarioIndex + 1, SCENARIOS.size) : scenarioIndex;
|
||||
if (expectedUnlocked.length !== scenarioIndex && expectedUnlocked.length !== allowedUnlockCount) return false;
|
||||
if (inheritedCount > scenarioIndex - 1) return false;
|
||||
}
|
||||
const reproduced = replay(getScenario(value.scenarioId), value.state.inheritedAtStart, value.actionLog, value.mode);
|
||||
return canonical(reproduced) === canonical(value.state);
|
||||
}
|
||||
|
||||
/** Structural and range validation of canonical domain state. */
|
||||
export function validateState(value: unknown): value is GameState {
|
||||
if (!record(value) || value.schemaVersion !== 1) return false;
|
||||
if ((value.mode !== "campaign" && value.mode !== "standalone") || !SCENARIOS.has(value.scenarioId)) return false;
|
||||
if (!integer(value.turn, 0, 100) || !integer(value.consecutiveObjectiveTurns, 0, value.turn)) return false;
|
||||
if (!["playing", "won", "collapsed", "expired"].includes(value.outcome)) return false;
|
||||
if (!Array.isArray(value.actionLog) || value.actionLog.length !== value.turn || !value.actionLog.every(validAction)) return false;
|
||||
if (!validTraits(value.inheritedAtStart) || !record(value.environmentActive)) return false;
|
||||
if (!PRESSURES.every((pressure) => typeof value.environmentActive[pressure] === "boolean")) return false;
|
||||
if (!record(value.rings)) return false;
|
||||
|
||||
const sizes: Record<RingId, number> = { inner: 6, middle: 12, outer: 18 };
|
||||
for (const ring of RINGS) {
|
||||
const data = value.rings[ring];
|
||||
if (!record(data) || (data.direction !== "cw" && data.direction !== "ccw") || !Array.isArray(data.tiles) || data.tiles.length !== sizes[ring]) return false;
|
||||
for (const tile of data.tiles) {
|
||||
if (!record(tile)) return false;
|
||||
if (!["nutrient", "heat", "toxin", "producer", "grazer", "phage"].every((field) => integer(tile[field], 0, 6))) return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!record(value.lineage)) return false;
|
||||
for (const lineage of LINEAGES) {
|
||||
const data = value.lineage[lineage];
|
||||
if (!record(data) || !record(data.pressure) || !record(data.unlocked)) return false;
|
||||
if (!PRESSURES.every((pressure) => integer(data.pressure[pressure], 0, 3) && typeof data.unlocked[pressure] === "boolean")) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// Generates canonical solver fixtures (win + loss routes per scenario) and verifies them.
|
||||
// Run: node --experimental-strip-types src/solver/gen-fixtures.ts
|
||||
import { readFileSync, writeFileSync } from "fs";
|
||||
import { SCENARIOS, buildInitialState } from "../domain/scenarios.ts";
|
||||
import { solveWin, solveLoss, replay, reachableInheritanceAt, inheritanceKey, lastWinTimedOut } from "../domain/solver.ts";
|
||||
import { nextState, resolve } from "../domain/transition.ts";
|
||||
import type { GameState, RotationAction, PressureId, Scenario } from "../domain/types.ts";
|
||||
|
||||
type Fixture = {
|
||||
scenarioId: string;
|
||||
win: RotationAction[];
|
||||
winOutcome: string;
|
||||
loss: RotationAction[];
|
||||
lossOutcome: string;
|
||||
exploitsAdaptation: boolean;
|
||||
avoidsAdaptation: boolean;
|
||||
};
|
||||
|
||||
type Effects = { evolved: boolean; benefit: boolean; cost: boolean; spillover: boolean; all: boolean };
|
||||
|
||||
function adaptationEffects(sc: Scenario, inherited: GameState["inheritedAtStart"], actions: RotationAction[]): Effects {
|
||||
let state = buildInitialState(sc, "campaign", inherited);
|
||||
const effects: Effects = { evolved: false, benefit: false, cost: false, spillover: false, all: false };
|
||||
for (const action of actions) {
|
||||
const result = resolve(state, action, true);
|
||||
state = result.state;
|
||||
for (const event of result.events) {
|
||||
if (event.phase === "evolution") effects.evolved = true;
|
||||
if (event.phase === "adaptation" && event.effect === "cost") effects.cost = true;
|
||||
if (event.phase === "adaptation" && event.effect === "spillover") effects.spillover = true;
|
||||
if (event.phase === "consequence" && event.kind === "prevented") effects.benefit = true;
|
||||
if ((event.phase === "consequence" && (event.kind === "payNutrient" || event.kind === "payPop")) ||
|
||||
(event.phase === "growth" && event.suppressed) ||
|
||||
(event.phase === "feed" && (event.suppressed || event.preyRemoved === 2))) effects.cost = true;
|
||||
if (event.phase === "spillover" || (event.phase === "immuneSelect" && event.retarget)) effects.spillover = true;
|
||||
}
|
||||
}
|
||||
effects.all = effects.evolved && effects.benefit && effects.cost && effects.spillover;
|
||||
return effects;
|
||||
}
|
||||
|
||||
const themePressure: Partial<Record<string, PressureId>> = {
|
||||
"s1-heat": "heat", "s2-hunger": "hunger", "s3-toxin": "toxin", "s4-immunity": "immunity",
|
||||
};
|
||||
|
||||
function trimRoute(sc: Scenario, inherited: GameState["inheritedAtStart"], actions: RotationAction[]): RotationAction[] {
|
||||
let state = buildInitialState(sc, "campaign", inherited);
|
||||
const route: RotationAction[] = [];
|
||||
for (const action of actions) {
|
||||
if (state.outcome !== "playing") break;
|
||||
route.push(action);
|
||||
state = nextState(state, action);
|
||||
}
|
||||
return route;
|
||||
}
|
||||
|
||||
const preferredWins: Partial<Record<string, RotationAction[]>> = {
|
||||
// Starts outside the objective, aligns two rings, and wins on the third resolved turn.
|
||||
"s5-convergence": [
|
||||
{ ring: "middle", dir: "ccw" },
|
||||
{ ring: "inner", dir: "cw" },
|
||||
{ ring: "middle", dir: "cw" },
|
||||
],
|
||||
};
|
||||
|
||||
let previousRoutes: Record<string, RotationAction[]> = {};
|
||||
try {
|
||||
previousRoutes = JSON.parse(readFileSync("test/solver-fixtures.json", "utf8")).campaignRoutes ?? {};
|
||||
} catch {
|
||||
// First generation has no candidates; the bounded solver supplies them.
|
||||
}
|
||||
|
||||
const fixtures: Record<string, Fixture> = {};
|
||||
for (const sc of SCENARIOS) {
|
||||
const candidate = preferredWins[sc.id];
|
||||
const preferred = candidate ? trimRoute(sc, { producer: [], grazer: [] }, candidate) : undefined;
|
||||
const win = preferred && replay(sc, { producer: [], grazer: [] }, preferred).outcome === "won"
|
||||
? preferred
|
||||
: solveWin(sc, { producer: [], grazer: [] }, { nodeBudget: 4_000_000, timeMs: 60_000 });
|
||||
if (!win) throw new Error(`No win found for ${sc.id} (timedOut=${lastWinTimedOut})`);
|
||||
const winEnd = replay(sc, { producer: [], grazer: [] }, win);
|
||||
if (winEnd.outcome !== "won") throw new Error(`Win replay mismatch for ${sc.id}: ${winEnd.outcome}`);
|
||||
const effects = adaptationEffects(sc, { producer: [], grazer: [] }, win);
|
||||
const theme = themePressure[sc.id];
|
||||
const avoids = theme ? !winEnd.lineage.producer.unlocked[theme] && !winEnd.lineage.grazer.unlocked[theme] : false;
|
||||
|
||||
const loss = solveLoss(sc, { producer: [], grazer: [] }) ?? [];
|
||||
const lossEnd = replay(sc, { producer: [], grazer: [] }, loss);
|
||||
if (lossEnd.outcome !== "collapsed" && lossEnd.outcome !== "expired") {
|
||||
// fallback: play to turn limit with a fixed sequence to force expiry
|
||||
let s = buildInitialState(sc, "campaign");
|
||||
let seq: RotationAction[] = [];
|
||||
while (s.outcome === "playing") {
|
||||
const a = { ring: "outer" as const, dir: "cw" as const };
|
||||
s = nextState(s, a);
|
||||
seq = [...seq, a];
|
||||
}
|
||||
fixtures[sc.id] = { scenarioId: sc.id, win, winOutcome: winEnd.outcome, loss: seq, lossOutcome: s.outcome, exploitsAdaptation: effects.all, avoidsAdaptation: avoids };
|
||||
continue;
|
||||
}
|
||||
fixtures[sc.id] = {
|
||||
scenarioId: sc.id,
|
||||
win,
|
||||
winOutcome: winEnd.outcome,
|
||||
loss,
|
||||
lossOutcome: lossEnd.outcome,
|
||||
exploitsAdaptation: effects.all,
|
||||
avoidsAdaptation: avoids,
|
||||
};
|
||||
console.log(`${sc.id}: win=${win.length} (${winEnd.outcome}) loss=${loss.length} (${lossEnd.outcome}) exploits=${effects.all} avoids=${avoids}`);
|
||||
}
|
||||
|
||||
// Prove a conservative superset of all reachable campaign inheritance sets. For N prior
|
||||
// scenarios this checks every subset of up to N of the eight lineage/pressure slots.
|
||||
let reachOk = true;
|
||||
const reachReport: string[] = [];
|
||||
const campaignRoutes: Record<string, RotationAction[]> = {};
|
||||
let adaptationEvidence: ({ scenarioId: string; inheritanceKey: string; route: RotationAction[] } & Effects) | null = null;
|
||||
for (let idx = 2; idx <= 5; idx++) {
|
||||
const sc = SCENARIOS[idx - 1];
|
||||
const baseline = fixtures[sc.id].win;
|
||||
for (const inherited of reachableInheritanceAt(idx)) {
|
||||
const key = `${sc.id}|${inheritanceKey(inherited)}`;
|
||||
const inheritedBaseline = trimRoute(sc, inherited, baseline);
|
||||
const baselineEnd = replay(sc, inherited, inheritedBaseline);
|
||||
const previousCandidate = previousRoutes[key];
|
||||
const previous = previousCandidate ? trimRoute(sc, inherited, previousCandidate) : undefined;
|
||||
const win = baselineEnd.outcome === "won"
|
||||
? inheritedBaseline
|
||||
: previous && replay(sc, inherited, previous).outcome === "won"
|
||||
? previous
|
||||
: solveWin(sc, inherited, { nodeBudget: 4_000_000, timeMs: 60_000 });
|
||||
if (!win) {
|
||||
reachOk = false;
|
||||
reachReport.push(`FAIL ${key} (timedOut=${lastWinTimedOut})`);
|
||||
} else {
|
||||
campaignRoutes[key] = win;
|
||||
reachReport.push(`ok ${key} win=${win.length}`);
|
||||
const routeEffects = adaptationEffects(sc, inherited, win);
|
||||
if (!adaptationEvidence && routeEffects.all) adaptationEvidence = { scenarioId: sc.id, inheritanceKey: inheritanceKey(inherited), route: win, ...routeEffects };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!adaptationEvidence) {
|
||||
reachOk = false;
|
||||
reachReport.push("FAIL no winning route demonstrated adaptation benefit, cost, and spillover");
|
||||
}
|
||||
writeFileSync("test/solver-fixtures.json", JSON.stringify({ fixtures, campaignRoutes, adaptationEvidence, reachOk, reachReport }, null, 2));
|
||||
|
||||
console.log("\nReachability:", reachOk ? "OK" : "FAILURES");
|
||||
console.log("Wrote test/solver-fixtures.json");
|
||||
if (!reachOk) process.exit(1);
|
||||
@@ -0,0 +1,119 @@
|
||||
/* Adaptive Loop — dark laboratory glass. Procedural SVG/CSS only. */
|
||||
:root {
|
||||
--bg: #070d18;
|
||||
--panel: #0e1830;
|
||||
--panel-2: #131f3b;
|
||||
--ink: #e6edf7;
|
||||
--muted: #8aa0c4;
|
||||
--line: #25344f;
|
||||
--accent: #5fd0ff;
|
||||
--accent-2: #7fffd6;
|
||||
--warn: #ffb347;
|
||||
--good: #7fff8a;
|
||||
--bad: #ff6b6b;
|
||||
--ring-inner: #5fd0ff;
|
||||
--ring-middle: #9d7bff;
|
||||
--ring-outer: #7fffd6;
|
||||
--radius: 8px;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; padding: 0; background: var(--bg); color: var(--ink); font: 15px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; }
|
||||
#app { min-height: 100vh; }
|
||||
.app { max-width: 1200px; margin: 0 auto; padding: 12px; }
|
||||
h1, h2, h3 { color: #fff; margin: 0 0 6px; font-weight: 600; }
|
||||
h1 { font-size: 22px; }
|
||||
h2 { font-size: 16px; }
|
||||
p { margin: 4px 0; }
|
||||
.muted { color: var(--muted); }
|
||||
|
||||
/* Topbar */
|
||||
.topbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 6px 4px; border-bottom: 1px solid var(--line); margin-bottom: 8px; flex-wrap: wrap; }
|
||||
.topnav { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
|
||||
/* Buttons */
|
||||
.btn { font: inherit; color: var(--ink); background: var(--panel-2); border: 1px solid var(--line); border-radius: var(--radius); padding: 8px 12px; cursor: pointer; min-height: 40px; }
|
||||
.btn:hover:not(:disabled) { border-color: var(--accent); }
|
||||
.btn:focus-visible { outline: 3px solid var(--accent); outline-offset: 1px; }
|
||||
.btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.btn.primary { background: linear-gradient(180deg, #1b3a6b, #142a52); border-color: var(--accent); color: #fff; }
|
||||
.btn.ghost { background: transparent; }
|
||||
.btn.selected { background: linear-gradient(180deg, #2a5b3a, #1c3f2a); border-color: var(--good); color: #d8ffd8; }
|
||||
|
||||
/* Title */
|
||||
.title { min-height: 90vh; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 10px; }
|
||||
.title h1 { font-size: 40px; letter-spacing: 1px; background: linear-gradient(90deg, var(--ring-inner), var(--ring-middle), var(--ring-outer)); -webkit-background-clip: text; background-clip: text; color: transparent; }
|
||||
.subtitle { color: var(--muted); font-size: 18px; }
|
||||
.lede { max-width: 640px; color: var(--ink); }
|
||||
.actions { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; }
|
||||
.hint { color: var(--muted); font-size: 13px; }
|
||||
|
||||
/* Play layout */
|
||||
.play { display: grid; grid-template-columns: minmax(360px, 1fr) 340px; gap: 12px; align-items: start; }
|
||||
@media (max-width: 900px) { .play { grid-template-columns: 1fr; } .rail { order: 2; } .board-wrap { order: 1; } }
|
||||
.board-wrap { background: radial-gradient(circle at center, #0c1830 0%, #060b16 70%); border: 1px solid var(--line); border-radius: var(--radius); padding: 8px; }
|
||||
.board-svg { width: 100%; height: auto; display: block; }
|
||||
.tile-ledger { display: none; }
|
||||
@media (max-width: 700px) {
|
||||
.tile-ledger { display: block; margin-top: 8px; color: var(--ink); font-size: 13px; }
|
||||
.tile-ledger summary { cursor: pointer; font-weight: 600; }
|
||||
.tile-ledger div { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 4px 8px; margin-top: 6px; }
|
||||
.tile-ledger span { overflow-wrap: anywhere; }
|
||||
}
|
||||
.rail { display: flex; flex-direction: column; gap: 10px; }
|
||||
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 10px 12px; }
|
||||
.obj .obj-text { color: var(--ink); }
|
||||
.turn { color: var(--accent); font-weight: 600; }
|
||||
.envflag { display: inline-block; background: #3a2a10; border: 1px solid var(--warn); color: var(--warn); border-radius: 12px; padding: 1px 8px; font-size: 12px; margin-right: 4px; }
|
||||
.inh { color: var(--muted); font-size: 12px; }
|
||||
|
||||
/* Rotation controls */
|
||||
.rot-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
|
||||
.rot { display: flex; align-items: center; gap: 6px; justify-content: center; }
|
||||
.key { display: inline-block; min-width: 16px; padding: 0 4px; background: #0a1426; border: 1px solid var(--line); border-radius: 4px; font-size: 11px; color: var(--muted); }
|
||||
.commit-row { display: flex; gap: 6px; margin-top: 8px; flex-wrap: wrap; }
|
||||
.sel-status { color: var(--muted); font-size: 12px; margin-top: 6px; }
|
||||
|
||||
/* Traits */
|
||||
.lineage { display: flex; align-items: center; gap: 8px; margin: 4px 0; flex-wrap: wrap; }
|
||||
.lin-name { min-width: 78px; color: var(--ink); }
|
||||
.ptrack { display: inline-grid; grid-template-columns: 18px auto; align-items: center; gap: 0 4px; font-size: 10px; color: var(--muted); }
|
||||
.ptrack svg { width: 18px; height: 18px; grid-row: span 2; }
|
||||
.ptrack b { font: 10px ui-monospace, monospace; letter-spacing: 1px; font-weight: 500; }
|
||||
.ptrack.adapted { color: var(--good); }
|
||||
.legend-mini { color: var(--muted); font-size: 11px; }
|
||||
|
||||
/* Events */
|
||||
.event-list { margin: 4px 0 0; padding-left: 18px; max-height: 200px; overflow-y: auto; font-size: 13px; }
|
||||
.event-list li { margin: 2px 0; }
|
||||
.event-list b { color: var(--accent-2); }
|
||||
.prediction { color: var(--accent-2); font-size: 12px; }
|
||||
.relocation { color: var(--muted); font-size: 11px; margin: 6px 0; }
|
||||
.relocation summary { color: var(--ink); cursor: pointer; }
|
||||
.relocation p, .delta-list p { margin: 3px 0; overflow-wrap: anywhere; }
|
||||
.delta-list { color: var(--muted); font-size: 11px; max-height: 90px; overflow-y: auto; border-block: 1px solid var(--line); padding: 5px 0; }
|
||||
|
||||
/* Menu / scenarios */
|
||||
.scn-list { list-style: none; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; }
|
||||
.scn-list li.locked .scenario-btn { opacity: 0.35; }
|
||||
.scenario-btn { width: 100%; text-align: left; display: flex; flex-direction: column; gap: 2px; }
|
||||
.scn-no { color: var(--accent); font-weight: 700; }
|
||||
.scn-sub { color: var(--muted); font-size: 12px; }
|
||||
|
||||
/* Choice */
|
||||
.choice { max-width: 760px; margin: 0 auto; text-align: center; }
|
||||
.choice-grid { display: grid; grid-template-columns: 1fr; gap: 8px; margin: 14px 0; }
|
||||
.choice .ch-lin { color: var(--accent); font-weight: 700; }
|
||||
.choice .ch-trait { color: var(--good); font-weight: 700; }
|
||||
.choice .ch-meta { color: var(--muted); font-size: 12px; }
|
||||
|
||||
/* Announce + help */
|
||||
.announce { color: var(--muted); font-size: 13px; min-height: 18px; }
|
||||
.help-panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px; margin-top: 12px; }
|
||||
.help-panel.hidden { display: none; }
|
||||
kbd { background: #0a1426; border: 1px solid var(--line); border-radius: 4px; padding: 1px 5px; font-family: ui-monospace, monospace; font-size: 12px; }
|
||||
.victory { text-align: center; padding: 40px; }
|
||||
|
||||
/* Reduced motion: we render final states already; ensure no transitions. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* { transition: none !important; animation: none !important; }
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
// Application: views, controls, preview/commit, campaign flow, persistence, accessibility.
|
||||
import type { GameState, LineageId, Mode, PressureId, RotationAction, RingId, Scenario } from "../domain/types.ts";
|
||||
import { SCENARIOS, buildInitialState, getScenario } from "../domain/scenarios.ts";
|
||||
import { resolve } from "../domain/transition.ts";
|
||||
import type { GameEvent } from "../domain/transition.ts";
|
||||
import { renderBoard, renderTraits } from "./board.ts";
|
||||
import { saveGame, loadGame, loadCampaignGame, clearSave, hasSave, hasCampaignSave } from "../persistence/save.ts";
|
||||
import type { CampaignProgress, SaveEnvelope } from "../persistence/save.ts";
|
||||
import { TRAIT_NAME, PRESSURE_META } from "../domain/types.ts";
|
||||
|
||||
type View = "title" | "menu" | "play" | "choice" | "victory";
|
||||
|
||||
type App = {
|
||||
view: View;
|
||||
mode: Mode;
|
||||
scenario: Scenario;
|
||||
state: GameState;
|
||||
progress: CampaignProgress;
|
||||
selected: RotationAction | null;
|
||||
preview: { state: GameState; events: GameEvent[] } | null;
|
||||
lastEvents: GameEvent[];
|
||||
announce: string;
|
||||
pendingNewTraits: { lin: LineageId; p: PressureId }[];
|
||||
};
|
||||
|
||||
const ROTATIONS: { ring: RingId; dir: "cw" | "ccw"; label: string; key: string }[] = [
|
||||
{ ring: "inner", dir: "cw", label: "Inner ⟳", key: "1" },
|
||||
{ ring: "inner", dir: "ccw", label: "Inner ⟲", key: "2" },
|
||||
{ ring: "middle", dir: "cw", label: "Middle ⟳", key: "3" },
|
||||
{ ring: "middle", dir: "ccw", label: "Middle ⟲", key: "4" },
|
||||
{ ring: "outer", dir: "cw", label: "Outer ⟳", key: "5" },
|
||||
{ ring: "outer", dir: "ccw", label: "Outer ⟲", key: "6" },
|
||||
];
|
||||
|
||||
let app: App;
|
||||
let root: HTMLElement;
|
||||
let suppressFocusPreview = false;
|
||||
|
||||
function focusWithoutPreview(element: HTMLElement | null): void {
|
||||
suppressFocusPreview = true;
|
||||
element?.focus();
|
||||
suppressFocusPreview = false;
|
||||
}
|
||||
|
||||
export function mount(el: HTMLElement): void {
|
||||
root = el;
|
||||
app = {
|
||||
view: "title",
|
||||
mode: "campaign",
|
||||
scenario: SCENARIOS[0],
|
||||
state: buildInitialState(SCENARIOS[0], "campaign"),
|
||||
progress: freshProgress(),
|
||||
selected: null,
|
||||
preview: null,
|
||||
lastEvents: [],
|
||||
announce: "",
|
||||
pendingNewTraits: [],
|
||||
};
|
||||
render();
|
||||
}
|
||||
|
||||
function freshProgress(): CampaignProgress {
|
||||
return {
|
||||
unlocked: [SCENARIOS[0].id],
|
||||
inherited: { producer: [], grazer: [] },
|
||||
entrySnapshot: { producer: [], grazer: [] },
|
||||
victory: false,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- rendering ----------
|
||||
function render(): void {
|
||||
root.innerHTML = viewHTML();
|
||||
wireEvents();
|
||||
const live = root.querySelector<HTMLElement>("#announce");
|
||||
queueMicrotask(() => { if (live) live.textContent = app.announce; });
|
||||
}
|
||||
|
||||
function viewHTML(): string {
|
||||
if (app.view === "title") return titleHTML();
|
||||
if (app.view === "menu") return menuHTML();
|
||||
if (app.view === "victory") return victoryHTML();
|
||||
if (app.view === "choice") return choiceHTML();
|
||||
return playHTML();
|
||||
}
|
||||
|
||||
function shell(inner: string, h1: string): string {
|
||||
return `<main class="app">
|
||||
<header class="topbar"><h1>${h1}</h1>
|
||||
<nav class="topnav">
|
||||
<button id="btnMenu" class="btn ghost" aria-label="Return to menu">Menu</button>
|
||||
<button id="btnSaveQuit" class="btn ghost" aria-label="Save and quit to title">Save & Quit</button>
|
||||
<button id="btnHelp" class="btn ghost" aria-label="Open help and legend" aria-controls="helpPanel" aria-expanded="false">Help</button>
|
||||
</nav>
|
||||
</header>
|
||||
<div id="announce" class="announce" role="status" aria-live="polite" aria-atomic="true"></div>
|
||||
${inner}
|
||||
<section id="helpPanel" class="help-panel hidden" aria-hidden="true">${legendHTML()}</section>
|
||||
</main>`;
|
||||
}
|
||||
|
||||
function titleHTML(): string {
|
||||
return `<main class="app title">
|
||||
<div id="announce" class="announce" role="status" aria-live="polite" aria-atomic="true"></div>
|
||||
<h1>Adaptive Loop</h1>
|
||||
<p class="subtitle">A calm deterministic microfluidic strategy puzzle.</p>
|
||||
<p class="lede">Rotate the three concentric glass rings to align the six radial gates, route nutrient inward, and provoke — then exploit — the ecosystem's counter-adaptations.</p>
|
||||
<div class="actions">
|
||||
<button id="btnStart" class="btn primary">New Campaign</button>
|
||||
<button id="btnContinue" class="btn">Continue</button>
|
||||
<button id="btnResumeCampaign" class="btn" ${hasCampaignSave() ? "" : "disabled"}>Resume Campaign</button>
|
||||
<button id="btnReplay" class="btn">Replay Standalone</button>
|
||||
</div>
|
||||
<p class="hint">${hasSave() ? "A saved run is available." : "Continue starts the next campaign scenario."}</p>
|
||||
</main>`;
|
||||
}
|
||||
|
||||
function menuHTML(): string {
|
||||
const standalone = app.mode === "standalone";
|
||||
const items = SCENARIOS.map((scenario) => {
|
||||
const unlocked = app.progress.unlocked.includes(scenario.id);
|
||||
const selectable = standalone ? unlocked : scenario.id === app.scenario.id && app.state.outcome === "playing";
|
||||
const action = standalone ? "Replay" : "Resume";
|
||||
return `<li class="${selectable ? "" : "locked"}">
|
||||
<button class="btn scenario-btn" data-scid="${scenario.id}" ${selectable ? "" : "disabled"} aria-label="${action} ${scenario.name}">
|
||||
<span class="scn-no">${scenario.index}</span>
|
||||
<span class="scn-name">${scenario.name}</span>
|
||||
<span class="scn-sub">${scenario.subtitle}</span>
|
||||
</button>
|
||||
</li>`;
|
||||
}).join("");
|
||||
const heading = standalone ? "Standalone Replay" : "Current Campaign";
|
||||
return shell(`<section class="menu"><h2>${heading}</h2><ul class="scn-list">${items}</ul></section>`, "Adaptive Loop — Menu");
|
||||
}
|
||||
|
||||
function playHTML(): string {
|
||||
const sc = app.scenario;
|
||||
const st = app.state;
|
||||
const terminal = st.outcome !== "playing";
|
||||
const flowEvents = (app.preview?.events ?? []).filter((e) => e.phase === "flow").map((e) => ({ ring: (e as any).ring, index: (e as any).index, field: (e as any).field, tangential: (e as any).tangential, radial: (e as any).radial })) as { ring: RingId; index: number; field: "nutrient" | "toxin"; tangential: number; radial: number }[];
|
||||
const board = renderBoard(st, sc, { previewState: app.preview?.state ?? null, selectedRing: app.selected?.ring ?? null, flowEvents });
|
||||
const objective = objectiveText(sc, st);
|
||||
const turnInfo = `Turn ${st.turn}/${sc.turnLimit}${st.outcome !== "playing" ? ` — ${outcomeLabel(st.outcome)}` : ""}`;
|
||||
const rotBtns = ROTATIONS.map((r) => {
|
||||
const sel = app.selected && app.selected.ring === r.ring && app.selected.dir === r.dir;
|
||||
const pred = sel && app.preview ? ` → ${predictLabel(app.preview.events)}` : "";
|
||||
return `<button class="btn rot ${sel ? "selected" : ""}" data-ring="${r.ring}" data-dir="${r.dir}" aria-label="Rotate ${r.ring} ${r.dir === "cw" ? "clockwise" : "counter-clockwise"}${pred}"${terminal ? " disabled" : ""}><span class="key">${r.key}</span> ${r.label}</button>`;
|
||||
}).join("");
|
||||
const commitDisabled = terminal || !app.selected;
|
||||
const commitBtn = `<button id="btnCommit" class="btn primary" ${commitDisabled ? "disabled" : ""} aria-label="Commit selected rotation">Commit</button>`;
|
||||
const cancelBtn = `<button id="btnCancel" class="btn ghost" ${!app.selected ? "disabled" : ""} aria-label="Cancel preview">Cancel (Esc)</button>`;
|
||||
const retryBtn = st.outcome === "collapsed" || st.outcome === "expired" ? `<button id="btnRetry" class="btn">Retry</button>` : "";
|
||||
const eventText = eventsToText(app.preview?.events ?? app.lastEvents);
|
||||
const previewDetails = app.preview && app.selected ? previewDetailsHTML(sc, st, app.preview.state, app.selected) : "";
|
||||
const traits = renderTraits(st);
|
||||
const envFlags = (["heat", "hunger", "toxin", "immunity"] as PressureId[]).filter((p) => st.environmentActive[p]).map((p) => `<span class="envflag">${PRESSURE_META[p].label} Response</span>`).join("");
|
||||
const inherited = [...app.progress.inherited.producer.map((p) => `Lumiflora:${TRAIT_NAME[p]}`), ...app.progress.inherited.grazer.map((p) => `Vellea:${TRAIT_NAME[p]}`)].join(", ") || "none";
|
||||
|
||||
return shell(`<section class="play">
|
||||
<div class="board-wrap">${board}</div>
|
||||
<aside class="rail">
|
||||
<div class="panel obj">
|
||||
<h2>${sc.index}. ${sc.name} <span class="scn-sub">(${sc.subtitle})</span></h2>
|
||||
<p class="obj-text">${objective}</p>
|
||||
<p class="turn">${turnInfo}</p>
|
||||
${envFlags ? `<p class="env">${envFlags}</p>` : ""}
|
||||
<p class="inh">Inherited: ${inherited}</p>
|
||||
</div>
|
||||
<div class="panel controls">
|
||||
<h2>Rotate a ring</h2>
|
||||
<div class="rot-grid">${rotBtns}</div>
|
||||
<div class="commit-row">${commitBtn} ${cancelBtn} ${retryBtn}</div>
|
||||
<p class="sel-status">${app.selected ? `Selected: ${app.selected.ring} ${app.selected.dir}. Commit enabled.` : "Select a rotation to preview."}</p>
|
||||
</div>
|
||||
<div class="panel traits"><h2>Pressure tracks</h2>${traits}<p class="legend-mini">▰ = track step · ✓ = adapted (benefit+cost active)</p></div>
|
||||
<div class="panel events"><h2>${app.preview ? "Exact one-turn preview" : "Last tick"}</h2>${previewDetails}<ol class="event-list">${eventText}</ol></div>
|
||||
</aside>
|
||||
</section>`, `Adaptive Loop — ${sc.name}`);
|
||||
}
|
||||
|
||||
function choiceHTML(): string {
|
||||
const opts = app.pendingNewTraits.map((t, i) => {
|
||||
const lin = t.lin === "producer" ? "Lumiflora" : "Vellea";
|
||||
const meta = PRESSURE_META[t.p];
|
||||
return `<button class="btn trait-choice" data-i="${i}"><span class="ch-lin">${lin}</span> · <span class="ch-trait">${TRAIT_NAME[t.p]}</span><br><span class="ch-meta">Benefit: prevents ${t.p} loss. Cost: ${costText(t.p)}. ${meta.response}.</span></button>`;
|
||||
}).join("");
|
||||
return shell(`<section class="choice">
|
||||
<h2>Scenario won — preserve a lineage trait?</h2>
|
||||
<p>The ecosystem unlocked new adaptations. Preserve one to carry its gift (and cost) forward, or decline.</p>
|
||||
<div class="choice-grid">${opts}</div>
|
||||
<button id="btnDecline" class="btn ghost">Decline</button>
|
||||
</section>`, "Lineage choice");
|
||||
}
|
||||
|
||||
function victoryHTML(): string {
|
||||
return shell(`<section class="victory"><h2>Campaign Victory</h2><p>You stabilized the Adaptive Loop across all five scenarios.</p><button id="btnVictoryMenu" class="btn primary">Return to Menu</button></section>`, "Victory");
|
||||
}
|
||||
|
||||
function legendHTML(): string {
|
||||
const species = `<li><b>Lumiflora</b> (producer, green diatom) — consumes nutrient, grows.</li>
|
||||
<li><b>Vellea</b> (grazer, amber crescent) — consumes producers, grows.</li>
|
||||
<li><b>Phage</b> (pink lander) — consumes grazers; starves without prey.</li>`;
|
||||
const pressures = (["heat", "hunger", "toxin", "immunity"] as PressureId[]).map((p) => `<li><b>${PRESSURE_META[p].label}</b> → trait <b>${TRAIT_NAME[p]}</b>. Response: ${PRESSURE_META[p].response}.</li>`).join("");
|
||||
return `<h2>Help & Legend</h2><p>Rotate a ring (buttons or keys 1–6). A rotation moves that ring's payloads and re-aligns the gates; the tick then resolves flow, growth, feeding, migration, adaptation, and pressure. Select to preview exact deltas; Commit applies it.</p>
|
||||
<h3>Species</h3><ul>${species}</ul>
|
||||
<h3>Pressures & adaptations</h3><ul>${pressures}</ul>
|
||||
<p>Gate tiles glow in their ring color; nutrient fills the tile base blue, toxin green, heat warms the rim. <kbd>1</kbd>–<kbd>6</kbd> rotate, <kbd>Enter</kbd>/<kbd>Space</kbd> commits, <kbd>Esc</kbd> cancels.</p>`;
|
||||
}
|
||||
|
||||
// ---------- event wiring ----------
|
||||
function wireEvents(): void {
|
||||
const on = (id: string, ev: string, fn: () => void) => root.querySelector<HTMLElement>(id)?.addEventListener(ev, fn);
|
||||
on("#btnStart", "click", startCampaign);
|
||||
on("#btnContinue", "click", continueRun);
|
||||
on("#btnResumeCampaign", "click", resumeCampaign);
|
||||
on("#btnReplay", "click", openStandalone);
|
||||
on("#btnMenu", "click", () => { app.view = "menu"; render(); });
|
||||
on("#btnVictoryMenu", "click", () => { app.view = "menu"; render(); });
|
||||
on("#btnSaveQuit", "click", saveAndQuit);
|
||||
on("#btnHelp", "click", toggleHelp);
|
||||
on("#btnDecline", "click", () => advanceAfterWin(null));
|
||||
|
||||
root.querySelectorAll<HTMLElement>(".rot").forEach((b) => {
|
||||
const ring = b.dataset.ring as RingId;
|
||||
const dir = b.dataset.dir as "cw" | "ccw";
|
||||
b.addEventListener("click", () => selectAction({ ring, dir }));
|
||||
b.addEventListener("focus", () => {
|
||||
if (!suppressFocusPreview && (!app.selected || app.selected.ring !== ring || app.selected.dir !== dir)) selectAction({ ring, dir });
|
||||
});
|
||||
b.addEventListener("mouseenter", () => { if (!app.selected) selectAction({ ring, dir }); });
|
||||
});
|
||||
root.querySelectorAll<HTMLElement>(".scenario-btn").forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
if (app.mode === "campaign") {
|
||||
app.view = "play";
|
||||
app.announce = `Resumed ${app.scenario.name}.`;
|
||||
render();
|
||||
} else {
|
||||
startScenario(button.dataset.scid!, "standalone");
|
||||
}
|
||||
});
|
||||
});
|
||||
root.querySelectorAll<HTMLElement>(".trait-choice").forEach((b) => {
|
||||
b.addEventListener("click", () => { const i = +b.dataset.i!; advanceAfterWin(app.pendingNewTraits[i] ?? null); });
|
||||
});
|
||||
on("#btnCommit", "click", commit);
|
||||
on("#btnCancel", "click", cancelPreview);
|
||||
on("#btnRetry", "click", retry);
|
||||
|
||||
document.onkeydown = handleKey;
|
||||
}
|
||||
|
||||
function handleKey(e: KeyboardEvent): void {
|
||||
if (e.key === "Escape") { cancelPreview(); return; }
|
||||
if (app.view !== "play" || app.state.outcome !== "playing") return;
|
||||
const idx = "123456".indexOf(e.key);
|
||||
if (idx >= 0) { selectAction(ROTATIONS[idx]); return; }
|
||||
if ((e.key === "Enter" || e.key === " ") && app.selected && document.activeElement?.classList.contains("rot")) { e.preventDefault(); commit(); }
|
||||
}
|
||||
|
||||
// ---------- actions ----------
|
||||
function startCampaign(): void {
|
||||
if (hasSave() && !window.confirm("Start a new campaign and clear the current campaign save?")) return;
|
||||
clearSave();
|
||||
app.mode = "campaign";
|
||||
app.progress = freshProgress();
|
||||
app.view = "play";
|
||||
startScenario(SCENARIOS[0].id, "campaign");
|
||||
}
|
||||
|
||||
function openStandalone(): void {
|
||||
const saved = loadGame();
|
||||
app.progress = saved.ok ? saved.env.progress : freshProgress();
|
||||
app.mode = "standalone";
|
||||
app.view = "menu";
|
||||
app.announce = "Choose an unlocked scenario. Standalone runs never change campaign progress.";
|
||||
render();
|
||||
}
|
||||
|
||||
function continueRun(): void {
|
||||
const r = loadGame();
|
||||
if (!r.ok) {
|
||||
if (!hasSave()) {
|
||||
startScenario(app.progress.unlocked[app.progress.unlocked.length - 1] ?? SCENARIOS[0].id, "campaign");
|
||||
return;
|
||||
}
|
||||
app.announce = r.reason;
|
||||
render();
|
||||
return;
|
||||
}
|
||||
restoreRun(r.env, "Resumed saved run.");
|
||||
}
|
||||
|
||||
function resumeCampaign(): void {
|
||||
const result = loadCampaignGame();
|
||||
if (!result.ok) { app.announce = result.reason; render(); return; }
|
||||
restoreRun(result.env, "Resumed campaign run.");
|
||||
}
|
||||
|
||||
function restoreRun(env: SaveEnvelope, announcement: string): void {
|
||||
app.mode = env.mode;
|
||||
app.progress = env.progress;
|
||||
app.scenario = getScenario(env.scenarioId);
|
||||
app.state = env.state;
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
app.lastEvents = [];
|
||||
app.view = "play";
|
||||
app.announce = announcement;
|
||||
if (app.mode === "campaign" && app.state.outcome === "won") onWin();
|
||||
else render();
|
||||
}
|
||||
|
||||
function startScenario(id: string, mode: Mode): void {
|
||||
const sc = getScenario(id);
|
||||
app.scenario = sc;
|
||||
app.mode = mode;
|
||||
const inh = mode === "standalone" ? { producer: [], grazer: [] } : app.progress.inherited;
|
||||
app.state = buildInitialState(sc, mode, inh);
|
||||
app.progress.entrySnapshot = { producer: [...inh.producer], grazer: [...inh.grazer] };
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
app.lastEvents = [];
|
||||
app.view = "play";
|
||||
app.announce = `${sc.name}: ${sc.teaches}`;
|
||||
saveCurrent();
|
||||
render();
|
||||
}
|
||||
|
||||
function selectAction(a: RotationAction): void {
|
||||
if (app.state.outcome !== "playing") return;
|
||||
app.selected = a;
|
||||
const { state, events } = resolve(app.state, a, true);
|
||||
app.preview = { state, events };
|
||||
app.announce = `Previewing ${a.ring} ${a.dir}: ${predictLabel(events)}`;
|
||||
render();
|
||||
// keep focus on the selected control for keyboard flow
|
||||
const sel = root.querySelector<HTMLElement>(`.rot[data-ring="${a.ring}"][data-dir="${a.dir}"]`);
|
||||
sel?.focus();
|
||||
}
|
||||
|
||||
function cancelPreview(): void {
|
||||
if (!app.selected) return;
|
||||
const action = app.selected;
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
app.announce = "Preview cancelled.";
|
||||
render();
|
||||
focusWithoutPreview(root.querySelector<HTMLElement>(`.rot[data-ring="${action.ring}"][data-dir="${action.dir}"]`));
|
||||
}
|
||||
|
||||
function commit(): void {
|
||||
if (!app.selected || app.state.outcome !== "playing") return;
|
||||
const a = app.selected;
|
||||
const { state, events } = resolve(app.state, a, true);
|
||||
app.state = state;
|
||||
app.lastEvents = events;
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
app.announce = `Turn ${state.turn}: ${outcomeLabel(state.outcome)}.`;
|
||||
saveCurrent();
|
||||
if (state.outcome === "won") {
|
||||
onWin();
|
||||
} else {
|
||||
render();
|
||||
const selector = state.outcome === "playing" ? `.rot[data-ring="${a.ring}"][data-dir="${a.dir}"]` : "#btnRetry";
|
||||
focusWithoutPreview(root.querySelector<HTMLElement>(selector));
|
||||
}
|
||||
}
|
||||
|
||||
function onWin(): void {
|
||||
if (app.mode === "standalone") {
|
||||
app.announce = "Standalone scenario complete.";
|
||||
render();
|
||||
root.querySelector<HTMLElement>("#btnMenu")?.focus();
|
||||
return;
|
||||
}
|
||||
// newly unlocked traits during this scenario (not already inherited)
|
||||
const start = app.state.inheritedAtStart;
|
||||
const newly: { lin: LineageId; p: PressureId }[] = [];
|
||||
for (const lin of ["producer", "grazer"] as LineageId[]) {
|
||||
for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) {
|
||||
if (app.state.lineage[lin].unlocked[p] && !start[lin].includes(p) && !app.progress.inherited[lin].includes(p)) {
|
||||
newly.push({ lin, p });
|
||||
}
|
||||
}
|
||||
}
|
||||
const nextIdx = app.scenario.index; // 0-based next
|
||||
const next = SCENARIOS[nextIdx];
|
||||
// unlock next scenario and persist the won state before the choice screen.
|
||||
if (next && !app.progress.unlocked.includes(next.id)) app.progress.unlocked.push(next.id);
|
||||
if (!next) {
|
||||
app.progress.victory = true;
|
||||
saveCurrent();
|
||||
app.view = "victory";
|
||||
render();
|
||||
root.querySelector<HTMLElement>("#btnMenu")?.focus();
|
||||
return;
|
||||
}
|
||||
saveCurrent();
|
||||
if (newly.length === 0) { advanceAfterWin(null); return; }
|
||||
app.pendingNewTraits = newly;
|
||||
app.view = "choice";
|
||||
render();
|
||||
root.querySelector<HTMLElement>(".trait-choice, #btnDecline")?.focus();
|
||||
}
|
||||
|
||||
function advanceAfterWin(choice: { lin: LineageId; p: PressureId } | null): void {
|
||||
if (choice) {
|
||||
app.progress.inherited[choice.lin] = [...app.progress.inherited[choice.lin], choice.p];
|
||||
}
|
||||
const nextIdx = app.scenario.index; // 0-based
|
||||
const next = SCENARIOS[nextIdx];
|
||||
if (!next) { app.progress.victory = true; saveCurrent(); app.view = "victory"; render(); return; }
|
||||
startScenario(next.id, "campaign");
|
||||
}
|
||||
|
||||
function retry(): void {
|
||||
// restore scenario-entry inheritance snapshot
|
||||
if (app.mode === "campaign") app.progress.inherited = { producer: [...app.progress.entrySnapshot.producer], grazer: [...app.progress.entrySnapshot.grazer] };
|
||||
startScenario(app.scenario.id, app.mode);
|
||||
}
|
||||
|
||||
function saveAndQuit(): void {
|
||||
saveCurrent();
|
||||
app.view = "title";
|
||||
app.announce = "Saved. Quit to title.";
|
||||
render();
|
||||
}
|
||||
|
||||
function saveCurrent(): void {
|
||||
if (app.view !== "play" && app.view !== "choice") return;
|
||||
saveGame({
|
||||
schemaVersion: 1,
|
||||
mode: app.mode,
|
||||
scenarioId: app.scenario.id,
|
||||
state: app.state,
|
||||
progress: app.progress,
|
||||
actionLog: app.state.actionLog,
|
||||
outcome: app.state.outcome,
|
||||
});
|
||||
}
|
||||
|
||||
function toggleHelp(): void {
|
||||
const p = root.querySelector<HTMLElement>("#helpPanel");
|
||||
if (!p) return;
|
||||
p.classList.toggle("hidden");
|
||||
p.setAttribute("aria-hidden", p.classList.contains("hidden") ? "true" : "false");
|
||||
root.querySelector<HTMLElement>("#btnHelp")?.setAttribute("aria-expanded", p.classList.contains("hidden") ? "false" : "true");
|
||||
}
|
||||
|
||||
// ---------- helpers ----------
|
||||
function objectiveText(sc: Scenario, st: GameState): string {
|
||||
if (sc.id === "s1-heat") return `Grow producers: producer at I0 ≥ 4 and total producer ≥ 12.`;
|
||||
if (sc.id === "s2-hunger") return `Endure to turn 10: total producer ≥ 8, grazer ≥ 4, across ≥3 producer tiles and ≥2 grazer tiles.`;
|
||||
if (sc.id === "s3-toxin") return `Contain: by turn 6–9 reach total toxin ≤ 8 and producer+grazer ≥ 8. (Tuned)`;
|
||||
if (sc.id === "s4-immunity") return `Escort: grazer at I0 (sanctuary) ≥ 4 and total producer ≥ 6. (Tuned)`;
|
||||
if (sc.id === "s5-convergence") return `Hold equilibrium: assay spoke + balanced ecosystem sustained for 2 consecutive turns. (Tuned)`;
|
||||
return sc.teaches;
|
||||
}
|
||||
|
||||
function previewDetailsHTML(sc: Scenario, current: GameState, preview: GameState, action: RotationAction): string {
|
||||
const prefix = action.ring === "inner" ? "I" : action.ring === "middle" ? "M" : "O";
|
||||
const size = preview.rings[action.ring].tiles.length;
|
||||
const destinations = Array.from({ length: size }, (_, index) => {
|
||||
const destination = action.dir === "cw" ? (index + 1) % size : (index + size - 1) % size;
|
||||
return `${prefix}${index}→${prefix}${destination}`;
|
||||
}).join(" · ");
|
||||
const fields = [["N", "nutrient"], ["H", "heat"], ["T", "toxin"], ["P", "producer"], ["V", "grazer"], ["F", "phage"]] as const;
|
||||
const changes: string[] = [];
|
||||
for (const ring of ["outer", "middle", "inner"] as RingId[]) {
|
||||
for (let index = 0; index < current.rings[ring].tiles.length; index++) {
|
||||
const before = current.rings[ring].tiles[index];
|
||||
const after = preview.rings[ring].tiles[index];
|
||||
const deltas = fields.flatMap(([label, field]) => {
|
||||
const delta = after[field] - before[field];
|
||||
return delta ? [`${label}${delta > 0 ? "+" : ""}${delta}`] : [];
|
||||
});
|
||||
if (deltas.length) changes.push(`${lbl(ring, index)} ${deltas.join(" ")}`);
|
||||
}
|
||||
}
|
||||
return `<p class="prediction"><b>Predicted turn ${preview.turn}:</b> ${objectiveProgress(sc, preview)}</p>
|
||||
<details class="relocation"><summary>Payload destinations · ${action.ring} ${action.dir} · gates g0–g5 stay fixed</summary><p>${destinations}</p></details>
|
||||
<div class="delta-list" aria-label="Exact tile deltas"><b>Exact deltas</b><p>${changes.join(" · ") || "No value changes"}</p></div>`;
|
||||
}
|
||||
|
||||
function objectiveProgress(sc: Scenario, state: GameState): string {
|
||||
const tiles = ["inner", "middle", "outer"].flatMap((ring) => state.rings[ring as RingId].tiles);
|
||||
const total = (field: "producer" | "grazer" | "phage" | "toxin") => tiles.reduce((sum, tile) => sum + tile[field], 0);
|
||||
const occupied = (field: "producer" | "grazer") => tiles.filter((tile) => tile[field] > 0).length;
|
||||
if (state.outcome !== "playing") return outcomeLabel(state.outcome);
|
||||
if (sc.id === "s1-heat") return `I0 P ${state.rings.inner.tiles[0].producer}/4 · total P ${total("producer")}/12`;
|
||||
if (sc.id === "s2-hunger") return `P ${total("producer")}/8 on ${occupied("producer")}/3 tiles · V ${total("grazer")}/4 on ${occupied("grazer")}/2 tiles`;
|
||||
if (sc.id === "s3-toxin") return `toxin ${total("toxin")}/8 max · P+V ${total("producer") + total("grazer")}/8`;
|
||||
if (sc.id === "s4-immunity") return `I0 V ${state.rings.inner.tiles[0].grazer}/4 · total P ${total("producer")}/6`;
|
||||
const assay = [state.rings.inner.tiles[0], state.rings.middle.tiles[0], state.rings.outer.tiles[0]].filter((tile) => tile.producer + tile.grazer > 0).length;
|
||||
return `assay ${assay}/3 · P ${total("producer")} · V ${total("grazer")} · F ${total("phage")} · toxin ${total("toxin")} · sustained ${state.consecutiveObjectiveTurns}/2`;
|
||||
}
|
||||
|
||||
function adaptationSummary(pressure: PressureId): string {
|
||||
if (pressure === "heat") return "Benefit: prevents heat loss. Cost: no population gain while hot. Spillover: cools the shared tile.";
|
||||
if (pressure === "hunger") return "Benefit: prevents hunger loss. Cost: dormant carriers cannot migrate. Spillover: dormant prey becomes inedible.";
|
||||
if (pressure === "toxin") return "Benefit: prevents toxin loss. Cost: pays 1 nutrient. Spillover: detoxifies the shared tile.";
|
||||
return "Benefit: avoids immune selection. Cost: predators remove 2 cloaked prey. Spillover: immune nodes retarget the other lineage.";
|
||||
}
|
||||
|
||||
function outcomeLabel(o: GameState["outcome"]): string {
|
||||
return o === "won" ? "Objective achieved" : o === "collapsed" ? "Ecosystem collapsed" : o === "expired" ? "Turn limit expired" : "resolved";
|
||||
}
|
||||
|
||||
function predictLabel(events: GameEvent[]): string {
|
||||
const parts: string[] = [];
|
||||
for (const e of events) {
|
||||
if (e.phase === "evolution") parts.push(`unlocks ${TRAIT_NAME[e.pressure]}`);
|
||||
if (e.phase === "env") parts.push(`${PRESSURE_META[e.pressure].label} response`);
|
||||
if (e.phase === "outcome" && e.outcome !== "playing") parts.push(`→ ${e.outcome}`);
|
||||
}
|
||||
return parts.slice(0, 3).join(", ") || "tick resolves";
|
||||
}
|
||||
|
||||
function costText(p: PressureId): string {
|
||||
if (p === "heat") return "no growth/feeding while hot";
|
||||
if (p === "hunger") return "dormant when starving (inedible, can't migrate)";
|
||||
if (p === "toxin") return "pays 1 nutrient under toxin";
|
||||
return "predator removes 2 cloaked prey at immune nodes";
|
||||
}
|
||||
|
||||
function eventsToText(events: GameEvent[]): string {
|
||||
if (events.length === 0) return `<li class="muted">Select a rotation to preview the tick.</li>`;
|
||||
const out: string[] = [];
|
||||
for (const e of events) {
|
||||
const t = eventLine(e);
|
||||
if (t) out.push(`<li>${t}</li>`);
|
||||
}
|
||||
return (out.length ? out : [`<li class="muted">No notable changes.</li>`]).join("");
|
||||
}
|
||||
|
||||
function eventLine(e: GameEvent): string | null {
|
||||
switch (e.phase) {
|
||||
case "rotate": return `<b>Rotate</b> ${e.ring} ${e.dir}.`;
|
||||
case "flow": return `Flow ${e.field} at ${lbl(e.ring, e.index)} (${e.delta >= 0 ? "+" : ""}${e.delta}).`;
|
||||
case "overflow": return `Overflow discarded: ${e.amount} ${e.field} at ${lbl(e.ring, e.index)}.`;
|
||||
case "growth": return e.suppressed ? `Heat Shield cost: growth suppressed at ${lbl(e.ring, e.index)}.` : `Producer +${e.gained} at ${lbl(e.ring, e.index)}.`;
|
||||
case "feed": return e.predator === "grazer" ? `Grazer ate ${e.preyRemoved}${e.preyRemoved === 2 ? " cloaked (Cloak cost)" : ""} producer at ${lbl(e.ring, e.index)}${e.suppressed ? "; Heat Shield cost suppressed grazer gain" : ""}.` : e.phageStarve ? `Phage starved at ${lbl(e.ring, e.index)}.` : `Phage ate ${e.preyRemoved}${e.preyRemoved === 2 ? " cloaked (Cloak cost)" : ""} grazer at ${lbl(e.ring, e.index)}.`;
|
||||
case "migrate": return `${e.species} migrated ${e.from}→${e.to}.`;
|
||||
case "evolution": return `<b>${e.lineage === "producer" ? "Lumiflora" : "Vellea"} unlocked ${TRAIT_NAME[e.pressure]}.</b> ${adaptationSummary(e.pressure)}`;
|
||||
case "env": return `<b>${PRESSURE_META[e.pressure].label} response active</b>: ${PRESSURE_META[e.pressure].response}.`;
|
||||
case "fixture": return `${e.kind} at ${lbl(e.ring, e.index)}: ${e.field} ${e.delta >= 0 ? "+" : ""}${e.delta}.`;
|
||||
case "fixtureGlobal": return null;
|
||||
case "immuneSelect": return `Immune node at ${lbl(e.ring, e.index)} targets ${e.lineage}${e.retarget ? " (retarget spillover)" : ""}.`;
|
||||
case "pressureInc": return `${e.lineage} ${e.pressure} track → ${e.to}/3.`;
|
||||
case "consequence":
|
||||
if (e.kind === "prevented") return `Benefit active: ${e.lineage} ${e.pressure} loss prevented at ${lbl(e.ring, e.index)}.`;
|
||||
if (e.kind === "payNutrient") return `${e.lineage} pays 1 nutrient (Efflux) at ${lbl(e.ring, e.index)}.`;
|
||||
if (e.kind === "payPop") return `${e.lineage} loses ${e.amount} (Efflux, no nutrient) at ${lbl(e.ring, e.index)}.`;
|
||||
return `${e.lineage} loses ${e.amount} to ${e.pressure} at ${lbl(e.ring, e.index)}.`;
|
||||
case "spillover": return `Spillover: ${e.field} −${e.reduced} at ${lbl(e.ring, e.index)} (${e.pressure} adaptation).`;
|
||||
case "adaptation": return e.effect === "cost"
|
||||
? `Cost active: dormant ${e.lineage} could not migrate at ${lbl(e.ring, e.index)}.`
|
||||
: `Spillover active: dormant ${e.lineage} was inedible at ${lbl(e.ring, e.index)}.`;
|
||||
case "outcome": return e.outcome === "playing" ? null : `<b>${outcomeLabel(e.outcome)}.</b>`;
|
||||
}
|
||||
}
|
||||
|
||||
function lbl(ring: RingId, index: number): string {
|
||||
const c = ring === "inner" ? "I" : ring === "middle" ? "M" : "O";
|
||||
return `${c}${index}`;
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// Renders the full SVG board from state + scenario fixtures (+ optional preview overlay).
|
||||
import type { GameState, RingId, Scenario, RotationAction, FixtureKind } from "../domain/types.ts";
|
||||
import { PRESSURE_META } from "../domain/types.ts";
|
||||
import { fixturesByTile } from "../domain/scenarios.ts";
|
||||
import { gateIndex, isOnGate } from "../domain/core.ts";
|
||||
import { CX, CY, RING_R, TILE_R, RING_COLOR, hexPoints, tileCenter, tileLabel, VIEW } from "./geom.ts";
|
||||
import { glyphFixture, glyphPressure, glyphSpecies } from "./svg.ts";
|
||||
|
||||
export type RenderOpts = {
|
||||
previewState?: GameState | null;
|
||||
previewAction?: RotationAction | null;
|
||||
flowEvents?: { ring: RingId; index: number; field: "nutrient" | "toxin"; tangential: number; radial: number }[];
|
||||
selectedRing?: RingId | null;
|
||||
};
|
||||
|
||||
|
||||
export function renderBoard(state: GameState, scenario: Scenario, opts: RenderOpts = {}): string {
|
||||
const fx = fixturesByTile(scenario);
|
||||
const fixturesAt = (ring: RingId, index: number): { kind: FixtureKind; label?: string }[] =>
|
||||
(fx.get(`${ring}:${index}`) ?? []).map((f) => ({ kind: f.kind as FixtureKind, label: f.label }));
|
||||
const preview = opts.previewState;
|
||||
|
||||
// ---- gate connectors (drawn first, behind tiles) ----
|
||||
const gates: string[] = [];
|
||||
for (let g = 0; g < 6; g++) {
|
||||
const ip = tileCenter("inner", gateIndex("inner", g));
|
||||
const mp = tileCenter("middle", gateIndex("middle", g));
|
||||
const op = tileCenter("outer", gateIndex("outer", g));
|
||||
const active = opts.selectedRing ? true : false;
|
||||
gates.push(
|
||||
`<line x1="${op[0].toFixed(1)}" y1="${op[1].toFixed(1)}" x2="${ip[0].toFixed(1)}" y2="${ip[1].toFixed(1)}" stroke="url(#gateGlow)" stroke-width="${active ? 5 : 3}" stroke-linecap="round" opacity="0.55"/>`,
|
||||
);
|
||||
void mp;
|
||||
}
|
||||
|
||||
// ---- ring guide polygons ----
|
||||
const guides: string[] = [];
|
||||
for (const ring of ["inner", "middle", "outer"] as RingId[]) {
|
||||
const pts: string[] = [];
|
||||
for (let k = 0; k < 6; k++) {
|
||||
const ang = (90 - 60 * k) * Math.PI / 180;
|
||||
const R = RING_R[ring] + TILE_R[ring] * 0.9;
|
||||
pts.push(`${(CX + R * Math.cos(ang)).toFixed(1)},${(CY - R * Math.sin(ang)).toFixed(1)}`);
|
||||
}
|
||||
guides.push(`<polygon points="${pts.join(" ")}" fill="none" stroke="${RING_COLOR[ring]}" stroke-width="1" stroke-dasharray="3 5" opacity="0.25"/>`);
|
||||
}
|
||||
|
||||
// ---- tiles ----
|
||||
const tiles: string[] = [];
|
||||
for (const ring of ["outer", "middle", "inner"] as RingId[]) {
|
||||
const tr = TILE_R[ring];
|
||||
for (let i = 0; i < state.rings[ring].tiles.length; i++) {
|
||||
const [x, y] = tileCenter(ring, i);
|
||||
const current = state.rings[ring].tiles[i];
|
||||
const c = preview?.rings[ring].tiles[i] ?? current;
|
||||
const onGate = isOnGate(ring, i);
|
||||
const label = tileLabel(ring, i);
|
||||
|
||||
// heat rim glow
|
||||
const heatGlow = c.heat > 0 ? `filter="url(#heatGlow)" ` : "";
|
||||
const fillCol = ring === "inner" ? "#10243a" : ring === "middle" ? "#152039" : "#0f1c33";
|
||||
// nutrient liquid level at base (blue), toxin level (green)
|
||||
const baseY = y + tr * 0.55;
|
||||
const lvlH = tr * 1.1;
|
||||
const nutH = (c.nutrient / 6) * lvlH;
|
||||
const toxH = (c.toxin / 6) * lvlH;
|
||||
const clipId = `clip-${ring}-${i}`;
|
||||
const shownState = preview ?? state;
|
||||
const adapted = (c.producer > 0 && Object.values(shownState.lineage.producer.unlocked).some(Boolean)) ||
|
||||
(c.grazer > 0 && Object.values(shownState.lineage.grazer.unlocked).some(Boolean));
|
||||
const resources = ([['N', c.nutrient], ['H', c.heat], ['T', c.toxin]] as [string, number][]).filter(([, value]) => value > 0).map(([name, value]) => `${name}${value}`).join(" ");
|
||||
const resourceText = resources ? `<text x="${x.toFixed(1)}" y="${(y + tr * 0.62).toFixed(1)}" text-anchor="middle" font-size="${ring === "inner" ? 10 : 8}" fill="#e6edf7" font-weight="600">${resources}</text>` : "";
|
||||
const adaptedMark = adapted ? `<text class="adapted-tag" x="${(x + tr * 0.55).toFixed(1)}" y="${(y - tr * 0.55).toFixed(1)}" font-size="${ring === "inner" ? 12 : 10}" fill="#fff" font-weight="800">✓</text>` : "";
|
||||
|
||||
// preview delta highlight
|
||||
let deltaMark = "";
|
||||
if (preview) {
|
||||
const fields = [["N", "nutrient"], ["H", "heat"], ["T", "toxin"], ["P", "producer"], ["V", "grazer"], ["F", "phage"]] as const;
|
||||
const changes = fields.flatMap(([label, field]) => {
|
||||
const delta = c[field] - current[field];
|
||||
return delta ? [`${label}${delta > 0 ? "+" : ""}${delta}`] : [];
|
||||
});
|
||||
if (changes.length) {
|
||||
deltaMark = `<text class="tile-delta" x="${x.toFixed(1)}" y="${(y - tr - 4).toFixed(1)}" text-anchor="middle" font-size="${ring === "inner" ? 9 : 7}" fill="#ffe08a" font-weight="700">${changes.join(" ")}</text>`;
|
||||
}
|
||||
}
|
||||
|
||||
// species glyphs + counts
|
||||
let entities = "";
|
||||
const gs = tr * 0.5;
|
||||
if (c.producer > 0) entities += glyphSpecies("producer", x - tr * 0.32, y - tr * 0.18, gs);
|
||||
if (c.grazer > 0) entities += glyphSpecies("grazer", x + tr * 0.30, y - tr * 0.18, gs * 0.95);
|
||||
if (c.phage > 0) entities += glyphSpecies("phage", x, y + tr * 0.22, gs * 0.85);
|
||||
const counts: string[] = [];
|
||||
if (c.producer > 0) counts.push(`<tspan fill="#7fff8a">P${c.producer}</tspan>`);
|
||||
if (c.grazer > 0) counts.push(`<tspan fill="#ffc46a">V${c.grazer}</tspan>`);
|
||||
if (c.phage > 0) counts.push(`<tspan fill="#ff9ec7">F${c.phage}</tspan>`);
|
||||
const countText = counts.length ? `<text x="${x.toFixed(1)}" y="${(y + tr * 0.95).toFixed(1)}" text-anchor="middle" font-size="${ring === "inner" ? 12 : 10}" font-weight="700">${counts.join(" ")}</text>` : "";
|
||||
|
||||
// fixtures
|
||||
let fixG = "";
|
||||
const tileFixtures = fixturesAt(ring, i);
|
||||
const fixtureDescription = tileFixtures.length ? `, fixtures: ${tileFixtures.map((fixture) => fixture.label ?? fixture.kind).join(", ")}` : "";
|
||||
for (const f of tileFixtures) {
|
||||
if (f.kind === "objective") continue; // drawn separately subtle
|
||||
fixG += glyphFixture(f.kind, x, y - tr * 0.0, tr * 0.7);
|
||||
}
|
||||
// objective marker as a faint reticle behind
|
||||
const objF = tileFixtures.find((f) => f.kind === "objective");
|
||||
const objMark = objF ? glyphFixture("objective", x, y, tr * 1.15) : "";
|
||||
|
||||
tiles.push(`
|
||||
<g class="tile${adapted ? " adapted" : ""}" role="img" aria-label="${label}: nutrient ${c.nutrient}, heat ${c.heat}, toxin ${c.toxin}, producer ${c.producer}, grazer ${c.grazer}, phage ${c.phage}${fixtureDescription}${adapted ? ", adapted" : ""}" data-ring="${ring}" data-index="${i}" data-values="${c.nutrient},${c.heat},${c.toxin},${c.producer},${c.grazer},${c.phage}">
|
||||
${objMark}
|
||||
<polygon points="${hexPoints(x, y, tr)}" ${heatGlow}fill="${fillCol}" stroke="${adapted ? "#ffffff" : onGate ? RING_COLOR[ring] : "#2a3b55"}" stroke-width="${adapted ? 3 : onGate ? 2.2 : 1.2}"/>
|
||||
<defs><clipPath id="${clipId}"><polygon points="${hexPoints(x, y, tr * 0.96)}"/></clipPath></defs>
|
||||
${nutH > 0 ? `<rect x="${(x - tr*0.96).toFixed(1)}" y="${(baseY - nutH).toFixed(1)}" width="${(tr*1.92).toFixed(1)}" height="${nutH.toFixed(1)}" fill="#1f6fd6" opacity="0.32" clip-path="url(#${clipId})"/>` : ""}
|
||||
${toxH > 0 ? `<rect x="${(x - tr*0.96).toFixed(1)}" y="${(baseY - toxH).toFixed(1)}" width="${(tr*1.92).toFixed(1)}" height="${toxH.toFixed(1)}" fill="#5fbf4a" opacity="0.40" clip-path="url(#${clipId})"/>` : ""}
|
||||
${c.heat > 0 ? `<polygon points="${hexPoints(x, y, tr)}" fill="none" stroke="#ff8a4c" stroke-width="${1 + c.heat * 0.4}" opacity="${0.3 + c.heat * 0.1}"/>` : ""}
|
||||
${fixG}
|
||||
${entities}
|
||||
${countText}
|
||||
${resourceText}
|
||||
${adaptedMark}
|
||||
<text x="${(x - tr*0.78).toFixed(1)}" y="${(y - tr*0.82).toFixed(1)}" font-size="${ring === "inner" ? 9 : 8}" fill="#6f86a8">${label}</text>
|
||||
${deltaMark}
|
||||
</g>`);
|
||||
}
|
||||
}
|
||||
|
||||
// center hub
|
||||
const hub = `<circle cx="${CX}" cy="${CY}" r="34" fill="#0a1426" stroke="#2a3b55"/><text x="${CX}" y="${(CY+4).toFixed(1)}" text-anchor="middle" font-size="11" fill="#7d97bf">ADAPTIVE</text><text x="${CX}" y="${(CY+16).toFixed(1)}" text-anchor="middle" font-size="11" fill="#7d97bf">LOOP</text>`;
|
||||
|
||||
// ---- preview flow arrows (SPEC §12): tangential chevrons + inward radial arrows ----
|
||||
const flowArrows: string[] = [];
|
||||
if (opts.flowEvents && opts.flowEvents.length) {
|
||||
const dirOf = (ring: RingId) => w_ringDir(ring);
|
||||
for (const fe of opts.flowEvents) {
|
||||
const [x, y] = tileCenter(fe.ring, fe.index);
|
||||
const tr = TILE_R[fe.ring];
|
||||
const col = fe.field === "nutrient" ? "#5fb0ff" : "#9fe06a";
|
||||
if (fe.tangential > 0) {
|
||||
// chevron along the ring direction (cw = clockwise arc)
|
||||
const cw = dirOf(fe.ring) === "cw";
|
||||
const dx = cw ? tr * 0.5 : -tr * 0.5;
|
||||
flowArrows.push(`<path d="M ${(x - dx).toFixed(1)} ${(y - tr*0.95).toFixed(1)} l ${dx.toFixed(1)} ${(tr*0.5).toFixed(1)} l ${dx.toFixed(1)} ${(-tr*0.5).toFixed(1)}" fill="none" stroke="${col}" stroke-width="2.2" stroke-linecap="round" opacity="0.95"><title>${fe.field} tangential flow at ${tileLabel(fe.ring, fe.index)}</title></path>`);
|
||||
}
|
||||
if (fe.radial > 0) {
|
||||
// inward arrow toward center
|
||||
const ia = Math.atan2(CY - y, CX - x);
|
||||
const ax = x + Math.cos(ia) * tr * 0.4, ay = y + Math.sin(ia) * tr * 0.4;
|
||||
const bx = x + Math.cos(ia) * tr * 0.95, by = y + Math.sin(ia) * tr * 0.95;
|
||||
flowArrows.push(`<line x1="${bx.toFixed(1)}" y1="${by.toFixed(1)}" x2="${ax.toFixed(1)}" y2="${ay.toFixed(1)}" stroke="${col}" stroke-width="2.4" stroke-linecap="round" opacity="0.95" marker-end="url(#flowHead)"><title>${fe.field} radial-inward flow at ${tileLabel(fe.ring, fe.index)}</title></line>`);
|
||||
}
|
||||
}
|
||||
}
|
||||
function w_ringDir(ring: RingId): string { return (preview ?? state).rings[ring].direction; }
|
||||
|
||||
const ledgerState = preview ?? state;
|
||||
const ledger = (["inner", "middle", "outer"] as RingId[]).flatMap((ring) => ledgerState.rings[ring].tiles.flatMap((chamber, index) => {
|
||||
const fixtureNames = fixturesAt(ring, index).map((fixture) => fixture.label ?? fixture.kind);
|
||||
const occupied = Object.values(chamber).some((value) => value > 0);
|
||||
if (!occupied && fixtureNames.length === 0) return [];
|
||||
return [`<span><b>${tileLabel(ring, index)}</b> N${chamber.nutrient} H${chamber.heat} T${chamber.toxin} P${chamber.producer} V${chamber.grazer} F${chamber.phage}${fixtureNames.length ? ` · ${fixtureNames.join(", ")}` : ""}</span>`];
|
||||
})).join("");
|
||||
const ledgerHTML = `<details class="tile-ledger" open><summary>Readable tile state</summary><div>${ledger}</div></details>`;
|
||||
|
||||
return `<svg viewBox="0 0 ${VIEW} ${VIEW}" role="group" aria-label="Culture board: three concentric hexagonal rings linked by six radial gates${opts.flowEvents?.length ? "; preview shows flow arrows" : ""}" class="board-svg">
|
||||
<defs>
|
||||
<linearGradient id="gateGlow" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" stop-color="#7fffd6"/><stop offset="50%" stop-color="#9d7bff"/><stop offset="100%" stop-color="#5fd0ff"/>
|
||||
</linearGradient>
|
||||
<filter id="heatGlow" x="-50%" y="-50%" width="200%" height="200%">
|
||||
<feGaussianBlur stdDeviation="2.2" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
|
||||
</filter>
|
||||
<marker id="flowHead" markerWidth="7" markerHeight="7" refX="3.5" refY="3.5" orient="auto"><path d="M0,0 L7,3.5 L0,7 z" fill="#9fe06a"/></marker>
|
||||
</defs>
|
||||
<rect x="0" y="0" width="${VIEW}" height="${VIEW}" fill="#070d18"/>
|
||||
${guides.join("")}
|
||||
${gates.join("")}
|
||||
${tiles.join("")}
|
||||
${flowArrows.join("")}
|
||||
${hub}
|
||||
</svg>${ledgerHTML}`;
|
||||
}
|
||||
|
||||
/** Compact textual status of pressure tracks + lineage traits for the rail. */
|
||||
export function renderTraits(state: GameState): string {
|
||||
const rows: string[] = [];
|
||||
for (const lin of ["producer", "grazer"] as const) {
|
||||
const L = state.lineage[lin];
|
||||
const name = lin === "producer" ? "Lumiflora" : "Vellea";
|
||||
const cells = (["heat", "hunger", "toxin", "immunity"] as const).map((p) => {
|
||||
const v = L.pressure[p];
|
||||
const u = L.unlocked[p];
|
||||
const bar = "▰".repeat(v) + "▱".repeat(3 - v);
|
||||
return `<span class="ptrack ${u ? "adapted" : ""}" aria-label="${name} ${PRESSURE_META[p].label} ${v} of 3${u ? ", adapted" : ""}"><svg viewBox="0 0 24 24" aria-hidden="true">${glyphPressure(p, 12, 12, 18)}</svg><span>${PRESSURE_META[p].label}</span><b>${bar}${u ? "✓" : ""}</b></span>`;
|
||||
});
|
||||
rows.push(`<div class="lineage"><span class="lin-name">${name}</span>${cells.join("")}</div>`);
|
||||
}
|
||||
return rows.join("");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// Board geometry: three concentric hexagonal rings + six radial gates (SPEC §4, docs/board-layout.md).
|
||||
import type { RingId } from "../domain/types.ts";
|
||||
|
||||
export const VIEW = 640;
|
||||
export const CX = VIEW / 2;
|
||||
export const CY = VIEW / 2;
|
||||
|
||||
// Vertex radius (center to vertex) per ring.
|
||||
export const RING_R: Record<RingId, number> = { inner: 96, middle: 168, outer: 246 };
|
||||
// Pointy-top hex tile "radius" (circumscribed) per ring.
|
||||
export const TILE_R: Record<RingId, number> = { inner: 30, middle: 23, outer: 17.5 };
|
||||
|
||||
const DEG = Math.PI / 180;
|
||||
|
||||
/** Vertex k (0..5, clockwise from top) of a hexagonal perimeter at radius R. */
|
||||
function vertex(R: number, k: number): [number, number] {
|
||||
const ang = (90 - 60 * k) * DEG;
|
||||
return [CX + R * Math.cos(ang), CY - R * Math.sin(ang)];
|
||||
}
|
||||
|
||||
/** Center position [x,y] of tile `index` in `ring`. */
|
||||
export function tileCenter(ring: RingId, index: number): [number, number] {
|
||||
const r = ring === "inner" ? 1 : ring === "middle" ? 2 : 3;
|
||||
const R = RING_R[ring];
|
||||
const group = Math.floor(index / r);
|
||||
const frac = (index % r) / r;
|
||||
const a = vertex(R, group % 6);
|
||||
const b = vertex(R, (group + 1) % 6);
|
||||
return [a[0] + (b[0] - a[0]) * frac, a[1] + (b[1] - a[1]) * frac];
|
||||
}
|
||||
|
||||
/** Pointy-top hexagon polygon points string centered at (x,y) with circumradius s. */
|
||||
export function hexPoints(x: number, y: number, s: number): string {
|
||||
const pts: string[] = [];
|
||||
for (let k = 0; k < 6; k++) {
|
||||
const ang = (90 - 60 * k) * DEG;
|
||||
pts.push(`${(x + s * Math.cos(ang)).toFixed(2)},${(y - s * Math.sin(ang)).toFixed(2)}`);
|
||||
}
|
||||
return pts.join(" ");
|
||||
}
|
||||
|
||||
|
||||
/** Label for a tile, e.g. "I0", "M2", "O3". */
|
||||
export function tileLabel(ring: RingId, index: number): string {
|
||||
const c = ring === "inner" ? "I" : ring === "middle" ? "M" : "O";
|
||||
return `${c}${index}`;
|
||||
}
|
||||
|
||||
/** Ring color family. */
|
||||
export const RING_COLOR: Record<RingId, string> = {
|
||||
inner: "#5fd0ff",
|
||||
middle: "#9d7bff",
|
||||
outer: "#7fffd6",
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
// Procedural SVG glyphs for species, fixtures, and pressure icons (SPEC §13).
|
||||
// Each returns inner SVG markup (shapes) centered at (x,y) at the given scale.
|
||||
import type { FixtureKind, PressureId } from "../domain/types.ts";
|
||||
|
||||
// ---------- Species ----------
|
||||
|
||||
/** Producer "Lumiflora": 6-petal diatom/flower around a chloroplast center. Green. */
|
||||
export function glyphProducer(x: number, y: number, s: number): string {
|
||||
const petals = [];
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const a = (i * 60) * Math.PI / 180;
|
||||
const px = x + Math.cos(a) * s * 0.5;
|
||||
const py = y - Math.sin(a) * s * 0.5;
|
||||
petals.push(
|
||||
`<ellipse cx="${px.toFixed(1)}" cy="${py.toFixed(1)}" rx="${(s*0.30).toFixed(1)}" ry="${(s*0.16).toFixed(1)}" transform="rotate(${-i*60} ${px.toFixed(1)} ${py.toFixed(1)})" fill="#5fd97a" fill-opacity="0.85"/>`,
|
||||
);
|
||||
}
|
||||
return `<g>${petals.join("")}<circle cx="${x}" cy="${y}" r="${(s*0.22).toFixed(1)}" fill="#bdf56a"/><circle cx="${x}" cy="${y}" r="${(s*0.11).toFixed(1)}" fill="#2e8b3d"/></g>`;
|
||||
}
|
||||
|
||||
/** Grazer "Vellea": segmented crescent with cilia legs + mouth notch. Amber. */
|
||||
export function glyphGrazer(x: number, y: number, s: number): string {
|
||||
const cilia: string[] = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const t = (i + 1) / 4;
|
||||
const lx = x - s * 0.45 + t * s * 0.9;
|
||||
cilia.push(`<line x1="${lx.toFixed(1)}" y1="${y}" x2="${(lx+s*0.06).toFixed(1)}" y2="${(y+s*0.42).toFixed(1)}" stroke="#e6a23c" stroke-width="${(s*0.05).toFixed(1)}"/>`);
|
||||
cilia.push(`<line x1="${lx.toFixed(1)}" y1="${y}" x2="${(lx-s*0.06).toFixed(1)}" y2="${(y+s*0.42).toFixed(1)}" stroke="#e6a23c" stroke-width="${(s*0.05).toFixed(1)}"/>`);
|
||||
}
|
||||
return `<g>
|
||||
<path d="M ${(x-s*0.5).toFixed(1)} ${y} a ${ (s*0.5).toFixed(1)} ${(s*0.32).toFixed(1)} 0 0 0 ${(s).toFixed(1)} 0 a ${(s*0.34).toFixed(1)} ${(s*0.22).toFixed(1)} 0 0 0 ${(-s).toFixed(1)} 0 z" fill="#f3b34a" stroke="#c97f1e" stroke-width="${(s*0.05).toFixed(1)}"/>
|
||||
<path d="M ${(x+s*0.42).toFixed(1)} ${(y-s*0.04).toFixed(1)} l ${(s*0.14).toFixed(1)} ${(s*0.10).toFixed(1)} l ${(-s*0.14).toFixed(1)} ${(s*0.10).toFixed(1)} z" fill="#7a4a08"/>
|
||||
${cilia.join("")}
|
||||
</g>`;
|
||||
}
|
||||
|
||||
/** Phage: lunar-lander virus (hex capsid head + 6 leg spikes). Pink. */
|
||||
export function glyphPhage(x: number, y: number, s: number): string {
|
||||
const legs: string[] = [];
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const a = (i * 60 + 30) * Math.PI / 180;
|
||||
const x1 = x + Math.cos(a) * s * 0.5;
|
||||
const y1 = y + Math.sin(a) * s * 0.5;
|
||||
const x2 = x + Math.cos(a) * s * 0.78;
|
||||
const y2 = y + Math.sin(a) * s * 0.78;
|
||||
legs.push(`<line x1="${x1.toFixed(1)}" y1="${y1.toFixed(1)}" x2="${x2.toFixed(1)}" y2="${y2.toFixed(1)}" stroke="#ff6fae" stroke-width="${(s*0.07).toFixed(1)}"/><circle cx="${x2.toFixed(1)}" cy="${y2.toFixed(1)}" r="${(s*0.05).toFixed(1)}" fill="#ff6fae"/>`);
|
||||
}
|
||||
const hp = [];
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const a = (90 - 60 * i) * Math.PI / 180;
|
||||
hp.push(`${(x + Math.cos(a) * s * 0.45).toFixed(1)},${(y - Math.sin(a) * s * 0.45).toFixed(1)}`);
|
||||
}
|
||||
return `<g>${legs.join("")}<polygon points="${hp.join(" ")}" fill="#ff9ec7" stroke="#d63d86" stroke-width="${(s*0.05).toFixed(1)}"/><polygon points="${hp.slice(0,3).join(" ")}" fill="#ffd0e4" fill-opacity="0.7"/></g>`;
|
||||
}
|
||||
|
||||
export function glyphSpecies(id: "producer" | "grazer" | "phage", x: number, y: number, s: number): string {
|
||||
if (id === "producer") return glyphProducer(x, y, s);
|
||||
if (id === "grazer") return glyphGrazer(x, y, s);
|
||||
return glyphPhage(x, y, s);
|
||||
}
|
||||
|
||||
// ---------- Fixtures ----------
|
||||
|
||||
export function glyphFixture(kind: FixtureKind, x: number, y: number, s: number): string {
|
||||
switch (kind) {
|
||||
case "nutrientInlet": // pipette/valve dropping a bead (blue)
|
||||
return `<g>
|
||||
<rect x="${(x-s*0.14).toFixed(1)}" y="${(y-s*0.5).toFixed(1)}" width="${(s*0.28).toFixed(1)}" height="${(s*0.5).toFixed(1)}" rx="${(s*0.05).toFixed(1)}" fill="#3a6ea5" stroke="#8fb8e6"/>
|
||||
<polygon points="${(x-s*0.14).toFixed(1)},${y} ${(x+s*0.14).toFixed(1)},${y} ${x.toFixed(1)},${(y+s*0.22).toFixed(1)}" fill="#6fa8dc"/>
|
||||
<circle cx="${x}" cy="${(y+s*0.36).toFixed(1)}" r="${(s*0.12).toFixed(1)}" fill="#9fd0ff"/>
|
||||
</g>`;
|
||||
case "heatSource": // coiled filament radiating warm rays (orange)
|
||||
{ const rays: string[] = []; for (let i=0;i<8;i++){const a=(i*45)*Math.PI/180;rays.push(`<line x1="${(x+Math.cos(a)*s*0.55).toFixed(1)}" y1="${(y-Math.sin(a)*s*0.55).toFixed(1)}" x2="${(x+Math.cos(a)*s*0.8).toFixed(1)}" y2="${(y-Math.sin(a)*s*0.8).toFixed(1)}" stroke="#ff7a3c" stroke-width="${(s*0.05).toFixed(1)}"/>`);}
|
||||
return `<g>${rays.join("")}<path d="M ${(x-s*0.3).toFixed(1)} ${y} q ${(s*0.3).toFixed(1)} ${(-s*0.3).toFixed(1)} ${(s*0.6).toFixed(1)} 0 q ${(s*0.3).toFixed(1)} ${(s*0.3).toFixed(1)} ${(s*0.6).toFixed(1)} 0" fill="none" stroke="#ff9a5c" stroke-width="${(s*0.09).toFixed(1)}"/><circle cx="${x}" cy="${y}" r="${(s*0.13).toFixed(1)}" fill="#ffb347"/></g>`; }
|
||||
case "toxinInlet": // dropper of greenish droplet
|
||||
return `<g><polygon points="${(x-s*0.22).toFixed(1)},${(y-s*0.4).toFixed(1)} ${(x+s*0.22).toFixed(1)},${(y-s*0.4).toFixed(1)} ${x.toFixed(1)},${(y-s*0.1).toFixed(1)}" fill="#6b8f3a" stroke="#a7d977"/><path d="M ${(x-s*0.12).toFixed(1)} ${(y-s*0.42).toFixed(1)} l ${(s*0.24).toFixed(1)} 0 l 0 ${(-s*0.18).toFixed(1)} l ${(-s*0.24).toFixed(1)} 0 z" fill="#8a6fbf"/><circle cx="${x}" cy="${(y+s*0.18).toFixed(1)}" r="${(s*0.15).toFixed(1)}" fill="#9fe06a" stroke="#5e8a2e" stroke-width="${(s*0.04).toFixed(1)}"/></g>`;
|
||||
case "drain": // funnel siphon
|
||||
return `<g><polygon points="${(x-s*0.34).toFixed(1)},${(y-s*0.34).toFixed(1)} ${(x+s*0.34).toFixed(1)},${(y-s*0.34).toFixed(1)} ${x.toFixed(1)},${(y+s*0.05).toFixed(1)}" fill="#445" stroke="#7d8aa0"/><rect x="${(x-s*0.07).toFixed(1)}" y="${(y+s*0.05).toFixed(1)}" width="${(s*0.14).toFixed(1)}" height="${(s*0.3).toFixed(1)}" fill="#6a7588"/><path d="M ${(x-s*0.26).toFixed(1)} ${(y-s*0.32).toFixed(1)} q ${(s*0.26).toFixed(1)} ${(s*0.16).toFixed(1)} ${(s*0.52).toFixed(1)} 0" fill="none" stroke="#9fe06a" stroke-width="${(s*0.06).toFixed(1)}"/></g>`;
|
||||
case "immuneNode": // sentinel eye/lens (cyan)
|
||||
return `<g><ellipse cx="${x}" cy="${y}" rx="${(s*0.4).toFixed(1)}" ry="${(s*0.24).toFixed(1)}" fill="#10303a" stroke="#5fd0ff" stroke-width="${(s*0.05).toFixed(1)}"/><circle cx="${x}" cy="${y}" r="${(s*0.16).toFixed(1)}" fill="#5fd0ff"/><circle cx="${(x-s*0.05).toFixed(1)}" cy="${(y-s*0.05).toFixed(1)}" r="${(s*0.06).toFixed(1)}" fill="#eafdff"/></g>`;
|
||||
case "objective": // targeting reticle (gold)
|
||||
return `<g><circle cx="${x}" cy="${y}" r="${(s*0.42).toFixed(1)}" fill="none" stroke="#ffd24a" stroke-width="${(s*0.05).toFixed(1)}" stroke-dasharray="${(s*0.14).toFixed(1)} ${(s*0.1).toFixed(1)}"/><circle cx="${x}" cy="${y}" r="${(s*0.10).toFixed(1)}" fill="#ffd24a"/><line x1="${(x-s*0.55).toFixed(1)}" y1="${y}" x2="${(x-s*0.2).toFixed(1)}" y2="${y}" stroke="#ffd24a" stroke-width="${(s*0.04).toFixed(1)}"/><line x1="${(x+s*0.2).toFixed(1)}" y1="${y}" x2="${(x+s*0.55).toFixed(1)}" y2="${y}" stroke="#ffd24a" stroke-width="${(s*0.04).toFixed(1)}"/><line x1="${x}" y1="${(y-s*0.55).toFixed(1)}" x2="${x}" y2="${(y-s*0.2).toFixed(1)}" stroke="#ffd24a" stroke-width="${(s*0.04).toFixed(1)}"/><line x1="${x}" y1="${(y+s*0.2).toFixed(1)}" x2="${x}" y2="${(y+s*0.55).toFixed(1)}" stroke="#ffd24a" stroke-width="${(s*0.04).toFixed(1)}"/></g>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Pressure icons ----------
|
||||
|
||||
export function glyphPressure(p: PressureId, x: number, y: number, s: number): string {
|
||||
switch (p) {
|
||||
case "heat": { // radiating sun rays (warm)
|
||||
const r: string[] = []; for (let i=0;i<8;i++){const a=(i*45)*Math.PI/180;r.push(`<line x1="${x}" y1="${y}" x2="${(x+Math.cos(a)*s*0.5).toFixed(1)}" y2="${(y-Math.sin(a)*s*0.5).toFixed(1)}" stroke="#ff8a4c" stroke-width="${(s*0.06).toFixed(1)}"/>`);}
|
||||
return `<g>${r.join("")}<circle cx="${x}" cy="${y}" r="${(s*0.2).toFixed(1)}" fill="#ff8a4c"/></g>`; }
|
||||
case "hunger": // waning crescent (violet)
|
||||
return `<g><path d="M ${(x+s*0.28).toFixed(1)} ${y} a ${(s*0.4).toFixed(1)} ${(s*0.4).toFixed(1)} 0 1 0 0 ${(s*0.001).toFixed(1)} z" fill="#b388ff"/><path d="M ${(x+s*0.28).toFixed(1)} ${y} a ${(s*0.28).toFixed(1)} ${(s*0.28).toFixed(1)} 0 1 1 0 ${(s*0.001).toFixed(1)} z" fill="#0d1117"/></g>`;
|
||||
case "toxin": // skull-and-drop (green)
|
||||
return `<g><path d="M ${(x-s*0.18).toFixed(1)} ${(y+s*0.34).toFixed(1)} q ${(s*0.18).toFixed(1)} ${(-s*0.1).toFixed(1)} ${(s*0.36).toFixed(1)} 0 q ${(-s*0.05).toFixed(1)} ${(s*0.18).toFixed(1)} ${(-s*0.36).toFixed(1)} 0 z" fill="#7fd66b"/><circle cx="${(x-s*0.07).toFixed(1)}" cy="${(y-s*0.08).toFixed(1)}" r="${(s*0.10).toFixed(1)}" fill="#0d1117"/><circle cx="${(x+s*0.07).toFixed(1)}" cy="${(y-s*0.08).toFixed(1)}" r="${(s*0.10).toFixed(1)}" fill="#0d1117"/></g>`;
|
||||
case "immunity": // shield (cyan)
|
||||
return `<g><path d="M ${x} ${(y-s*0.4).toFixed(1)} l ${(s*0.34).toFixed(1)} ${(s*0.12).toFixed(1)} l 0 ${(s*0.26).toFixed(1)} q 0 ${(s*0.22).toFixed(1)} ${(-s*0.34).toFixed(1)} ${(s*0.14).toFixed(1)} q ${(-s*0.34).toFixed(1)} ${(-s*0.22).toFixed(1)} 0 ${(-s*0.14).toFixed(1)} z" fill="#5fd0ff" fill-opacity="0.5" stroke="#5fd0ff" stroke-width="${(s*0.05).toFixed(1)}"/><path d="M ${(x-s*0.12).toFixed(1)} ${y} l ${(s*0.10).toFixed(1)} ${(s*0.12).toFixed(1)} l ${(s*0.18).toFixed(1)} ${(-s*0.2).toFixed(1)}" fill="none" stroke="#0d1117" stroke-width="${(s*0.06).toFixed(1)}"/></g>`;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user