primordial-soup/engine/index.js

1001 lines
29 KiB
JavaScript

import { sha256 } from "@noble/hashes/sha2.js";
import {
CELLS,
COLORS,
GENE,
GENES,
ENVIRONMENTS,
DIRECTIONS,
coordinate,
destination,
adjacent,
populationPoints,
genePoints,
} from "./catalog.js";
export * from "./catalog.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 + GENE[g.id].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) + 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) {
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);
}
const injuriesToDie = (s, p) => (has(s, p, "longevity") ? 3 : 2);
const swimCost = (s, p) => (has(s, p, "streamline") ? 0 : 1);
const divisionCost = (s, p) =>
!colony(s, p).length ? 0 : has(s, p, "division") ? 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].includes(players),
"Primordial Soup is for three or four colonies.",
);
requireThat(!expansions.length, "This version supports the base game.");
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,
};
s._deck = shuffle(s, ENVIRONMENTS);
s.environment = s._deck.shift();
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))] : [],
);
}
export function menus(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 })));
}
}
const seen = new Set();
return variants.filter((v) => {
const key = JSON.stringify(v);
if (seen.has(key) || v.food.some((n, p) => n > s.food[a.cell][p]))
return false;
seen.add(key);
return true;
});
}
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")),
);
}
function availableGenes(s, p) {
return GENES.filter((g) => {
if (
s.players[p].bp < g.cost ||
has(s, p, g.id) ||
GENES.some(
(advanced) => advanced.base.includes(g.id) && has(s, p, advanced.id),
)
)
return false;
if (
g.copies[s.players.length - 3] <=
s.players.reduce(
(n, pl) => n + pl.genes.filter((x) => x.id === g.id).length,
0,
)
)
return false;
return (
!g.base.length ||
s.players[p].genes.some((x) => g.base.includes(x.id) && x.round < s.round)
);
});
}
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 s.players
.map((_, 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: 7 }, (_, i) => i + 1)
.filter((n) => !colony(s, p).some((a) => a.n === n))
.map((n) => choice("place", { cell, n })),
);
case "movement":
return [
choice("drift", { cell: destination(a.cell, s.environment.direction) }),
...(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),
),
].map((direction) =>
choice("direction", {
direction,
cell: destination(a.cell, direction),
}),
);
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) => GENE[g.id].mutation > 0)
.map((g) => choice("discard", { gene: g.id })),
];
case "genes":
return [
...availableGenes(s, p).flatMap((g) =>
g.base.length
? player.genes
.filter((x) => g.base.includes(x.id) && x.round < s.round)
.map((x) => choice("buy", { gene: g.id, base: x.id }))
: [choice("buy", { gene: g.id })],
),
choice("done"),
];
case "division": {
const own = colony(s, p),
cost = divisionCost(s, p),
empty = Array.from({ length: 7 }, (_, i) => i + 1).filter(
(n) => !own.some((a) => a.n === n),
);
return [
...(player.bp >= cost && own.length < 7
? 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 })))
: []),
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 && has(s, b.p, "escape") && 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: s.players.length - 1,
cargo: [],
travel: t,
});
else putTasks(s, t);
}
function finishFeed(s, a, menu) {
for (let p = 0; p < s.players.length; p++) {
s.food[a.cell][p] -= menu.food[p];
s.supply[p] += menu.food[p];
}
if (menu.host !== undefined) pay(s, menu.host, 1);
addFood(s, a.cell, a.p, 2);
say(
s,
`${label(s, a)} feeds${menu.host === undefined ? "" : ` using ${name(s, menu.host)}'s BP`} and leaves two ${COLORS[a.p]} nutrients.`,
a.cell,
);
}
function finishAttack(s, c, success) {
const a = amoeba(s, c.attacker),
b = amoeba(s, c.victim);
if (success && b) {
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);
}
}
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 (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);
return;
}
if (
(!c.defended && has(s, b.p, "defense") && s.players[b.p].bp >= 1) ||
(!c.escaped &&
has(s, b.p, "escape") &&
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 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;
s.tasks = order(s).flatMap((p) =>
colony(s, p).map((a) => ({ kind: "movement", a: a.id })),
);
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;
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;
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];
say(
s,
`${name(s, s.winner)} wins with ${s.players[s.winner].score} evolution points.`,
);
}
break;
case 5:
s.round++;
s.phase = 0;
s.tasks = order(s).flatMap((p) =>
colony(s, p).map((a) => ({ kind: "movement", a: a.id })),
);
say(s, `Round ${s.round}: movement and feeding.`);
break;
}
}
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();
s.players[t.p].bp += 10;
say(s, `${name(s, t.p)} receives 10 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;
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 });
} 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;
}
}
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 = [];
s.history.push({ player, move: clone(m) });
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 "drift":
case "hold":
startTravel(s, a, m.type === "hold" ? a.cell : m.cell, {
kind: "feeding",
a: a.id,
});
break;
case "swim":
startSwim(s, a, {
kind: "after-swim",
a: a.id,
after: { kind: "feeding", a: a.id },
});
break;
case "direction":
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 "eat":
finishFeed(s, a, m);
break;
case "starve":
a.hp++;
say(s, `${label(s, a)} cannot feed and takes one injury.`, a.cell);
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].mutation;
say(s, `${name(s, p)} gives up ${GENE[m.gene].name}.`);
putTasks(s, t);
break;
case "buy":
pay(s, p, GENE[m.gene].cost);
if (m.base)
s.players[p].genes = s.players[p].genes.filter((g) => g.id !== m.base);
s.players[p].genes.push({ id: m.gene, round: s.round });
say(s, `${name(s, p)} evolves ${GENE[m.gene].name}.`);
putTasks(s, t);
break;
case "divide": {
const cost = divisionCost(s, p);
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,
);
putTasks(s, t);
break;
}
case "done":
say(
s,
`${name(s, p)} finishes ${s.phase === 2 ? "buying genes" : s.phase === 3 ? "cell division" : "the survival phase"}.`,
);
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",
});
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,
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 s;
}
export function move(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) {
const s = clone(data);
delete s._seed;
delete s._counter;
delete s._deck;
delete s.history;
s.moves = legalMoves(data);
s.actor = currentPlayer(data);
return s;
}
export function dropPlayer(data, p) {
let s = 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 };
return 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 === "division" || t.kind === "setup-place") {
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) + GENE[m.gene].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) => GENE[b.gene].mutation - GENE[a.gene].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;
}