primordial-soup/engine/index.js

1568 lines
46 KiB
JavaScript

import { sha256 } from "@noble/hashes/sha2.js";
import {
CELLS,
COLORS,
GENE,
GENES,
ALL_GENES,
copiesOf,
ENVIRONMENTS,
DIRECTIONS,
coordinate,
destination,
adjacent,
populationPoints,
geneFor,
amoebaLimit,
roundIncome,
tentacleLimit,
genePoints,
} from "./catalog.js";
import {
createNewGeneMarket,
revealNewGenesAfterPurchases,
publicNewGeneMarket,
} from "./new-genes.js";
import { canUndo, commitPending, recordMove, undoMove } from "./undo.js";
export { canUndo, isLiveUpdate, timeIncrements } from "./undo.js";
export * from "./catalog.js";
export { NEW_GENES_OPTION } from "./new-genes.js";
export const hashSeed = true;
const clone = (x) => structuredClone(x);
const requireThat = (yes, message) => {
if (!yes) throw new Error(message);
};
export const has = (s, p, id) => s.players[p].genes.some((g) => g.id === id);
export const colony = (s, p) =>
s.amoebas.filter((a) => a.p === p).sort((a, b) => a.n - b.n);
export const amoeba = (s, id) => s.amoebas.find((a) => a.id === id);
export const mutation = (s, p) =>
s.players[p].genes.reduce(
(v, g) => v + geneFor(g.id, s.players.length).mutation,
0,
);
export const geneCount = (s, p) =>
s.players[p].genes.reduce((v, g) => v + GENE[g.id].points, 0);
export const evolution = (s, p) =>
populationPoints(colony(s, p).length, s.players.length) +
genePoints(geneCount(s, p));
const order = (s, descending = false) =>
s.players
.map((_, p) => p)
.sort(
(a, b) =>
(s.players[a].score - s.players[b].score) * (descending ? -1 : 1),
);
function random(s, max) {
const b = sha256(new TextEncoder().encode(`${s._seed}:${s._counter++}`));
return new DataView(b.buffer, b.byteOffset, 4).getUint32(0) % max;
}
function shuffle(s, items) {
const a = clone(items);
for (let i = a.length - 1; i > 0; i--) {
const j = random(s, i + 1);
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
const die = (s) => 1 + random(s, 6);
const say = (s, text, cell) => {
s.log.push({
round: s.round,
phase: s.phase,
text,
...(cell === undefined ? {} : { cell }),
});
if (cell !== undefined) s.lastCells = [cell];
};
const name = (s, p) => s.players[p].name;
const label = (s, a) => `${name(s, a.p)} #${a.n}`;
const pay = (s, p, n) => {
requireThat(s.players[p].bp >= n, "Not enough biological points.");
s.players[p].bp -= n;
};
const addFood = (s, cell, p, n) => {
const add = Math.min(n, s.supply[p]);
s.food[cell][p] += add;
s.supply[p] -= add;
};
function kill(s, a, amount) {
if (!amoeba(s, a.id)) return;
s.amoebas = s.amoebas.filter((b) => b.id !== a.id);
s.players.forEach((_, p) => addFood(s, a.cell, p, amount));
say(s, `${label(s, a)} returns to the soup.`, a.cell);
if (has(s, a.p, "bang")) {
const others = s.amoebas
.filter((b) => b.cell === a.cell)
.sort((x, y) => s.players[y.p].score - s.players[x.p].score || x.n - y.n);
for (const b of others) b.hp++;
say(s, `${GENE.bang.name} injures ${others.length} other amoebas.`, a.cell);
for (const b of others) if (b.hp >= injuriesToDie(s, b.p)) kill(s, b, 2);
}
}
export const injuriesToDie = (s, p) =>
(has(s, p, "longevity") ? 3 : 2) - Number(has(s, p, "short-life"));
const swimCost = (s, p) => (has(s, p, "streamline") ? 0 : 1);
export const divisionCost = (s, p) =>
!colony(s, p).length
? 0
: has(s, p, "division") || has(s, p, "short-life")
? 4
: 6;
const putTasks = (s, ...tasks) => s.tasks.unshift(...tasks.filter(Boolean));
const taskPlayer = (s, t) => t.p ?? amoeba(s, t.a)?.p;
export function init(players, expansions = [], options = {}, seed = "soup") {
requireThat(
[3, 4, 5, 6].includes(players),
"Primordial Soup is for three to six colonies.",
);
requireThat(
!expansions.length,
"Use the New genes option; no separate expansion is required.",
);
const s = {
version: 1,
players: Array.from({ length: players }, (_, p) => ({
name: `Colony ${p + 1}`,
color: COLORS[p],
bp: 4,
score: 0,
genes: [],
dropped: false,
})),
amoebas: [],
food: Array.from({ length: 25 }, (_, c) =>
Array(players).fill(CELLS.includes(c) ? 2 : 0),
),
supply: Array(players).fill(17),
round: 0,
phase: "setup-score",
tasks: [],
log: [],
lastCells: [],
history: [],
_seed: String(seed),
_counter: 0,
deckRemaining: 10,
options: { newGenes: options.newGenes ?? false },
};
s._deck = shuffle(s, ENVIRONMENTS);
s.environment = s._deck.shift();
s.initialEnvironment = clone(s.environment);
if (options.newGenes) {
s.toxins = Array(25).fill(0);
s.alarmPlayers = [];
s._knowledge = {};
}
const market = createNewGeneMarket(options, (n) => random(s, n));
if (market) s.newGeneMarket = market;
const rolled = s.players
.map((_, p) => ({ p, roll: die(s) + die(s), tie: random(s, 1000000) }))
.sort((a, b) => b.roll - a.roll || b.tie - a.tie);
s.setupRolls = rolled.map(({ p, roll }) => ({ p, roll }));
s.tasks = rolled.map(({ p }) => ({ kind: "setup-score", p }));
say(s, "Choose your starting evolution position, then place two amoebas.");
return s;
}
function foodVectors(n, total) {
const all = [];
function f(i, left, v) {
if (i === n - 1) {
all.push([...v, left]);
return;
}
for (let k = 0; k <= left; k++) f(i + 1, left - k, [...v, k]);
}
f(0, total, []);
return all;
}
function reduced(v) {
return v.flatMap((n, p) =>
n ? [v.map((x, i) => x - (i === p ? 1 : 0))] : [],
);
}
function largeColonyMenus(s, a) {
const variants = [];
const hosts = has(s, a.p, "parasitism")
? [
...new Set(
s.amoebas
.filter(
(b) => b.cell === a.cell && b.p !== a.p && s.players[b.p].bp > 0,
)
.map((b) => b.p),
),
]
: [];
for (const host of [undefined, ...hosts]) {
const hostReduction = host === undefined ? 0 : 1;
for (let frugal = 0; frugal <= Number(has(s, a.p, "frugality")); frugal++) {
const reduction = hostReduction + frugal;
for (
let substitute = 0;
substitute <= Number(has(s, a.p, "substitution"));
substitute++
) {
const total = 4 - reduction + substitute;
for (const food of foodVectors(s.players.length, total)) {
if (food[a.p]) continue;
const colours = food.filter((n) => n > 0).length;
if (
substitute
? colours < Math.max(1, 3 - reduction) || colours > 3
: colours !== total
)
continue;
variants.push({ food, ...(host === undefined ? {} : { host }) });
}
}
}
}
return variants;
}
function mealRecipes(s, a) {
if (s.players.length >= 5) return largeColonyMenus(s, a);
let base = foodVectors(s.players.length, 3).filter(
(v) =>
v[a.p] === 0 &&
(s.players.length === 4
? v.every((n, p) => p === a.p || n === 1)
: v.filter((n) => n > 0).length === 2),
);
if (has(s, a.p, "substitution"))
base.push(
...foodVectors(s.players.length, 4).filter(
(v) =>
!v[a.p] &&
(s.players.length === 4
? v.filter((n) => n === 2).length === 2
: v.includes(4)),
),
);
if (has(s, a.p, "frugality")) {
base.push(...base.flatMap(reduced));
if (has(s, a.p, "substitution"))
base.push(
...foodVectors(s.players.length, 3).filter(
(v) => !v[a.p] && v.includes(3),
),
);
}
const variants = base.map((food) => ({ food }));
if (has(s, a.p, "parasitism")) {
const hosts = [
...new Set(
s.amoebas
.filter(
(b) => b.cell === a.cell && b.p !== a.p && s.players[b.p].bp > 0,
)
.map((b) => b.p),
),
];
for (const host of hosts) {
const meals = base.flatMap(reduced);
if (has(s, a.p, "substitution")) {
meals.push(
...foodVectors(s.players.length, 3).filter(
(v) => !v[a.p] && v.includes(3),
),
);
if (has(s, a.p, "frugality"))
meals.push(
...foodVectors(s.players.length, 2).filter(
(v) => !v[a.p] && v.includes(2),
),
);
}
variants.push(...meals.map((food) => ({ food, host })));
}
}
return variants;
}
export function menus(s, a) {
let variants = mealRecipes(s, a);
if (has(s, a.p, "glutton"))
variants = variants.flatMap((v) =>
s.players.flatMap((_, p) =>
p === a.p
? []
: [
{
...v,
food: v.food.map((n, color) => n + Number(color === p)),
},
],
),
);
const suction = has(s, a.p, "suction2") ? 2 : has(s, a.p, "suction1") ? 1 : 0;
const sources =
suction === 2
? CELLS.filter(
(c) =>
c !== a.cell &&
Math.abs((c % 5) - (a.cell % 5)) <= 1 &&
Math.abs(Math.floor(c / 5) - Math.floor(a.cell / 5)) <= 1,
)
: suction
? adjacent(a.cell)
: [];
const meals = [],
seen = new Set();
const add = (v) => {
const key = JSON.stringify(v);
if (!seen.has(key)) {
seen.add(key);
meals.push(v);
}
};
for (const v of variants) {
if (v.food.every((n, p) => n <= s.food[a.cell][p])) add(v);
for (const source of sources)
for (let n = 1; n <= suction; n++)
for (const borrowed of foodVectors(s.players.length, n)) {
if (
borrowed.some(
(x, p) =>
x > v.food[p] ||
x > s.food[source][p] ||
v.food[p] - x > s.food[a.cell][p],
)
)
continue;
add({ ...v, source, borrowed });
}
}
return meals;
}
const canEscape = (s, p) =>
has(s, p, "escape") ||
(has(s, p, "alarm") && s.phase === 0 && s.alarmPlayers?.includes(p));
export function movementDestinations(s, a, direction) {
const normal = destination(a.cell, direction),
result = [normal];
if (direction < 4 && normal === a.cell && has(s, a.p, "rebound")) {
const [dx, dy] = [
[-1, 0],
[0, -1],
[1, 0],
[0, 1],
][direction];
const x = (a.cell % 5) + 2 * dx,
y = Math.floor(a.cell / 5) + 2 * dy;
if (x >= 0 && x < 5 && y >= 0 && y < 5 && CELLS.includes(y * 5 + x))
result.push(y * 5 + x);
}
return result;
}
function possibleVictims(s, a, mode) {
return s.amoebas.filter(
(b) =>
b.id !== a.id &&
b.cell === a.cell &&
(mode !== "aggression" || b.p !== a.p) &&
(mode !== "feeding" || !has(s, b.p, "armor")) &&
(!has(s, b.p, "threat") || a.n <= b.n),
);
}
export const genesInGame = (s) =>
[...GENES, ...(s.newGeneMarket?.available ?? []).map((id) => GENE[id])]
.map((g) => geneFor(g.id, s.players.length))
.filter((g) => copiesOf(g, s.players.length));
const ownerOf = (s, id) =>
s.players.findIndex((pl) => pl.genes.some((g) => g.id === id));
export function genePurchaseCost(s, p, id, exchange) {
const price =
id === "social" && ownerOf(s, id) !== -1
? GENE.social.transferCost
: geneFor(id, s.players.length).cost;
return Math.max(
0,
price -
(exchange ? geneFor(exchange, s.players.length).cost : 0) -
Number(has(s, p, "flexible")),
);
}
function availableGenes(s, p, exchange) {
return genesInGame(s).filter((g) => {
if (
s.players[p].bp < genePurchaseCost(s, p, g.id, exchange) ||
has(s, p, g.id) ||
ALL_GENES.some(
(advanced) =>
advanced.id !== exchange &&
advanced.base.includes(g.id) &&
has(s, p, advanced.id),
)
)
return false;
if (g.id === "social" && order(s)[0] !== p) return false;
const held = s.players.reduce(
(n, pl) => n + Number(pl.genes.some((x) => x.id === g.id)),
0,
);
if (g.id !== "social" && copiesOf(g, s.players.length) <= held)
return false;
return (
!g.base.length ||
s.players[p].genes.some((x) => g.base.includes(x.id) && x.round < s.round)
);
});
}
function geneMoves(s, p, exchange) {
return availableGenes(s, p, exchange).flatMap((g) => {
const data = { gene: g.id, ...(exchange ? { exchange } : {}) };
return g.base.length
? s.players[p].genes
.filter((x) => g.base.includes(x.id) && x.round < s.round)
.map((x) =>
choice(exchange ? "exchange" : "buy", { ...data, base: x.id }),
)
: [choice(exchange ? "exchange" : "buy", data)];
});
}
function healingMoves(s, p) {
if (!has(s, p, "healing1") && !has(s, p, "healing2")) return [];
return colony(s, p)
.filter((a) => a.hp > 0)
.flatMap((a) => [
...(s.players[p].bp >= 3 ? [choice("heal", { amoeba: a.id })] : []),
...(has(s, p, "healing2")
? s.amoebas
.filter((b) => b.id !== a.id && b.cell === a.cell)
.map((b) =>
choice("transfer-injury", { amoeba: a.id, target: b.id }),
)
: []),
]);
}
const choice = (type, data = {}) => ({ type, ...data });
export function legalMoves(s) {
if (s.finished || !s.tasks.length) return [];
const t = s.tasks[0],
p = taskPlayer(s, t),
a = amoeba(s, t.a),
player = s.players[p];
switch (t.kind) {
case "setup-score":
return Array.from(
{ length: s.players.length >= 5 ? 6 : s.players.length },
(_, i) => i + 1,
)
.filter((score) => !s.players.some((pl) => pl.score === score))
.map((score) => choice("score", { score }));
case "setup-place":
return CELLS.filter(
(cell) => !s.amoebas.some((a) => a.cell === cell),
).flatMap((cell) =>
Array.from({ length: amoebaLimit(s.players.length) }, (_, i) => i + 1)
.filter((n) => !colony(s, p).some((a) => a.n === n))
.map((n) => choice("place", { cell, n })),
);
case "movement":
return [
...movementDestinations(s, a, s.environment.direction).map((cell) =>
choice("drift", { cell }),
),
...(!t.fed && has(s, p, "fast-food") ? [choice("eat-first")] : []),
...(has(s, p, "holding") &&
destination(a.cell, s.environment.direction) !== a.cell
? [choice("hold")]
: []),
...(player.bp >= swimCost(s, p) ? [choice("swim")] : []),
];
case "direction":
return [
...new Set(
t.dice.includes(6) ? [0, 1, 2, 3, 4] : t.dice.map((d) => d - 1),
),
].flatMap((direction) =>
movementDestinations(s, a, direction).map((cell) =>
choice("direction", { direction, cell }),
),
);
case "carry":
return [
choice("travel"),
...s.food[a.cell].flatMap((n, color) =>
n && t.cargo.length < t.limit ? [choice("carry", { color })] : [],
),
...(t.cargo.length
? [choice("return-food", { color: t.cargo.at(-1) })]
: []),
];
case "follow":
return [choice("follow"), choice("decline")];
case "speed":
return [choice("feed-now"), choice("swim-again")];
case "feeding": {
const meals = menus(s, a);
return [
...meals.map((v) => choice("eat", v)),
...(!meals.length &&
(has(s, p, "struggle") || has(s, p, "aggression")) &&
player.bp >= 1 &&
!t.noAttack
? possibleVictims(s, a, "feeding").map((b) =>
choice("attack", { victim: b.id }),
)
: []),
...(!meals.length ? [choice("starve")] : []),
];
}
case "defect":
return [
...(player.bp >= t.debt
? [choice("pay-defect", { amount: t.debt })]
: []),
...player.genes
.filter((g) => geneFor(g.id, s.players.length).mutation > 0)
.map((g) => choice("discard", { gene: g.id })),
];
case "excrete":
return [a.cell, ...adjacent(a.cell)].map((cell) =>
choice("excrete", { cell }),
);
case "crust":
return [
...(player.bp >= 1 ? [choice("pay-crust")] : []),
choice("abandon-attack"),
];
case "population":
return [choice("take-income"), choice("population-explosion")];
case "genes":
return [
...geneMoves(s, p),
...(has(s, p, "adaptable")
? player.genes.flatMap((g) => geneMoves(s, p, g.id))
: []),
choice("done"),
];
case "division": {
const own = colony(s, p),
cost = t.target === undefined ? divisionCost(s, p) : 0,
empty = Array.from(
{ length: amoebaLimit(s.players.length) },
(_, i) => i + 1,
).filter((n) => !own.some((a) => a.n === n));
const placements =
player.bp >= cost &&
own.length < (t.target ?? amoebaLimit(s.players.length))
? CELLS.filter(
(cell) =>
!own.some((a) => a.cell === cell) &&
(own.length < 2 ||
has(s, p, "spores") ||
own.some((a) => adjacent(a.cell).includes(cell))),
).flatMap((cell) => empty.map((n) => choice("divide", { cell, n })))
: [];
return [
...placements,
...healingMoves(s, p),
...(t.target !== undefined && placements.length
? []
: [choice("done")]),
];
}
case "aggression":
return [
...(player.bp >= 1
? colony(s, p).flatMap((a) =>
possibleVictims(s, a, "aggression").map((b) =>
choice("attack", { attacker: a.id, victim: b.id }),
),
)
: []),
choice("done"),
];
case "combat": {
const b = amoeba(s, t.combat.victim),
bp = s.players[b.p].bp;
return [
choice("accept-attack"),
...(!t.combat.defended && has(s, b.p, "defense") && bp >= 1
? [choice("defend")]
: []),
...(!t.combat.escaped && canEscape(s, b.p) && bp >= swimCost(s, b.p)
? [choice("escape")]
: []),
];
}
case "retry-attack":
return [
choice("stop-attack"),
...possibleVictims(s, a, t.combat.mode).map((b) =>
choice("retry-attack", { victim: b.id }),
),
];
case "retry-defense":
return [choice("retry-defense"), choice("accept-defense-roll")];
default:
throw new Error(`Unknown decision: ${t.kind}`);
}
}
function startSwim(s, a, after, free = false) {
if (!free) pay(s, a.p, swimCost(s, a.p));
const dice = has(s, a.p, "movement2")
? [6]
: Array.from({ length: has(s, a.p, "movement1") ? 2 : 1 }, () => die(s));
if (!has(s, a.p, "movement2"))
say(s, `${label(s, a)} rolls ${dice.join(" and ")}.`);
putTasks(s, { kind: "direction", a: a.id, dice, after });
}
function startTravel(s, a, to, after, followers = true) {
const t = { kind: "travel", a: a.id, from: a.cell, to, after, followers };
if (
to !== a.cell &&
has(s, a.p, "tentacle") &&
s.food[a.cell].some((n) => n > 0)
)
putTasks(s, {
kind: "carry",
a: a.id,
limit: tentacleLimit(s.players.length),
cargo: [],
travel: t,
});
else putTasks(s, t);
}
function excrete(s, a, cell) {
addFood(s, cell, a.p, 2);
if (has(s, a.p, "toxic")) {
s.toxins ??= Array(25).fill(0);
s.toxins[cell]++;
}
say(
s,
`${label(s, a)} excretes two ${COLORS[a.p]} nutrients${has(s, a.p, "toxic") ? " and one toxin" : ""} at ${coordinate(cell)}.`,
cell,
);
}
function finishFeed(s, a, menu, after) {
for (let p = 0; p < s.players.length; p++) {
const remote = menu.borrowed?.[p] ?? 0;
s.food[a.cell][p] -= menu.food[p] - remote;
if (remote) s.food[menu.source][p] -= remote;
s.supply[p] += menu.food[p];
}
if (menu.host !== undefined) pay(s, menu.host, 1);
say(
s,
`${label(s, a)} feeds${menu.host === undefined ? "" : ` using ${name(s, menu.host)}'s BP`}.`,
a.cell,
);
if (has(s, a.p, "cleanliness"))
putTasks(s, { kind: "excrete", a: a.id, after });
else {
excrete(s, a, a.cell);
putTasks(s, after);
}
}
function finishAttack(s, c, success) {
const a = amoeba(s, c.attacker),
b = amoeba(s, c.victim);
if (success && a && b && has(s, b.p, "hard-crust") && !c.crustPaid) {
putTasks(s, { kind: "crust", a: a.id, combat: c });
return;
}
if (success && a && b) {
if (has(s, b.p, "armor")) {
b.hp++;
say(
s,
`${label(s, b)} absorbs the attack with Armor and takes one injury.`,
b.cell,
);
if (b.hp >= injuriesToDie(s, b.p)) kill(s, b, 2);
} else if (c.mode === "feeding" && a.p !== b.p && has(s, b.p, "mouthful")) {
b.hp++;
say(
s,
`${label(s, b)} survives with More than a Mouthful and takes one injury.`,
b.cell,
);
} else {
if (c.mode === "feeding" && has(s, b.p, "alarm")) {
s.alarmPlayers ??= [];
if (!s.alarmPlayers.includes(b.p)) s.alarmPlayers.push(b.p);
say(s, `${name(s, b.p)} sounds the Alarm.`);
}
kill(s, b, c.mode === "feeding" ? 1 : 2);
}
say(
s,
`${label(s, a)} wins the attack${c.mode === "feeding" ? " and feeds" : ""}.`,
a.cell,
);
} else if (
c.retry !== true &&
a &&
has(s, a.p, "persistence") &&
possibleVictims(s, a, c.mode).length
) {
putTasks(s, { kind: "retry-attack", a: a.id, combat: c });
return;
} else if (c.mode === "feeding" && a) {
a.hp++;
say(s, `${label(s, a)} could not feed and takes one injury.`, a.cell);
}
putTasks(s, c.after);
}
function resolveCombat(s, c) {
const a = amoeba(s, c.attacker),
b = amoeba(s, c.victim);
if (!a || !b || a.cell !== b.cell) {
finishAttack(s, c, false);
return;
}
if (!c.camoRolled) {
c.camoRolled = true;
c.camouflaged = has(s, a.p, "camouflage2");
if (has(s, a.p, "camouflage1")) {
const roll = die(s);
c.camouflaged = roll >= 4;
say(
s,
`${label(s, a)} rolls ${roll} for Camouflage I${c.camouflaged ? ": defenses are bypassed" : ": normal defenses apply"}.`,
);
}
}
if (has(s, b.p, "armor")) {
finishAttack(s, c, true);
return;
}
if (
!c.camouflaged &&
((!c.defended && has(s, b.p, "defense") && s.players[b.p].bp >= 1) ||
(!c.escaped &&
canEscape(s, b.p) &&
s.players[b.p].bp >= swimCost(s, b.p)))
)
putTasks(s, { kind: "combat", p: b.p, combat: c });
else finishAttack(s, c, true);
}
function fight(s, c, again = false) {
const a = amoeba(s, c.attacker),
b = amoeba(s, c.victim);
let x, y;
do {
x = die(s);
y = die(s);
} while (x === y);
say(s, `${name(s, a.p)} rolls ${x}; ${name(s, b.p)} rolls ${y}.`);
if (y > x) finishAttack(s, c, false);
else if (!again && has(s, b.p, "persistence"))
putTasks(s, { kind: "retry-defense", p: b.p, combat: c });
else resolveCombat(s, c);
}
function foresee(s, gene) {
if (!s._deck.length) return;
s.players.forEach((_, p) => {
if (has(s, p, gene)) {
s._knowledge ??= {};
s._knowledge[p] = clone(s._deck[0]);
}
});
}
function startMovement(s) {
if (s.newGeneMarket) s.alarmPlayers = [];
foresee(s, "migration");
s.tasks = order(s).flatMap((p) =>
colony(s, p).map((a) => ({ kind: "movement", a: a.id })),
);
}
function socialIncome(s) {
const p = ownerOf(s, "social");
if (p < 0) return;
for (let other = 0; other < s.players.length; other++)
if (
s.players[other].score >= s.players[p].score + 6 &&
s.players[other].bp > 0
) {
pay(s, other, 1);
s.players[p].bp++;
say(
s,
`${name(s, other)} gives ${name(s, p)} one BP through Social Gene.`,
);
}
}
function newPhase(s) {
switch (s.phase) {
case "setup-score":
s.phase = "setup-first";
s.tasks = order(s).map((p) => ({
kind: "setup-place",
p,
injury: s.players.length >= 4 ? 1 : 0,
}));
break;
case "setup-first":
s.phase = "setup-second";
s.tasks = order(s, true).map((p) => ({
kind: "setup-place",
p,
injury: 0,
}));
break;
case "setup-second":
s.round = 1;
s.phase = 0;
startMovement(s);
say(s, "Round 1: movement and feeding, starting with the lowest score.");
break;
case 0:
s.phase = 1;
s.environment = s._deck.shift();
s.deckRemaining = s._deck.length;
if (s._knowledge) s._knowledge = {};
foresee(s, "environmental");
say(
s,
`The current is ${DIRECTIONS[s.environment.direction].toLowerCase()}. Ozone layer: ${s.environment.ozone}.`,
);
s.tasks = order(s, true)
.filter((p) => s.round > 1 && mutation(s, p) > s.environment.ozone)
.map((p) => ({
kind: "defect",
p,
debt: mutation(s, p) - s.environment.ozone,
}));
break;
case 1:
s.phase = 2;
s.tasks = order(s, true).map((p) => ({ kind: "genes", p }));
break;
case 2:
s.phase = 3;
s.tasks = order(s, true).flatMap((p) => [
{ kind: "income", p },
{ kind: "division", p },
]);
break;
case 3:
s.phase = 4;
for (const p of order(s, true))
for (const a of colony(s, p))
if (a.hp >= injuriesToDie(s, p)) kill(s, a, 2);
s.tasks = order(s, true)
.filter((p) => has(s, p, "aggression"))
.map((p) => ({ kind: "aggression", p }));
break;
case 4:
s.phase = 5;
socialIncome(s);
for (const p of order(s, true)) {
let advance = evolution(s, p);
const earned = advance;
while (advance > 0) {
s.players[p].score++;
if (
!s.players.some(
(pl, i) => i !== p && pl.score === s.players[p].score,
)
)
advance--;
}
say(
s,
`${name(s, p)} advances ${earned} spaces to ${s.players[p].score}.`,
);
}
s.lastScoring = s.players.map((_, p) => ({
population: colony(s, p).length,
genes: geneCount(s, p),
advance: evolution(s, p),
}));
if (s.players.some((p) => p.score >= 42) || !s._deck.length) {
s.finished = true;
s.winner = order(s, true)[0];
const chooser = ownerOf(s, "doris-frank");
if (chooser >= 0) {
s.nextGameChooser = chooser;
say(
s,
`${name(s, chooser)} chooses the next game with Doris & Frank Gene.`,
);
}
say(
s,
`${name(s, s.winner)} wins with ${s.players[s.winner].score} evolution points.`,
);
}
break;
case 5:
s.round++;
s.phase = 0;
startMovement(s);
say(s, `Round ${s.round}: movement and feeding.`);
break;
}
}
function finishTurn(s, t) {
const p = taskPlayer(s, t);
say(
s,
`${name(s, p)} finishes ${s.phase === 2 ? "buying genes" : s.phase === 3 ? "cell division" : "the survival phase"}.`,
);
if (t.kind !== "genes" || !s.newGeneMarket) return;
const previous = s.newGeneMarket;
s.newGeneMarket = revealNewGenesAfterPurchases(previous, {
phase: s.phase,
round: s.round,
player: p,
leader: order(s, true)[0],
finishedBuying: true,
});
const revealed = s.newGeneMarket.available.slice(previous.available.length);
if (revealed.length)
say(
s,
`New genes available: ${revealed.map((id) => GENE[id].name).join(" and ")}.`,
);
}
function settle(s) {
for (let safety = 0; safety < 300; safety++) {
if (s.finished) return;
if (!s.tasks.length) {
newPhase(s);
continue;
}
const t = s.tasks[0],
a = amoeba(s, t.a);
if (t.a && !a) {
s.tasks.shift();
continue;
}
if (t.kind === "income") {
s.tasks.shift();
if (has(s, t.p, "population")) {
putTasks(s, {
kind: "population",
p: t.p,
target: colony(s, order(s, true)[0]).length,
});
continue;
}
const income = roundIncome(s.players.length);
s.players[t.p].bp += income;
say(s, `${name(s, t.p)} receives ${income} BP.`);
continue;
}
if (t.kind === "travel") {
s.tasks.shift();
const from = a.cell;
const riders = t.followers
? s.amoebas
.filter(
(b) => b.id !== a.id && b.cell === from && has(s, b.p, "holding"),
)
.sort(
(a, b) =>
s.players[a.p].score - s.players[b.p].score || a.n - b.n,
)
: [];
a.cell = t.to;
if (from !== t.to && s.toxins?.[t.to]) {
const damage = s.toxins[t.to];
a.hp += damage;
s.toxins[t.to] = 0;
say(s, `${label(s, a)} absorbs ${damage} toxic injuries.`, t.to);
}
s.lastCells = [from, t.to];
say(
s,
`${label(s, a)} ${from === t.to ? "stays at" : "moves to"} ${coordinate(t.to)}.`,
t.to,
);
if (t.after) putTasks(s, t.after);
if (from !== t.to)
putTasks(
s,
...riders.map((b) => ({ kind: "follow", a: b.id, to: t.to, from })),
);
continue;
}
if (t.kind === "after-swim") {
s.tasks.shift();
if (has(s, a.p, "speed") && !t.second)
putTasks(s, { kind: "speed", a: a.id, after: t.after });
else putTasks(s, t.after);
continue;
}
if (t.kind === "escape-result") {
s.tasks.shift();
const c = t.combat,
attacker = amoeba(s, c.attacker);
if (a.cell !== t.from) {
say(s, `${label(s, a)} escapes.`, a.cell);
if (attacker?.cell === a.cell) {
say(
s,
`${label(s, attacker)} followed with Holding. The attack ends.`,
a.cell,
);
if (c.mode === "feeding")
putTasks(s, {
kind: "feeding",
a: attacker.id,
noAttack: true,
after: c.after,
});
} else finishAttack(s, c, false);
} else resolveCombat(s, c);
continue;
}
if (t.kind === "defect" && t.debt <= 0) {
s.tasks.shift();
continue;
}
if (t.kind === "combat") {
const b = amoeba(s, t.combat.victim);
if (!b) {
s.tasks.shift();
finishAttack(s, t.combat, false);
continue;
}
}
// Skip an empty turn on entry, but preserve Done and Undo after a choice.
if (
(t.kind === "genes" || t.kind === "division") &&
!t.acted &&
!legalMoves(s).some((m) => m.type !== "done")
) {
s.tasks.shift();
finishTurn(s, t);
continue;
}
if (
t.kind === "aggression" &&
!legalMoves(s).some((m) => m.type === "attack")
) {
s.tasks.shift();
continue;
}
return;
}
throw new Error("The game could not advance to its next decision.");
}
const same = (a, b) =>
JSON.stringify(Object.entries(a).sort()) ===
JSON.stringify(Object.entries(b).sort());
function applyMove(data, action, player) {
requireThat(!data.finished, "The game has ended.");
requireThat(player === currentPlayer(data), "It is another colony's turn.");
const legal = legalMoves(data).find((m) => same(m, action));
requireThat(legal, "That action is not available.");
const s = clone(data),
m = legal,
t = s.tasks.shift(),
p = taskPlayer(s, t),
a = amoeba(s, t.a);
s.lastCells = [];
switch (m.type) {
case "score":
s.players[p].score = m.score;
say(s, `${name(s, p)} starts at evolution ${m.score}.`);
break;
case "place":
s.amoebas.push({
id: `${p}-${m.n}`,
p,
n: m.n,
cell: m.cell,
hp: t.injury,
});
say(
s,
`${name(s, p)} places amoeba #${m.n} at ${coordinate(m.cell)}${t.injury ? " with one injury" : ""}.`,
m.cell,
);
break;
case "eat-first":
putTasks(s, {
kind: "feeding",
a: a.id,
after: { kind: "movement", a: a.id, fed: true },
});
break;
case "drift":
case "hold":
if (m.type === "drift" && has(s, p, "energy")) {
s.players[p].bp++;
say(s, `${name(s, p)} gains one BP from Energy Conservation.`);
}
startTravel(
s,
a,
m.type === "hold" ? a.cell : m.cell,
t.fed
? undefined
: {
kind: "feeding",
a: a.id,
},
);
break;
case "swim":
startSwim(s, a, {
kind: "after-swim",
a: a.id,
after: t.fed ? undefined : { kind: "feeding", a: a.id },
});
break;
case "direction":
say(
s,
`${label(s, a)} chooses ${m.direction === 4 ? "to stay" : DIRECTIONS[m.direction].toLowerCase()}${has(s, p, "movement2") ? " with Movement II" : ""}.`,
);
startTravel(s, a, m.cell, t.after);
break;
case "carry":
s.food[a.cell][m.color]--;
t.cargo.push(m.color);
putTasks(s, t);
break;
case "return-food":
s.food[a.cell][m.color]++;
t.cargo.pop();
putTasks(s, t);
break;
case "travel":
for (const color of t.cargo) s.food[t.travel.to][color]++;
putTasks(s, t.travel);
break;
case "follow":
startTravel(s, a, t.to, null, false);
break;
case "decline":
break;
case "feed-now":
putTasks(s, t.after);
break;
case "swim-again":
startSwim(
s,
a,
{ kind: "after-swim", a: a.id, second: true, after: t.after },
true,
);
break;
case "excrete":
excrete(s, a, m.cell);
putTasks(s, t.after);
break;
case "eat":
finishFeed(s, a, m, t.after);
break;
case "starve":
a.hp++;
say(s, `${label(s, a)} cannot feed and takes one injury.`, a.cell);
putTasks(s, t.after);
break;
case "pay-defect":
pay(s, p, m.amount);
say(s, `${name(s, p)} pays ${m.amount} BP to protect their genes.`);
break;
case "discard":
s.players[p].genes = s.players[p].genes.filter((g) => g.id !== m.gene);
t.debt -=
GENE[m.gene].defectRelief ?? geneFor(m.gene, s.players.length).mutation;
say(s, `${name(s, p)} gives up ${GENE[m.gene].name}.`);
putTasks(s, t);
break;
case "buy":
case "exchange": {
const cost = genePurchaseCost(s, p, m.gene, m.exchange);
pay(s, p, cost);
if (m.gene === "social") {
const owner = ownerOf(s, "social");
if (owner >= 0) {
s.players[owner].genes = s.players[owner].genes.filter(
(g) => g.id !== "social",
);
s.players[owner].bp += cost;
}
}
if (m.base || m.exchange)
s.players[p].genes = s.players[p].genes.filter(
(g) => g.id !== m.base && g.id !== m.exchange,
);
s.players[p].genes.push({ id: m.gene, round: s.round });
say(
s,
`${name(s, p)} evolves ${GENE[m.gene].name}${m.exchange ? ` by exchanging ${GENE[m.exchange].name}` : ""} for ${cost} BP.`,
);
t.acted = true;
putTasks(s, t);
break;
}
case "take-income": {
const income = roundIncome(s.players.length);
s.players[p].bp += income;
say(s, `${name(s, p)} receives ${income} BP.`);
s.tasks[0].acted = true;
break;
}
case "population-explosion":
s.players[p].bp = 0;
s.tasks[0].target = t.target;
s.tasks[0].acted = true;
say(
s,
`${name(s, p)} uses Population Explosion, gives up all BP and grows toward ${t.target} amoebas.`,
);
break;
case "heal":
case "transfer-injury": {
const healed = amoeba(s, m.amoeba);
healed.hp--;
if (m.type === "heal") pay(s, p, 3);
else {
const target = amoeba(s, m.target);
target.hp++;
kill(s, target, 2);
}
say(
s,
`${label(s, healed)} removes one injury with ${m.type === "heal" ? "Healing" : "Healing II"}.`,
healed.cell,
);
t.acted = true;
putTasks(s, t);
break;
}
case "divide": {
const cost = t.target === undefined ? divisionCost(s, p) : 0;
pay(s, p, cost);
s.amoebas.push({ id: `${p}-${m.n}`, p, n: m.n, cell: m.cell, hp: 0 });
say(
s,
`${name(s, p)} places amoeba #${m.n} at ${coordinate(m.cell)} for ${cost} BP.`,
m.cell,
);
t.acted = true;
putTasks(s, t);
break;
}
case "done":
finishTurn(s, t);
break;
case "attack": {
const actor = amoeba(s, m.attacker ?? t.a);
pay(s, actor.p, 1);
say(
s,
`${label(s, actor)} attacks ${label(s, amoeba(s, m.victim))}.`,
actor.cell,
);
resolveCombat(s, {
attacker: actor.id,
victim: m.victim,
mode: t.kind === "aggression" ? "aggression" : "feeding",
after: t.after,
});
break;
}
case "pay-crust":
pay(s, p, 1);
finishAttack(s, { ...t.combat, crustPaid: true }, true);
break;
case "abandon-attack":
finishAttack(s, t.combat, false);
break;
case "accept-attack":
finishAttack(s, t.combat, true);
break;
case "defend":
pay(s, p, 1);
t.combat.defended = true;
fight(s, t.combat);
break;
case "escape": {
const b = amoeba(s, t.combat.victim);
t.combat.escaped = true;
startSwim(s, b, {
kind: "after-swim",
a: b.id,
after: {
kind: "escape-result",
a: b.id,
from: b.cell,
combat: t.combat,
},
});
break;
}
case "retry-attack":
resolveCombat(s, {
...t.combat,
victim: m.victim,
defended: false,
escaped: false,
camoRolled: false,
camouflaged: false,
crustPaid: false,
retry: true,
});
break;
case "stop-attack":
finishAttack(s, { ...t.combat, retry: true }, false);
break;
case "retry-defense":
fight(s, t.combat, true);
break;
case "accept-defense-roll":
resolveCombat(s, t.combat);
break;
default:
throw new Error("Unknown move.");
}
settle(s);
return recordMove(data, s, action, player, currentPlayer(s) === player);
}
export function move(data, action, player) {
if (action?.type === "undo") return undoMove(data, action, player);
let s = applyMove(data, action, player);
while (!s.finished && s.players[currentPlayer(s)].dropped)
s = applyMove(s, chooseAI(s), currentPlayer(s));
return s;
}
export function currentPlayer(s) {
return s.finished ? undefined : taskPlayer(s, s.tasks[0]);
}
export const ended = (s) => !!s.finished;
export const scores = (s) => s.players.map((p) => p.score);
export const round = (s) => s.round;
export const factions = (s) => s.players.map((p) => p.color);
export const logLength = (s) => s.history.length;
export const logSlice = (s, { start = 0, end = s.history.length } = {}) =>
s.history.slice(start, end);
export function setPlayerMetaData(s, p, meta) {
if (typeof meta.name === "string") s.players[p].name = meta.name;
return s;
}
export function stripSecret(data, player) {
const s = clone(data);
delete s._seed;
delete s._counter;
delete s._deck;
delete s.history;
delete s._knowledge;
delete s._undo;
delete s._pendingMoves;
delete s._moveDepth;
delete s._maxMoveDepth;
delete s._timeIncrements;
delete s._liveUpdate;
const undoPlayer = data._undo?.at(-1)?.player;
if (canUndo(data, undoPlayer)) s.undoPlayer = undoPlayer;
if (data._knowledge?.[player])
s.foreseenEnvironment = clone(data._knowledge[player]);
if (s.newGeneMarket)
s.newGeneMarket = publicNewGeneMarket(data.newGeneMarket);
s.moves = legalMoves(data);
s.actor = currentPlayer(data);
return s;
}
export function dropPlayer(data, p) {
let s = commitPending(clone(data));
s.players[p].dropped = true;
while (!s.finished && s.players[currentPlayer(s)].dropped)
s = moveAI(s, currentPlayer(s));
return s;
}
export function chooseAI(s) {
const moves = legalMoves(s),
t = s.tasks[0],
p = currentPlayer(s),
a = amoeba(s, t.a);
const pick = (type) => moves.find((m) => m.type === type);
if (t.kind === "movement") {
const drift = moves.find((m) => m.type === "drift");
const test = { ...a, cell: drift.cell };
if (pick("eat-first") && menus(s, a).length && !menus(s, test).length)
return pick("eat-first");
return t.fed || menus(s, test).length ? drift : (pick("swim") ?? drift);
}
if (t.kind === "direction")
return moves.reduce((best, m) =>
menus(s, { ...a, cell: m.cell }).length >
menus(s, { ...a, cell: best.cell }).length
? m
: best,
);
if (t.kind === "feeding")
return pick("eat") ?? pick("attack") ?? pick("starve");
if (t.kind === "population")
return t.target > colony(s, p).length + 2
? pick("population-explosion")
: pick("take-income");
if (t.kind === "crust") return pick("pay-crust") ?? pick("abandon-attack");
if (t.kind === "division" || t.kind === "setup-place") {
const heal = moves.find(
(m) => m.type === "heal" && amoeba(s, m.amoeba).hp >= injuriesToDie(s, p),
);
const transfer = moves.find(
(m) => m.type === "transfer-injury" && amoeba(s, m.target).p !== p,
);
if (transfer || heal) return transfer ?? heal;
const places = moves.filter((m) => ["divide", "place"].includes(m.type));
if (places.length) {
const n = Math.min(...places.map((m) => m.n));
return places
.filter((m) => m.n === n)
.sort(
(a, b) =>
s.food[b.cell].reduce((sum, v, i) => sum + (i !== p ? v : 0), 0) -
s.food[a.cell].reduce((sum, v, i) => sum + (i !== p ? v : 0), 0),
)[0];
}
}
if (t.kind === "genes") {
const desired = [
"division",
"movement1",
"spores",
"longevity",
"streamline",
"ray",
"substitution",
"movement2",
"intelligence",
"struggle",
"speed",
"holding",
"defense",
"tentacle",
"escape",
"aggression",
"armor",
"frugality",
"parasitism",
"persistence",
];
const buy = moves
.filter(
(m) =>
m.type === "buy" &&
(mutation(s, p) + geneFor(m.gene, s.players.length).mutation <=
s.environment.ozone + 3 ||
m.gene === "ray"),
)
.sort((a, b) => desired.indexOf(a.gene) - desired.indexOf(b.gene))[0];
return buy ?? pick("done");
}
if (t.kind === "defect")
return (
pick("pay-defect") ??
moves
.filter((m) => m.type === "discard")
.sort(
(a, b) =>
geneFor(b.gene, s.players.length).mutation -
geneFor(a.gene, s.players.length).mutation,
)[0]
);
if (t.kind === "carry") return pick("travel");
if (t.kind === "follow") return pick("decline");
if (t.kind === "speed")
return menus(s, a).length ? pick("feed-now") : pick("swim-again");
if (t.kind === "combat")
return pick("defend") ?? pick("escape") ?? pick("accept-attack");
if (t.kind === "retry-defense") return pick("retry-defense");
if (t.kind === "retry-attack")
return pick("retry-attack") ?? pick("stop-attack");
return moves[0];
}
export function moveAI(data, player) {
requireThat(player === currentPlayer(data), "Not this bot's turn.");
let state = data;
// Resolve a colony's turn together so seven amoebas do not exhaust BGS's bot-call cap.
// An opponent's Holding/Defense/Escape decision immediately yields control.
for (let n = 0; n < 100 && currentPlayer(state) === player; n++) {
state = move(state, chooseAI(state), player);
}
return state;
}
export function replay(data, { to = data.history.length } = {}) {
requireThat(
Number.isInteger(to) && to >= 0 && to <= data.history.length,
"Invalid history position.",
);
let state = init(data.players.length, [], data.options ?? {}, data._seed);
state.players.forEach((player, seat) => {
player.name = data.players[seat].name;
});
for (const entry of data.history.slice(0, to))
state = applyMove(state, entry.move, entry.player);
// Analysis may stop within a committed turn. Its prefix is already published.
return commitPending(state);
}
export function canLaunchAnalysisMode(data) {
return (
!!data.initialEnvironment ||
!data.log.some((entry) =>
/^The current is (.+)\. Ozone layer: (\d+)\.$/.test(entry.text),
)
);
}
/** Reconstruct unknown futures from canonical pools, never the live secret deck. */
export function createAnalysisScenario(data, { player, seed }) {
requireThat(
canLaunchAnalysisMode(data),
"This legacy position lacks its public initial environment record.",
);
const s = stripSecret(data, player);
const known = s.foreseenEnvironment;
for (const key of ["moves", "actor", "undoPlayer", "foreseenEnvironment"])
delete s[key];
s._seed = seed;
s._counter = 0;
s.history = [];
s.players.forEach((p) => {
p.dropped = false;
});
const pool = clone(ENVIRONMENTS);
const remove = (card) => {
const i = pool.findIndex(
(c) => c.ozone === card.ozone && c.direction === card.direction,
);
if (i >= 0) pool.splice(i, 1);
};
s.initialEnvironment ??= clone(s.environment);
remove(s.initialEnvironment);
for (const entry of s.log) {
const match = /^The current is (.+)\. Ozone layer: (\d+)\.$/.exec(
entry.text,
);
if (match) {
const card = {
direction: DIRECTIONS.findIndex((d) => d.toLowerCase() === match[1]),
ozone: Number(match[2]),
};
remove(card);
}
}
if (known) remove(known);
s._deck = [...(known ? [clone(known)] : []), ...shuffle(s, pool)].slice(
0,
s.deckRemaining,
);
if (s.options.newGenes) {
s._knowledge =
known && player !== undefined ? { [player]: clone(known) } : {};
// All previously revealed genes remain in the public market's available list.
const canonical = createNewGeneMarket(s.options, (n) => random(s, n));
s.newGeneMarket = {
available: [...s.newGeneMarket.available],
_deck: canonical._deck.filter(
(id) => !s.newGeneMarket.available.includes(id),
),
revealedRound: data.newGeneMarket.revealedRound,
};
}
return s;
}