primordial-soup/test/engine.test.js

427 lines
15 KiB
JavaScript

import test from "node:test";
import assert from "node:assert/strict";
import * as E from "../engine/index.js";
import { prepared, chapters } from "../viewer/tutorials.js";
import { createTutorial } from "@boardgamers/protocol/tutorial";
const act = (s, type, extra = {}) => {
const m = E.legalMoves(s).find(
(m) =>
m.type === type && Object.entries(extra).every(([k, v]) => m[k] === v),
);
assert.ok(m, `Missing ${type}: ${JSON.stringify(s.tasks[0])}`);
return E.move(s, m, E.currentPlayer(s));
};
function conserved(s) {
for (let p = 0; p < s.players.length; p++) {
assert.ok(s.players[p].bp >= 0);
const carried = s.tasks
.filter((t) => t.kind === "carry")
.reduce((sum, t) => sum + t.cargo.filter((c) => c === p).length, 0);
assert.equal(
s.food.reduce((sum, v) => sum + v[p], s.supply[p]) + carried,
55,
);
assert.ok(s.food.every((v) => Number.isInteger(v[p]) && v[p] >= 0));
const own = E.colony(s, p);
assert.ok(own.length <= 7);
assert.equal(new Set(own.map((a) => a.n)).size, own.length);
for (const a of own) {
assert.ok(E.CELLS.includes(a.cell));
assert.ok(a.hp >= 0);
}
}
}
test("19 spaces, finite food, deterministic setup, and secret random state", () => {
assert.equal(E.CELLS.length, 19);
const s = E.init(4, [], {}, "seed");
assert.deepEqual(s, E.init(4, [], {}, "seed"));
assert.equal(s.players[0].bp, 4);
conserved(s);
const view = E.stripSecret(s);
assert.ok(!("_seed" in view));
assert.ok(!("_deck" in view));
assert.ok(!("_counter" in view));
assert.equal(view.moves.length, 4);
const before = structuredClone(s);
assert.throws(() =>
E.move(s, { type: "score", score: 1 }, (E.currentPlayer(s) + 1) % 4),
);
assert.deepEqual(s, before);
});
test("setup is snake order; only first amoebas in four-player games are injured", () => {
for (const n of [3, 4]) {
let s = E.init(n, [], {}, "setup");
while (s.phase === "setup-score") s = act(s, "score");
const scores = E.scores(s);
const asc = scores.map((_, p) => p).sort((a, b) => scores[a] - scores[b]);
assert.deepEqual(
s.tasks.map((t) => t.p),
asc,
);
while (s.phase === "setup-first") s = act(s, "place");
assert.deepEqual(
s.tasks.map((t) => t.p),
asc.toReversed(),
);
while (s.round === 0) s = act(s, "place");
for (let p = 0; p < n; p++) {
assert.deepEqual(
E.colony(s, p).map((a) => a.hp),
[n === 4 ? 1 : 0, 0],
);
}
conserved(s);
}
});
test("drift is free and blocked by the island and shore, not by other amoebas", () => {
assert.equal(E.destination(11, 2), 11);
assert.equal(E.destination(1, 0), 1);
let s = prepared({ bp: 0 });
s.amoebas.find((a) => a.p === 1).cell = 7;
s = act(s, "drift");
assert.equal(E.amoeba(s, "0-1").cell, 7);
assert.equal(s.players[0].bp, 0);
assert.equal(s.tasks[0].kind, "feeding");
s = act(s, "eat");
assert.deepEqual(s.food[7], [4, 1, 1, 1]);
conserved(s);
});
test("unaffordable swimming is rejected without mutating the position", () => {
const s = prepared({ bp: 0 }),
before = structuredClone(s);
assert.ok(!E.legalMoves(s).some((m) => m.type === "swim"));
assert.throws(() => E.move(s, { type: "swim" }, 0));
assert.deepEqual(s, before);
});
test("swimming pays once; Movement I rolls two, Movement II chooses, Speed has no second fee", () => {
let s = prepared({ genes: ["movement1"] });
s = act(s, "swim");
assert.equal(s.players[0].bp, 11);
assert.equal(s.tasks[0].dice.length, 2);
assert.equal(
s.log.at(-1).text,
`You #1 rolls ${s.tasks[0].dice.join(" and ")}.`,
);
s = prepared({ genes: ["movement2", "speed"] });
s = act(s, "swim");
assert.equal(E.legalMoves(s).length, 5);
s = act(s, "direction", { direction: 1 });
assert.ok(
s.log.some(
(line) => line.text === "You #1 chooses north with Movement II.",
),
);
assert.ok(!s.log.some((line) => /rolls/.test(line.text)));
assert.equal(s.tasks[0].kind, "speed");
s = act(s, "swim-again");
assert.equal(s.players[0].bp, 11);
s = act(s, "direction", { direction: 3 });
assert.equal(s.tasks[0].kind, "feeding");
s = prepared({ bp: 0, genes: ["streamline"] });
s = act(s, "swim");
assert.equal(s.players[0].bp, 0);
});
test("three-colony meals give a real choice and starvation consumes nothing", () => {
let s = prepared({ players: 3, task: { kind: "feeding", a: "0-1" } });
assert.deepEqual(
E.legalMoves(s)
.filter((m) => m.type === "eat")
.map((m) => m.food),
[
[0, 1, 2],
[0, 2, 1],
],
);
s.food[6][1] = 0;
s.supply[1] += 2;
const before = s.food[6].slice();
s = act(s, "starve");
assert.equal(E.amoeba(s, "0-1").hp, 1);
assert.deepEqual(s.food[6], before);
conserved(s);
});
test("combined feeding genes include the one-colour meal", () => {
const s = chapters["feeding-genes"].initialState();
assert.deepEqual(
E.legalMoves(s).find((m) => m.type === "eat").food,
[0, 3, 0, 0],
);
conserved(act(s, "eat"));
});
test("advanced genes require an earlier-round prerequisite; pool copies are finite", () => {
let s = prepared({
phase: 2,
task: { kind: "genes", p: 0 },
genes: ["movement1"],
});
s.players[0].genes[0].round = 2;
assert.ok(!E.legalMoves(s).some((m) => m.gene === "movement2"));
s.players[0].genes[0].round = 1;
s = act(s, "buy", { gene: "movement2" });
assert.ok(E.has(s, 0, "movement2"));
assert.ok(!E.has(s, 0, "movement1"));
assert.equal(E.geneCount(s, 0), 2);
assert.ok(!E.legalMoves(s).some((m) => m.gene === "movement1"));
s.players[1].genes = [{ id: "spores", round: 1 }];
assert.ok(!E.legalMoves(s).some((m) => m.gene === "spores"));
});
test("mutation debt can combine a discarded gene and BP", () => {
let s = chapters.environment.initialState();
s = act(s, "discard", { gene: "intelligence" });
assert.equal(s.tasks[0].debt, 1);
s = act(s, "pay-defect");
assert.equal(s.players[0].bp, 1);
assert.ok(E.has(s, 0, "longevity"));
assert.equal(s.phase, 2);
});
test("division uses adjacency, colony cap, affordable cost, and extinction recovery", () => {
let s = prepared({ phase: 3, bp: 6, task: { kind: "division", p: 0 } });
assert.ok(!E.legalMoves(s).some((m) => m.cell === 9));
s = act(s, "divide", { cell: 7 });
assert.equal(s.players[0].bp, 0);
assert.ok(!E.legalMoves(s).some((m) => m.type === "divide"));
s = prepared({ phase: 3, bp: 0, task: { kind: "division", p: 0 } });
s.amoebas = s.amoebas.filter((a) => a.p !== 0);
assert.ok(E.legalMoves(s).some((m) => m.cell === 9));
s = act(s, "divide", { cell: 9 });
assert.equal(s.players[0].bp, 0);
assert.equal(E.colony(s, 0).length, 1);
});
test("food left after death and feeding is limited to available supply", () => {
let s = chapters.survival.initialState();
const c = E.amoeba(s, "0-2").cell,
old = s.food[c].slice();
s = act(s, "done");
assert.ok(!E.amoeba(s, "0-2"));
assert.ok(E.amoeba(s, "0-1"));
assert.deepEqual(
s.food[c],
old.map((n) => n + 2),
);
conserved(s);
s = prepared({ task: { kind: "feeding", a: "0-1" } });
s.food[1][0] += 16;
s.supply[0] = 1;
const count = s.food[6][0];
s = act(s, "eat");
assert.equal(s.food[6][0], count + 1);
assert.equal(s.supply[0], 0);
conserved(s);
});
test("Holding interrupts correctly and Tentacle carries with a conserved supply", () => {
let s = prepared();
s.players[1].genes = [
{ id: "holding", round: 1 },
{ id: "tentacle", round: 1 },
];
s.amoebas.find((a) => a.p === 1).cell = 6;
s = act(s, "drift");
assert.equal(E.currentPlayer(s), 1);
assert.equal(s.tasks[0].kind, "follow");
s = act(s, "follow");
s = act(s, "carry", { color: 0 });
conserved(s);
s = act(s, "travel");
assert.equal(E.amoeba(s, "1-1").cell, 7);
assert.equal(E.currentPlayer(s), 0);
assert.equal(s.tasks[0].kind, "feeding");
conserved(s);
});
test("Struggle cannot eat Armor; Aggression wounds it and can trigger natural death", () => {
let s = chapters.attacks.initialState();
s.players[1].genes = [{ id: "armor", round: 1 }];
assert.ok(!E.legalMoves(s).some((m) => m.type === "attack"));
s.phase = 4;
s.tasks = [{ kind: "aggression", p: 0 }];
s.players[0].genes = [{ id: "aggression", round: 1 }];
s.amoebas.find((a) => a.id === "1-1").hp = 1;
s = act(s, "attack");
assert.ok(!E.amoeba(s, "1-1"));
assert.equal(s.players[0].bp, 11);
conserved(s);
});
test("Escape uses movement genes and returns to the original turn", () => {
let s = chapters.attacks.initialState();
s.players[1].genes = [
{ id: "escape", round: 1 },
{ id: "movement2", round: 1 },
];
s = act(s, "attack");
assert.equal(E.currentPlayer(s), 1);
s = act(s, "escape");
assert.equal(s.players[1].bp, 5);
s = act(s, "direction", { direction: 1 });
assert.equal(E.amoeba(s, "1-1").cell, 1);
assert.equal(E.amoeba(s, "0-1").hp, 1);
conserved(s);
});
test("scoring leapfrogs occupied spaces in descending order", () => {
let s = prepared({ phase: 3, bp: 0, task: { kind: "division", p: 0 } });
s.players.forEach((p, i) => (p.score = [1, 2, 3, 4][i]));
s.amoebas = s.amoebas.filter((a) => a.p !== 0);
for (let n = 1; n <= 3; n++)
s.amoebas.push({ id: `0-${n}`, p: 0, n, cell: [6, 7, 11][n - 1], hp: 0 });
s = act(s, "done");
assert.equal(s.players[0].score, 5);
assert.equal(s.lastScoring[0].advance, 1);
});
test("completed games at both player counts remain valid across save/reload", () => {
for (const n of [3, 4])
for (let seed = 0; seed < 12; seed++) {
let s = E.init(n, [], {}, `autoplay-${seed}`),
steps = 0;
while (!E.ended(s) && steps++ < 2000) {
const before = structuredClone(s),
next = E.moveAI(s, E.currentPlayer(s));
assert.deepEqual(s, before);
s = steps % 19 === 0 ? JSON.parse(JSON.stringify(next)) : next;
conserved(s);
assert.equal(E.stripSecret(s).actor, E.currentPlayer(s));
}
assert.ok(s.finished, `No finish: ${n}/${seed}`);
assert.ok(s.round <= 10);
assert.equal(E.currentPlayer(s), undefined);
assert.equal(new Set(E.scores(s)).size, n);
}
});
test("dropped colonies get a replacement at any point", () => {
let s = E.init(3, [], {}, "drop");
const dropped = E.currentPlayer(s);
s = E.dropPlayer(s, dropped);
assert.notEqual(E.currentPlayer(s), dropped);
let count = 0;
while (!s.finished && count++ < 2000) {
assert.notEqual(E.currentPlayer(s), dropped);
s = E.moveAI(s, E.currentPlayer(s));
}
assert.ok(s.finished);
});
test("every tutorial is playable, completes, and restores from recorded actions", async () => {
const sequences = {
drift: ["continue", "drift", "eat"],
swim: ["swim", "direction", "eat"],
division: ["divide", "divide", "done"],
genes: ["buy:movement1", "continue", "done"],
environment: ["discard:intelligence", "pay-defect"],
survival: ["done", "continue"],
"movement-genes": ["buy:movement2", "continue"],
"feeding-genes": ["eat", "continue"],
interactions: ["follow", "carry", "travel"],
attacks: ["attack", "continue"],
};
for (const [id, config] of Object.entries(chapters)) {
const cache = new Map(),
storage = {
getItem: (k) => cache.get(k) ?? null,
setItem: (k, v) => cache.set(k, v),
};
const c = await createTutorial({ ...config, storage });
for (const token of sequences[id]) {
if (token === "continue") {
await c.continue();
continue;
}
const [type, gene] = token.split(":"),
m = E.legalMoves(c.snapshot.state).find(
(m) => m.type === type && (!gene || m.gene === gene),
);
assert.ok(m, `${id}: missing ${token}`);
assert.ok(await c.play(m), `${id}: ${c.snapshot.error}`);
}
assert.ok(c.snapshot.completed, `${id} incomplete`);
const expected = c.snapshot.state;
c.destroy();
const restored = await createTutorial({ ...config, storage });
assert.ok(restored.snapshot.completed);
assert.deepEqual(restored.snapshot.state, expected);
restored.destroy();
}
});
test("Parasitism combines with other feeding adaptations but cannot charge an empty host", () => {
let s = prepared({
genes: ["parasitism", "substitution"],
task: { kind: "feeding", a: "0-1" },
});
s.amoebas.find((a) => a.p === 1).cell = 6;
for (let p = 0; p < 4; p++) {
s.supply[p] += s.food[6][p];
s.food[6][p] = 0;
}
s.food[6][2] = 3;
s.supply[2] -= 3;
const eat = E.legalMoves(s).find((m) => m.type === "eat");
assert.deepEqual(eat.food, [0, 0, 3, 0]);
assert.equal(eat.host, 1);
const after = E.move(s, eat, 0);
assert.equal(after.players[1].bp, 5);
conserved(after);
s.players[1].bp = 0;
assert.ok(!E.legalMoves(s).some((m) => m.type === "eat"));
});
test("random legal play preserves invariants across uncommon gene combinations", () => {
for (let run = 0; run < 12; run++) {
let s = E.init(4, [], {}, `random-${run}`),
rng = run + 1,
steps = 0;
const random = (n) => {
rng = (Math.imul(rng, 1664525) + 1013904223) >>> 0;
return rng % n;
};
while (!E.ended(s) && steps++ < 4000) {
const moves = E.legalMoves(s);
assert.ok(moves.length);
const affordable = moves.filter((m) => m.type === "buy");
const choices = affordable.length && random(3) ? affordable : moves;
s = E.move(s, choices[random(choices.length)], E.currentPlayer(s));
conserved(s);
}
assert.ok(E.ended(s), `random run ${run} must end`);
}
});
test("a bot completes its colony turn but yields to an opponent's Holding decision", () => {
let s = prepared();
s = E.moveAI(s, 0);
assert.notEqual(E.currentPlayer(s), 0);
assert.ok(s.history.filter((h) => h.move.type === "eat").length >= 2);
s = prepared();
s.players[1].genes = [{ id: "holding", round: 1 }];
s.amoebas.find((a) => a.p === 1).cell = 6;
s = E.moveAI(s, 0);
assert.equal(E.currentPlayer(s), 1);
assert.equal(s.tasks[0].kind, "follow");
assert.equal(s.history.length, 1);
});
test("replay restores a playable analysis boundary without running dropped-player bots", () => {
let state = E.init(3, [], {}, "analysis-replay");
state.players[0].name = "Alice";
const snapshots = [structuredClone(state)];
for (let i = 0; i < 80 && !state.finished; i++) {
state = E.move(state, E.legalMoves(state)[0], E.currentPlayer(state));
snapshots.push(structuredClone(state));
}
const original = structuredClone(state);
for (const to of [0, 5, 20, state.history.length]) {
const copy = E.replay(state, { to });
const view = E.stripSecret(copy);
const expected = E.stripSecret(snapshots[to]);
delete expected.undoPlayer;
// Replay commits the requested prefix, including moves which were still
// undoable in the original snapshot at this point.
expected.historyLength = to;
assert.deepEqual(view, expected);
assert.deepEqual(copy.history, state.history.slice(0, to));
assert.equal(E.logLength(copy), to);
if (!copy.finished) {
const next = E.move(copy, E.legalMoves(copy)[0], E.currentPlayer(copy));
assert.equal(
next.history.length + (next._pendingMoves?.length ?? 0),
to + 1,
);
}
}
assert.deepEqual(state, original);
});