primordial-soup/viewer/ui.js
coyotte508 1e4aed6c68 Offer "Undo my move" in games against bots
BGS lets the only human of a game against bots take back their last saved
move (protocol 0.10.0). The top toolbar shows an undo control while BGS
reports it available and the board is live (hidden in replays, analysis, to
spectators, once the game is over and while a move is pending); it asks BGS
to undo, which then sends the earlier position. That position resets local
selections (shown colony, selected amoeba, new amoeba number), also when the
moves were taken back elsewhere, and drops replay positions cached beyond
it. On the narrowest phones the header tightens to fit the extra control.
The chat preview emulates it locally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:36:07 +02:00

832 lines
45 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {
COLORS,
ENVIRONMENTS,
COLOR_NAMES,
CELLS,
copiesOf,
GENE,
DIRECTIONS,
PHASES,
coordinate,
geneFor,
amoebaLimit,
roundIncome,
} from "../engine/catalog.js";
import {
colony,
genesInGame,
genePurchaseCost,
mutation,
evolution,
geneCount,
divisionCost,
amoeba as findAmoeba,
} from "../engine/index.js";
import {
amoeba,
icon,
colors,
colonyTraits,
PHASE_ICONS,
setPlayerColors,
setPlayerSymbols,
displayColorName,
} from "./art.js";
import { geneArt } from "./gene-art.js";
import { geneSummary } from "./gene-summary.js";
import { geneFamilies } from "./gene-pool.js";
import { scoringLegend } from "./scoring-legend.js";
import {
geneIcon,
geneLabel,
geneScoringMark,
isNewGene,
newGeneMark,
} from "./gene-label.js";
import {
richText,
food,
bp,
injury,
sensitivity,
evolutionPoints,
} from "./rich-text.js";
import { mountActivity } from "./activity.js";
import { journalEntryHtml, playerReference } from "./journal.js";
import { pondArt } from "./pond.js";
import { viewerState } from "./state.js";
import {
readLocalColorBlindMode,
saveLocalColorBlindMode,
} from "./preferences.js";
export const RULES_URL =
"https://s3.fr-par.scw.cloud/bgs-assets/assets/primordial-soup/rules-en/69e877694adc4a15/rules-en.pdf";
export const SIMPLE_RULES_URL =
"https://boardgamers.space/page/primordial-soup/rules";
export const esc = (x) =>
String(x ?? "").replace(
/[&<>"']/g,
(c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
c
],
);
const OZONE_HELP =
"Ozone layer: protection from radiation. In phase 2, sensitivity above this limit must be covered by paying BP or discarding genes.";
const SENSITIVITY_HELP =
"Sensitivity: add up the values of your genes and compare the total with the ozone layer. Negative values reduce your total.";
const ROUND_LIMIT = ENVIRONMENTS.length - 1;
const nutrients = (vector) =>
vector.map((n, p) => (n ? food(p, n) : "")).join("");
const placementCost = (state) =>
state.tasks[0]?.kind === "setup-place" || state.tasks[0]?.target !== undefined
? 0
: divisionCost(state, state.actor);
const placementPrice = (state) =>
placementCost(state) ? `${placementCost(state)} BP` : "free";
export function moveLabel(m, s) {
const t = s.tasks[0],
a = findAmoeba(s, t?.a);
const ref = (id) => {
const b = findAmoeba(s, id);
return b ? `${esc(s.players[b.p].name)} #${b.n}` : "amoeba";
};
switch (m.type) {
case "score":
return `Start at ${m.score}`;
case "place":
return `Place #${m.n} · free`;
case "drift":
return `${m.cell === a?.cell ? "Stay" : "Drift"} · free`;
case "hold":
return "Hold position · free";
case "swim":
return `${icon("wave")} Swim ${s.players[s.actor].genes.some((g) => g.id === "movement2") ? "" : "· roll"} <small>${bp(s.players[s.actor].genes.some((g) => g.id === "streamline") ? 0 : 1)}</small>`;
case "direction":
return m.cell === a?.cell ? "Stay here" : DIRECTIONS[m.direction];
case "carry":
return `Carry ${food(m.color)}`;
case "return-food":
return `Put back ${food(m.color)}`;
case "travel":
return "Ready · move";
case "follow":
return `Follow to ${coordinate(t.to)} · free`;
case "decline":
return "Stay here";
case "swim-again":
return "Swim again · free";
case "feed-now":
return "Finish moving";
case "eat":
return `Eat ${nutrients(m.food)}${m.borrowed ? `<small>Take ${nutrients(m.borrowed)} from ${coordinate(m.source)}</small>` : ""}${m.host === undefined ? "" : `<small>${bp(-1)} for ${esc(s.players[m.host].name)}</small>`}`;
case "starve":
return `Take ${injury(1)}`;
case "pay-defect":
return `Pay ${bp(m.amount)}`;
case "discard":
return `Give up ${geneLabel(m.gene)} ${sensitivity(GENE[m.gene].defectRelief ?? geneFor(m.gene, s.players.length).mutation)}`;
case "buy":
return `Evolve · ${bp(genePurchaseCost(s, s.actor, m.gene))}`;
case "exchange":
return `Exchange ${geneLabel(m.exchange)} · ${bp(genePurchaseCost(s, s.actor, m.gene, m.exchange))}`;
case "eat-first":
return "Fast Food · eat before moving";
case "excrete":
return `Excrete at ${coordinate(m.cell)}`;
case "take-income":
return `Receive ${bp(roundIncome(s.players.length))}`;
case "population-explosion":
return `Population Explosion · give up all BP, grow to ${t.target}`;
case "heal":
return `Heal ${ref(m.amoeba)} · ${bp(3)}`;
case "transfer-injury":
return `Heal ${ref(m.amoeba)} · sacrifice ${ref(m.target)}`;
case "pay-crust":
return `Complete attack · ${bp(1)} extra`;
case "abandon-attack":
return "Abandon attack";
case "divide":
return `New amoeba #${m.n} · ${placementPrice(s)}`;
case "done":
return "Done";
case "attack":
return `${m.attacker ? ref(m.attacker) + " → " : "Attack "}${ref(m.victim)} · ${bp(1)}`;
case "accept-attack":
return "Accept attack";
case "defend":
return `Defend · ${bp(1)}`;
case "escape":
return `Escape · ${bp(s.players[s.actor].genes.some((g) => g.id === "streamline") ? 0 : 1)}`;
case "retry-attack":
return `Try again against ${ref(m.victim)} · free`;
case "stop-attack":
return "End attack";
case "retry-defense":
return "Defend again · free";
case "accept-defense-roll":
return "Keep this roll";
default:
return esc(m.type);
}
}
function instruction(s, seat) {
if (s.replaying) return s.replayLoading ? "Loading replay…" : "Replay";
if (s.finished) return `${s.players[s.winner].name} wins!`;
if (s.closed) return "This game has ended.";
if (s.actor !== seat) return `Waiting for ${s.players[s.actor].name}.`;
const t = s.tasks[0],
a = findAmoeba(s, t.a);
switch (t.kind) {
case "setup-score":
return "Choose a starting score. Lower scores move and feed first; higher scores buy genes first.";
case "setup-place":
return `Click an empty space for your ${s.phase === "setup-first" ? "first" : "second"} amoeba${t.injury ? " (starts with one injury)" : ""}.`;
case "movement":
return `Amoeba #${a.n} · Click the drift destination, or swim ${s.players[a.p].genes.some((g) => g.id === "movement2") ? "in a direction of your choice" : "to roll for a direction"}.`;
case "direction":
return `Amoeba #${a.n} · ${s.players[a.p].genes.some((g) => g.id === "movement2") ? "Choose your direction." : `Rolled ${t.dice.join(" / ")}. Click a highlighted destination.`}`;
case "feeding":
return `Amoeba #${a.n} · ${s.moves.some((m) => m.type === "eat") ? `Choose a meal, then leave two ${displayColorName(s.actor, COLOR_NAMES[s.actor]).toLowerCase()} nutrients.` : "Not enough food here. This amoeba will take an injury unless it can hunt."}`;
case "speed":
return "Speed lets you swim once more, for free, before feeding.";
case "carry":
return `Tentacle · Pick up to ${t.limit} nutrients to carry, then move. ${t.cargo.length} selected.`;
case "follow":
return `Holding · Amoeba #${a.n} can follow to ${coordinate(t.to)} for free.`;
case "defect":
return `Your mutation sensitivity exceeds the ozone layer by ${t.debt}. Pay BP, give up genes, or combine both.`;
case "genes":
return "Evolve your colony with new genes, then choose Done.";
case "division":
return t.target === undefined
? `New amoeba: ${placementPrice(s)}.${s.players[s.actor].bp < placementCost(s) ? " Not enough BP to place one." : " Click a highlighted space to place one."} You may also use Healing or finish with Done.`
: `Population Explosion · Free placement until you have ${t.target} amoebas. You may also use Healing.`;
case "population":
return "Receive your usual income, or give up all BP to match the score leader’s population.";
case "excrete":
return "Cleanliness · Choose where to leave both nutrients. Toxic Excretions, if owned, goes to the same space.";
case "crust":
return "Hard Crust · Pay one more BP to complete the attack, or let the defender survive.";
case "aggression":
return "You may make one attack with Aggression, or finish with Done.";
case "combat":
return "One of your amoebas is being attacked. Choose how to respond.";
case "retry-defense":
return "Persistence gives you a second defense roll for free.";
case "retry-attack":
return "Persistence gives you a second attack for free.";
default:
return "Choose an action.";
}
}
export function mountGame(
target,
{
onMove,
onUndo,
onFullscreen,
onOpenPlayer,
onColorBlindChange,
chat,
practice = false,
} = {},
) {
const root = document.createElement("div");
root.className = "soup game-shell";
let appearance = {};
const playerBadge = (i) => {
const badge = appearance.players?.[i]?.pro && appearance.supporterBadge;
return badge
? `<img class="supporter-badge" src="${esc(badge.url)}" alt="${esc(badge.label)}" title="${esc(badge.label)}">`
: "";
};
let colonySymbols = onColorBlindChange ? false : readLocalColorBlindMode();
root.classList.toggle("colony-symbols", colonySymbols);
target.append(root);
root.innerHTML = `<header class="topbar"><div class="brand"><span>${amoeba("green", 0)}</span><div><h1 translate="no">primordial soup<span class="title-dot">.</span></h1><span class="byline" translate="no">DORIS MATTHÄUS & FRANK NESTEL</span></div></div><nav class="utilities" aria-label="Game options"><button class="icon-button" data-ui="undo-move" aria-label="Undo my move" title="Undo my move" hidden>${icon("undo")}</button><button class="quiet-button" data-ui="genes" aria-label="Genes" title="Gene pool">${icon("gene")}<span class="utility-label">Genes</span></button><button class="icon-button" data-ui="colony-symbols" aria-label="Color-blind mode" aria-pressed="${colonySymbols}" title="Color-blind mode: match colonies by symbol">${icon("colony-symbols")}</button><button class="icon-button" data-ui="rules" aria-label="How to play">${icon("help")}</button><button class="icon-button" data-ui="fullscreen" aria-label="Fullscreen">${icon("expand")}</button></nav></header>
<div class="tutorial-slot"></div><section class="players" aria-label="The colonies" data-tutorial="colonies"></section>
<main class="play-area"><section class="pond-section" aria-label="Primordial soup board"><div class="board-wrap"><div class="board" data-tutorial="board"><div class="pond-tools">${chat ? `<button class="quiet-button" data-ui="chat">${icon("chat")} Chat</button>` : ""}<button class="quiet-button" data-ui="journal">${icon("history")} Journal</button></div><svg id="pond-art" viewBox="0 0 900 650" preserveAspectRatio="none" aria-hidden="true">${pondArt()}</svg><div class="cells"></div><div class="organisms"></div><div class="current-compass" data-tutorial="current"><div class="environment-current"><span>CURRENT</span><div class="compass-arrow">➜</div><b class="compass-label"></b></div><div class="environment-ozone" role="img" tabindex="0" title="${OZONE_HELP}"><span class="ozone-value">${icon("ozone")}<strong class="ozone"></strong></span></div></div></div><div class="board-actions" data-tutorial="movement" hidden></div><div class="board-reference"><div class="game-progress"></div><aside class="soup-board-key" data-tutorial="scoring" aria-label="Scoring reference"></aside></div></div><div class="private-forecast" hidden></div><div class="pond-bottom"><div class="last-move" aria-live="polite"></div><span class="food-reserve" title="Food cubes remaining in the common supply"></span></div></section><aside class="colony-panel" data-tutorial="colony"></aside></main>
<footer class="turnbar" data-tutorial="actions"><div class="round"><span>ROUND</span><strong class="round-number"></strong></div><div class="turn-details"><div class="phase-label"></div><div class="phase-instruction" aria-live="polite"></div><ol class="phase-steps" aria-label="Round phases"></ol></div><div class="action-buttons"></div></footer><div class="game-message" role="alert"></div>
<div class="activity-slot"></div><dialog><button class="close-modal icon-button" data-ui="close" aria-label="Close">×</button><div class="modal-content"></div></dialog>`;
const $ = (q) => root.querySelector(q),
$$ = (q) => [...root.querySelectorAll(q)];
function setColorBlind(enabled) {
colonySymbols = enabled;
root.classList.toggle("colony-symbols", enabled);
$('[data-ui="colony-symbols"]').setAttribute(
"aria-pressed",
String(enabled),
);
if (!onColorBlindChange) saveLocalColorBlindMode(enabled);
}
let state,
seat,
selected,
viewPlayer,
number = 1,
busy = false,
locked = false,
replaying = false,
analysis = false,
undoAvailable = false,
modalKind,
modalPlayer,
oldTask,
mealSource,
buyableOnly = false;
const dialog = $("dialog");
const activity = mountActivity($(".activity-slot"), {
chat,
openPlayer: onOpenPlayer,
backToBoard() {
$(".play-area").scrollIntoView({ block: "start" });
$(
chat && !$('[data-ui="chat"]').hidden
? '[data-ui="chat"]'
: '[data-ui="journal"]',
).focus({
preventScroll: true,
});
},
});
const canAct = () =>
!busy &&
!locked &&
!replaying &&
!state?.closed &&
seat !== undefined &&
state?.actor === seat;
const actions = () => (canAct() ? state.moves : []);
// BGS offers "Undo my move" to the only human of a game against bots; it is
// usable from the live board only, also while the bots reply.
const canUndoMove = () =>
undoAvailable &&
!analysis &&
!busy &&
!locked &&
!replaying &&
seat !== undefined &&
!!state &&
!state.closed;
function showUndoMove() {
$('[data-ui="undo-move"]').hidden = !canUndoMove();
}
const doMove = async (m) => {
if (!canAct()) return;
busy = true;
$(".game-message").textContent = "";
render();
try {
await onMove(m);
} catch (e) {
$(".game-message").textContent = e.message;
} finally {
busy = false;
render();
}
};
function actionButton(m, index, extra = "") {
return `<button class="action ${m.type === "done" || m.type === "eat" ? "primary" : "secondary"} ${extra}" data-move="${index}">${moveLabel(m, state)}</button>`;
}
function render() {
showUndoMove();
if (!state) return;
activity.update(state);
const t = state.tasks[0],
taskKey = JSON.stringify(t),
actor = state.actor;
if (oldTask !== taskKey) {
oldTask = taskKey;
mealSource = undefined;
if (t?.a) selected = t.a;
viewPlayer = replaying ? (actor ?? seat ?? 0) : (seat ?? actor ?? 0);
if (replaying && !t?.a) selected = colony(state, viewPlayer)[0]?.id;
}
const a = findAmoeba(state, selected) ?? colony(state, viewPlayer ?? 0)[0];
selected = a?.id;
const shown = viewPlayer ?? seat ?? actor ?? 0,
pl = state.players[shown];
$(".soup-board-key").innerHTML = renderScoring(shown);
$(".players").style.setProperty(
"--player-columns",
Math.min(4, state.players.length),
);
$(".players").innerHTML = state.players
.map(
(p, i) =>
`<button class="player ${i === actor ? "active" : ""}" data-player="${i}" data-bgs-player="${i}" style="--player:${colors[p.color].shade}"><span class="player-color"></span><span class="player-portrait">${amoeba(p.color, i, colonyTraits(p.genes))}</span><span class="player-info"><span class="player-name">${esc(p.name)}${playerBadge(i)}${i === seat && p.name !== "You" ? '<span class="you-tag">You</span>' : ""}</span><span class="player-stat"><span class="resource-amount player-population" role="img" aria-label="${colony(state, i).length} living amoebas" title="Living amoebas">${amoeba(p.color)}<span>${colony(state, i).length}</span></span><span aria-hidden="true">·</span><span class="resource-amount" role="img" aria-label="${geneCount(state, i)} genes" title="Genes">${icon("gene")}${geneCount(state, i)}</span></span></span><span class="player-balances"><span class="player-bp">${bp(p.bp)}</span><span class="player-sensitivity ${mutation(state, i) < 0 ? "protective" : ""}" role="img" aria-label="Total sensitivity ${mutation(state, i)}" title="${SENSITIVITY_HELP}">${icon("sun")}<b>${mutation(state, i)}</b></span><span class="player-score-group"><span class="player-score" title="Evolution points">${icon("spark")}${p.score}</span>${state.closed ? "" : `<span class="player-income" role="img" aria-label="${evolution(state, i)} evolution points per round with the current colony" title="Projected evolution points per round with the current amoebas and genes. Occupied score spaces are skipped in addition."><b>+${evolution(state, i)}</b><span class="income-unit"> / round</span></span>`}</span></span></button>`,
)
.join("");
const positions = actions().filter((m) =>
["place", "divide"].includes(m.type),
);
if (positions.length && !positions.some((m) => m.n === number))
number = positions[0].n;
const cellMoves = actions().filter(
(m) =>
["drift", "direction", "place", "divide", "excrete"].includes(m.type) &&
(!("n" in m) || m.n === number),
);
$(".cells").innerHTML = Array.from({ length: 25 }, (_, cell) => {
if (!CELLS.includes(cell)) return '<span class="land-cell"></span>';
const move = cellMoves.find((m) => m.cell === cell),
last = state.lastCells.includes(cell);
const destination = move
? ["place", "divide"].includes(move.type)
? `#${number} · ${placementPrice(state)}`
: moveLabel(move, state)
: "";
return `<button class="water-cell ${move ? "valid" : ""} ${move?.type === "drift" ? "drift" : ""} ${last ? "last-cell" : ""}" data-cell="${cell}" data-destination="${esc(destination)}" aria-label="Space ${coordinate(cell)}${move ? " · " + esc(moveLabel(move, state)) : ""}" ${move ? "" : 'aria-disabled="true"'}>${move ? `<span class="cell-destination" aria-hidden="true">${richText(destination)}</span>` : ""}<span class="cell-coord">${coordinate(cell)}</span><span class="nutrients">${nutrients(state.food[cell])}</span>${state.toxins?.[cell] ? `<span class="toxin-marker" title="${state.toxins[cell]} toxic injuries for the next entrant">☣ ${state.toxins[cell]}</span>` : ""}</button>`;
}).join("");
$(".organisms").innerHTML = state.amoebas
.map((a) => {
const group = state.amoebas.filter((b) => b.cell === a.cell),
i = group.indexOf(a),
scale = group.length > 4 ? 0.55 : group.length > 2 ? 0.72 : 1,
dx =
((i % 3) - (Math.min(group.length, 3) - 1) / 2) *
(group.length > 2 ? 54 : 45),
dy = group.length > 3 ? Math.floor(i / 3) * 48 - 24 : 0;
const hp = a.hp
? `<span class="injury" title="${a.hp} injuries">${injury(a.hp)}</span>`
: "";
return `<button class="amoeba-button ${selected === a.id ? "selected" : ""} ${t?.a === a.id ? "acting" : ""}" data-amoeba="${a.id}" aria-label="${esc(state.players[a.p].name)} amoeba #${a.n}, ${coordinate(a.cell)}${a.hp ? ", " + a.hp + " injuries" : ""}" aria-pressed="${selected === a.id}" style="--x:${(60 + (a.cell % 5) * 156 + 78 + dx) / 9}%;--y:${(55 + Math.floor(a.cell / 5) * 105 + 49 + dy) / 6.5}%;--scale:${scale};--delay:-${a.n * 0.7}s;--amoeba-paper:${colors[COLORS[a.p]].light};--amoeba-ink:${colors[COLORS[a.p]].stroke}">${amoeba(COLORS[a.p], a.n, colonyTraits(state.players[a.p].genes))}<span class="amoeba-number">${a.n}</span>${hp}</button>`;
})
.join("");
const movementActions = actions();
const driftMoves = movementActions
.map((move, index) => ({ move, index }))
.filter(({ move }) => move.type === "drift");
const swimIndex = movementActions.findIndex((m) =>
["swim", "swim-again"].includes(m.type),
);
const movementButtons = [];
if (driftMoves.length) {
const currentCell = state.amoebas.find((a) => a.id === t.a)?.cell;
const driftTitle = `<span class="board-movement-title">${icon("arrow")} Drift</span><small>${driftMoves.length === 1 && driftMoves[0].move.cell === currentCell ? "Stay here" : "Free"}</small>`;
// Rebound may offer two destinations; opening the chooser makes no move.
movementButtons.push(
driftMoves.length === 1
? `<button class="action secondary board-movement board-drift" data-move="${driftMoves[0].index}" aria-label="Drift · free">${driftTitle}</button>`
: `<details class="board-drift-choice"><summary role="button" class="action secondary board-movement board-drift" aria-label="Drift · free">${driftTitle}</summary><div class="board-drift-destinations">${driftMoves.map(({ move, index }) => `<button class="action secondary" data-move="${index}">${move.cell === currentCell ? "Stay here" : `<span>Drift</span><span translate="no">${coordinate(move.cell)}</span>`}</button>`).join("")}</div></details>`,
);
}
if (swimIndex >= 0) {
const again = movementActions[swimIndex].type === "swim-again";
const free =
again || state.players[seat].genes.some((g) => g.id === "streamline");
const title = again
? "Swim again for free before feeding."
: state.players[seat].genes.some((g) => g.id === "movement2")
? "Swim: choose a direction."
: "Swim: roll for a direction.";
movementButtons.push(
`<button class="action primary board-movement board-swim" data-move="${swimIndex}" title="${title}" aria-label="${again ? "Swim again" : "Swim"} · ${free ? "free" : "1 biological point"}"><span class="board-movement-title">${icon("wave")} ${again ? "Swim again" : "Swim"}</span><small>${free ? "Free" : bp(1)}</small></button>`,
);
}
$(".board-actions").hidden = movementButtons.length === 0;
$(".board-actions").innerHTML = movementButtons.join("");
const direction = state.environment.direction;
$(".board").dataset.current = ["west", "north", "east", "south", "still"][
direction
];
$(".compass-arrow").textContent = direction === 4 ? "·" : "➜";
$(".compass-arrow").style.transform =
`rotate(${[180, 270, 0, 90, 0][direction]}deg)`;
$(".compass-label").textContent = DIRECTIONS[direction].toUpperCase();
$(".ozone").textContent = state.environment.ozone;
$(".environment-ozone").setAttribute(
"aria-label",
`Ozone layer ${state.environment.ozone}. ${OZONE_HELP}`,
);
const forecast = state.foreseenEnvironment;
$(".private-forecast").hidden = !forecast;
$(".private-forecast").textContent = forecast
? `Private forecast · Next environment: ${DIRECTIONS[forecast.direction]}, ozone ${forecast.ozone}. Only you can see this.`
: "";
$(".game-progress").innerHTML =
`<div class="round-progress"><span>${state.round ? `Round <strong>${state.round}</strong>` : "Setup"}</span><span class="round-meter" role="img" aria-label="${state.round} of ${ROUND_LIMIT} rounds">${Array.from({ length: ROUND_LIMIT }, (_, i) => `<span class="${i < state.round ? "reached" : ""}"></span>`).join("")}</span></div><span class="game-finish" title="The game ends after round ${ROUND_LIMIT}, or earlier if a colony reaches 42 evolution points at the end of a round. Highest score wins.">Ends: round <strong>${ROUND_LIMIT}</strong> or ${evolutionPoints(42)}</span>`;
$(".last-move").innerHTML = journalEntryHtml(
state.log.at(-1),
state.players,
);
$(".food-reserve").innerHTML =
`<small>Supply</small>${nutrients(state.supply)}`;
$(".colony-panel").innerHTML =
`<div class="colony-heading"><div><span class="eyebrow">${shown === seat ? "YOUR COLONY" : "THE COLONY"}</span><h2>${esc(pl.name)}</h2></div><div class="bio-balance" data-tutorial="bp" title="Biological points">${icon("bio")}<strong>${pl.bp}</strong><span>BP</span></div></div><div class="specimen"><div class="specimen-orbit"></div><div id="selected-portrait">${amoeba(pl.color, a?.n ?? 1, colonyTraits(pl.genes))}</div><span class="specimen-coord">${a ? coordinate(a.cell) : "—"}</span></div><div class="specimen-heading"><h3>${a ? `Amoeba #${a.n}` : "Ready to grow"}</h3><span class="health ${a?.hp ? "hurt" : ""}">${a?.hp ? injury(a.hp) : "Feeling great"}</span></div><div class="diet"><span>Food colours</span><div>${state.players.map((_, p) => (p !== shown ? food(p) : "")).join("")}</div></div>${positions.length ? `<label class="amoeba-picker">New amoeba <select aria-label="Amoeba number">${[...new Set(positions.map((m) => m.n))].map((n) => `<option value="${n}" ${n === number ? "selected" : ""}>#${n}</option>`).join("")}</select><span class="placement-price">${placementCost(state) ? bp(placementCost(state)) : "Free"}</span></label>` : ""}<div class="gene-heading"><h3>Genes <span>${geneCount(state, shown)}</span></h3><button class="text-button" data-ui="genes">${t?.kind === "genes" && canAct() ? "Evolve ↗" : "Gene pool ↗"}</button></div><div class="gene-list" data-tutorial="genes">${pl.genes.map((g) => `<button class="gene ${isNewGene(g.id) ? "gene--new" : ""}" data-gene="${g.id}"><span class="gene-art">${geneIcon(g.id)}</span><span class="gene-text"><strong>${newGeneMark(g.id)}${GENE[g.id].name} ${geneScoringMark(g.id)}</strong><p>${richText(geneSummary(g.id, state.players.length))}</p></span><span class="gene-sensitivity ${geneFor(g.id, state.players.length).mutation < 0 ? "protective" : ""}" title="${SENSITIVITY_HELP}" aria-label="${geneFor(g.id, state.players.length).mutation} mutation sensitivity. ${SENSITIVITY_HELP}">${icon("sun")}<b>${geneFor(g.id, state.players.length).mutation}</b></span></button>`).join("") || '<p class="empty-genes">No genes yet. New abilities evolve in phase 3.</p>'}</div><div class="colony-metrics"><span>${icon("sun")} <strong>${mutation(state, shown)}</strong> mutation</span><span title="Evolution points earned at the end of the round with the current amoebas and genes">${evolutionPoints(`+${evolution(state, shown)}`)}</span></div>`;
$(".round-number").textContent = state.round || "—";
$(".phase-label").textContent = state.closed
? state.finished
? "Game complete"
: "Game ended"
: typeof state.phase === "number"
? `${state.phase + 1} / 6 · ${PHASES[state.phase]}`
: "Life begins · Setup";
const prompt = instruction(state, seat);
const actingAmoeba = findAmoeba(state, t?.a);
$(".phase-instruction").innerHTML =
actingAmoeba && state.actor === seat
? prompt
.split(`Amoeba #${actingAmoeba.n}`)
.map(richText)
.join(
playerReference(state.players[actingAmoeba.p], actingAmoeba.n),
)
: richText(prompt);
$(".phase-steps").innerHTML = PHASES.map((p, i) => {
const income = i === 3 ? roundIncome(state.players.length) : undefined;
const turnOrder =
i === 0
? "Lowest scorer first."
: i === 5
? "Automatic scoring, highest scorer first."
: "Highest scorer first.";
const label = `${i + 1}. ${p}${i === 1 ? " · Reveal a new environment card (current and ozone), then check sensitivity." : income ? ` · Receive ${income} biological points` : ""} · ${turnOrder}`;
const automatic =
i === 1
? `<span class="phase-environment" aria-hidden="true">${icon("environment-card")}</span>`
: income
? `<span class="phase-income">${bp(`+${income}`)}</span>`
: "";
const symbols = automatic
? `${automatic}<span class="phase-detail" aria-hidden="true">${icon(PHASE_ICONS[i])}</span>`
: icon(PHASE_ICONS[i]);
return `<li tabindex="0" title="${esc(label)}" aria-label="${esc(label)}" ${!state.closed && state.phase === i ? 'aria-current="step"' : ""} class="${typeof state.phase === "number" && i < state.phase ? "complete" : ""}"><span aria-hidden="true">${i + 1}</span>${symbols}</li>`;
}).join("");
const meals = actions().filter((m) => m.type === "eat");
const sources = [...new Set(meals.map((m) => m.source ?? "local"))];
if (!sources.includes(mealSource)) mealSource = sources[0];
const sourcePicker =
sources.length > 1
? `<label class="meal-source">Food source <select aria-label="Food source">${sources.map((source) => `<option value="${source}" ${source === mealSource ? "selected" : ""}>${source === "local" ? "This space only" : `Suction from ${coordinate(source)}`}</option>`).join("")}</select></label>`
: "";
$(".action-buttons").innerHTML =
sourcePicker +
`${canAct() && t.kind === "genes" ? '<button class="action primary" data-ui="genes">' + icon("gene") + " Evolve genes</button>" : ""}${actions()
.map((m, i) =>
[
"place",
"divide",
"buy",
"exchange",
"direction",
"drift",
"swim",
"swim-again",
"excrete",
].includes(m.type) ||
(m.type === "eat" && (m.source ?? "local") !== mealSource)
? ""
: actionButton(m, i),
)
.join(
"",
)}${state.closed ? `<button class="action primary" data-ui="results">${state.finished ? "Final scores" : "Scores"}</button>` : ""}`;
if (canAct() && state.undoPlayer === seat)
$(".turnbar .action-buttons").insertAdjacentHTML(
"beforeend",
`<button class="action secondary" data-undo title="Undo the last action. Available before a roll, reveal or turn handoff.">${icon("undo")} Undo</button>`,
);
if (dialog.open) renderModal();
}
function renderScoring(player, expandable = true) {
return scoringLegend(
colony(state, player).length,
geneCount(state, player),
state.players[player].color,
expandable,
state.players.length,
state.players.map((p, i) => ({
name: p.name,
color: p.color,
population: colony(state, i).length,
genes: geneCount(state, i),
})),
);
}
function sensitivityBadge(g) {
return `<div class="sensitivity-badge ${g.mutation < 0 ? "protective" : ""}" role="img" tabindex="0" title="${SENSITIVITY_HELP}" aria-label="${g.mutation} mutation sensitivity. ${SENSITIVITY_HELP}"><span class="sensitivity-value">${icon("sun")}<strong>${g.mutation < 0 ? "−" + Math.abs(g.mutation) : g.mutation}</strong></span></div>`;
}
function renderGeneCard(g) {
const held = state.players.reduce(
(n, p) => n + p.genes.filter((x) => x.id === g.id).length,
0,
);
const remaining = copiesOf(g, state.players.length) - held;
const viewer = seat ?? state.actor ?? 0;
const price =
seat === undefined ? g.cost : genePurchaseCost(state, seat, g.id);
const moves = actions()
.map((m, i) => ({ m, i }))
.filter(
({ m }) => ["buy", "exchange"].includes(m.type) && m.gene === g.id,
);
const owned = state.players[viewer].genes.some((x) => x.id === g.id);
const trading = g.id === "social" && held && !owned;
let unavailable = owned
? "Already owned"
: !remaining
? trading
? "May transfer to the last colony"
: "All copies owned"
: "";
if (!unavailable && canAct() && state.tasks[0]?.kind === "genes") {
if (g.id === "social") unavailable = "Only the last colony can buy";
else if (
g.base.length &&
!state.players[viewer].genes.some(
(x) => g.base.includes(x.id) && x.round < state.round,
)
)
unavailable = "Requires an earlier gene";
else if (state.players[viewer].bp < price) unavailable = "Not enough BP";
}
const buttons = moves
.map(({ m, i }) =>
m.type === "buy"
? `<button class="action primary" data-move="${i}">${icon("gene")} Evolve${m.base ? ` with ${geneLabel(m.base)}` : ""}</button>`
: actionButton(m, i),
)
.join("");
return `<article class="shop-card ${isNewGene(g.id) ? "shop-card--new" : ""}" data-tutorial="gene-${g.id}"><div class="shop-art"><div class="shop-illustration">${geneArt(g.id)}</div>${sensitivityBadge(g)}</div><div class="shop-body"><div class="shop-title"><h3>${newGeneMark(g.id)}${g.name}</h3>${geneScoringMark(g.id)}</div><div class="gene-facts"><div class="gene-cost"><span>${price !== g.cost ? "Your cost" : "Cost"}</span><strong>${bp(price)}<small>BP</small></strong></div><div class="gene-stock ${remaining ? "" : "is-empty"}"><span>Available</span><strong>${remaining}</strong></div></div><p>${richText(g.text)}</p>${g.base.length ? `<small class="gene-prerequisite">${richText(`Trade in ${g.base.map((id) => GENE[id].name).join(" or ")}, owned since a previous round.`)}</small>` : ""}${buttons || (unavailable ? `<span class="gene-unavailable">${unavailable}</span>` : "")}</div></article>`;
}
function renderModal() {
if (!state) return;
let html = "";
if (modalKind === "genes") {
const canShop =
!state.closed &&
seat !== undefined &&
seat === state.actor &&
state.tasks[0]?.kind === "genes";
const buyable = new Set(
state.moves
.filter((move) => ["buy", "exchange"].includes(move.type))
.map((move) => move.gene),
);
const filtering = buyableOnly && canShop;
const families = geneFamilies(
genesInGame(state).filter((gene) => !filtering || buyable.has(gene.id)),
);
const groups = [
{
title: "New genes",
extra: true,
families: families.filter((family) =>
family.some((g) => isNewGene(g.id)),
),
},
{
title: "Standard genes",
extra: false,
families: families.filter(
(family) => !family.some((g) => isNewGene(g.id)),
),
},
].filter((group) => group.families.length);
html = `<div class="pool-header"><div><h2>Gene pool</h2><p>${canAct() && state.tasks[0].kind === "genes" ? `${bp(state.players[seat].bp)} to spend` : "Buy during phase 3"}</p></div><div class="pool-guide" role="img" tabindex="0" title="${OZONE_HELP}" aria-label="Ozone layer ${state.environment.ozone}. ${OZONE_HELP}">${icon("ozone")}<strong>${state.environment.ozone}</strong></div></div><div class="pool-filters"><button class="action ${filtering ? "primary" : "secondary"}" data-ui="filter-buyable" aria-pressed="${filtering}" title="${canShop ? "Show only genes you can buy or exchange now." : "Buy during phase 3"}" ${canShop ? "" : "disabled"}><span>Buyable</span>${canShop ? `<small>${buyable.size}</small>` : ""}</button></div>${filtering && !families.length ? '<p class="pool-empty" role="status">No genes available to buy.</p>' : ""}${groups.map((group) => `<section class="pool-section ${group.extra ? "pool-section--new" : ""}" aria-label="${group.title}"><div class="pool-heading"><h3>${group.extra ? '<span class="new-gene-star" aria-hidden="true">★</span>' : icon("gene")}${group.title}</h3><span>${group.families.flat().filter((g) => !group.extra || isNewGene(g.id)).length} ${group.extra ? "revealed" : "types"}</span></div>${group.extra ? `<p class="market-status" title="Two new genes are revealed in phase 3, after the leader finishes buying.">${state.newGeneMarket.remaining} unrevealed · +2 per round</p>` : ""}<div class="shop-grid">${group.families.map((family) => `<div class="shop-family" style="--gene-count:${family.length}"${family.length > 1 ? ` role="group" aria-label="${esc(family.map((g) => g.name).join(" / "))}"` : ""}>${family.map(renderGeneCard).join("")}</div>`).join("")}</div></section>`).join("")}`;
} else if (modalKind === "scoring") {
const player = viewPlayer ?? seat ?? state.actor ?? 0;
html = `<h2>Scoring each round</h2><p>Look up your living amoebas and your gene total, then add the two rows. These points belong to the whole colony.</p><div class="scoring-detail">${renderScoring(player, false)}</div><p>Advanced genes count as two; Ray Protection counts as zero. Score every round. Skip occupied scores on the track.</p>`;
} else if (modalKind === "results")
html = `<h2>${state.finished ? "Final scores" : "Scores"}</h2>${state.finished ? `<p>${esc(state.players[state.winner]?.name ?? "")} wins.</p>` : ""}<ol class="results-list">${state.players
.map((p, i) => ({ ...p, index: i }))
.sort((a, b) => b.score - a.score)
.map(
(p) =>
`<li>${amoeba(p.color)}<strong>${esc(p.name)}${playerBadge(p.index)}</strong><b>${p.score}</b></li>`,
)
.join(
"",
)}</ol>${state.nextGameChooser !== undefined ? `<p>${esc(state.players[state.nextGameChooser].name)} chooses the next game with ${geneLabel("doris-frank")}.</p>` : ""}`;
else if (GENE[modalKind]) {
const g = geneFor(modalKind, state.players.length);
const color = state.players[modalPlayer].color;
html = `<div class="gene-detail-hero"><div class="gene-explainer-art">${geneArt(g.id, color)}</div>${sensitivityBadge(g)}</div>${newGeneMark(g.id, true)}<h2>${g.name} ${geneScoringMark(g.id)}</h2><p>${richText(g.text)}</p><div class="gene-detail-cost"><span>Cost</span><strong>${bp(g.cost)} BP</strong></div><p>Counts as ${g.points} gene${g.points === 1 ? "" : "s"} when calculating evolution points.</p><div class="action-buttons">${actions()
.map((m, i) =>
m.type === "discard" && m.gene === g.id ? actionButton(m, i) : "",
)
.join("")}</div>`;
} else
html = `<span class="eyebrow">HOW LIFE WORKS</span><h2>Welcome to the soup.</h2><p>Grow your population and evolve genes. At the end of each round, earn evolution points from your amoebas and genes. Advance along the evolution track, skipping occupied scores. When a colony reaches 42 points — or the last environment card is revealed — finish the round. The highest score wins.</p><div class="help-steps"><section><h3>1 · Move & feed</h3><p>Lowest score first; amoebas act in number order. Drift with the current for free, or pay 1 BP to swim: roll a die for direction. 1 west, 2 north, 3 east, 4 south, 5 stay, 6 choose. A blocked move stays in place.</p></section><section><h3>Food & injuries</h3><p>${state.players.length >= 5 ? "Eat four nutrients of four different colours, never your own. With six colonies, choose which other colour to leave out." : "Eat three nutrients, never your own colour. With four colonies, eat one of each other colour; with three, eat two of one and one of the other."} After eating, excrete two nutrients of your own colour onto the same space. If you cannot eat, excrete nothing and take one injury instead.</p></section><section><h3>2 · Environment</h3><p>A new card sets the next current and ozone layer. If your mutation exceeds the ozone, pay the difference in BP or discard genes. No defects in round one.</p></section><section><h3>3 · New genes</h3><p>Highest score first. Buy as many genes as you can afford. Advanced genes replace a prerequisite owned since a previous round.</p></section>${state.newGeneMarket ? "<section><h3>Freshly Spiced genes</h3><p>Social Gene and Population Explosion start in the pool. Two shuffled genes appear after the leader finishes buying each round. Revealed genes remain available. Select any gene to read its effect.</p></section>" : ""}<section><h3>4 · Cell division</h3><p>Receive ${roundIncome(state.players.length)} BP. You can have at most ${amoebaLimit(state.players.length)} amoebas. Each new amoeba costs 6 BP and goes next to one of yours, without sharing your colour's space. With one amoeba, the second may go anywhere. With none, the first returns anywhere for free.</p></section><section><h3>5 · Survival</h3><p>Two injuries cause death, or three with Longevity. Return two food cubes of every colour to that space. Aggression happens after natural deaths.</p></section><section><h3>6 · Evolution points</h3><p>Your living amoebas and genes earn points automatically. See the scoring table on the board.</p></section><section><h3>Food supply</h3><p>There are 55 cubes of each colour. If the supply runs out, place only the cubes still available. Dead amoeba numbers may be used again.</p></section></div><p class="rules-links"><a href="${SIMPLE_RULES_URL}" target="_blank" rel="noopener">Simplified rules ↗</a><a href="${RULES_URL}" target="_blank" rel="noopener">Original rules (PDF) ↗</a></p>`;
$(".modal-content").innerHTML = html;
if (modalKind === "rules") {
for (const text of $(".modal-content").querySelectorAll(
".help-steps p",
)) {
text.innerHTML = richText(
text.firstElementChild?.getAttribute("data-localized-rich-text") ??
text.textContent,
);
}
}
}
function open(kind) {
modalKind = kind;
modalPlayer = viewPlayer ?? seat ?? state?.actor ?? 0;
renderModal();
if (!dialog.open) dialog.showModal();
}
async function toggleFullscreen() {
$(".game-message").textContent = "";
try {
if (onFullscreen) await onFullscreen();
else if (document.fullscreenElement) await document.exitFullscreen();
else if (root.requestFullscreen) await root.requestFullscreen();
else throw new Error("Fullscreen is not available in this browser.");
} catch (error) {
$(".game-message").textContent =
error.message || "Fullscreen could not be opened.";
}
}
root.addEventListener("click", (e) => {
const el = e.target.closest("button");
if (!el) return;
if (el.hasAttribute("data-undo")) {
void doMove({ type: "undo" });
return;
}
if (el.dataset.move !== undefined) {
void doMove(actions()[Number(el.dataset.move)]);
return;
}
if (el.dataset.cell !== undefined) {
const cell = Number(el.dataset.cell);
const m = actions().find(
(m) => m.cell === cell && (!("n" in m) || m.n === number),
);
if (m) void doMove(m);
return;
}
if (el.dataset.amoeba) {
const a = findAmoeba(state, el.dataset.amoeba);
const m = actions().find(
(m) => m.cell === a.cell && ["drift", "direction"].includes(m.type),
);
if (m) {
void doMove(m);
return;
}
selected = a.id;
viewPlayer = a.p;
render();
return;
}
if (el.dataset.player !== undefined) {
viewPlayer = Number(el.dataset.player);
selected = colony(state, viewPlayer)[0]?.id;
render();
return;
}
if (el.dataset.gene) {
open(el.dataset.gene);
return;
}
if (el.dataset.ui === "close") {
dialog.close();
return;
}
if (el.dataset.ui === "filter-buyable") {
buyableOnly = !buyableOnly;
renderModal();
$('[data-ui="filter-buyable"]').focus({ preventScroll: true });
return;
}
if (el.dataset.ui === "chat" || el.dataset.ui === "journal") {
activity.open(el.dataset.ui);
return;
}
if (el.dataset.ui === "undo-move") {
if (canUndoMove()) {
$(".game-message").textContent = "";
onUndo?.();
}
return;
}
if (el.dataset.ui === "colony-symbols") {
setColorBlind(!colonySymbols);
onColorBlindChange?.(colonySymbols);
return;
}
if (el.dataset.ui === "fullscreen") {
void toggleFullscreen();
return;
}
if (el.dataset.ui) open(el.dataset.ui);
});
root.addEventListener("change", (e) => {
if (e.target.matches('[aria-label="Food source"]')) {
mealSource =
e.target.value === "local" ? "local" : Number(e.target.value);
render();
} else if (e.target.matches("select")) {
number = Number(e.target.value);
render();
}
});
return {
root,
guide: $(".tutorial-slot"),
setPlayerAppearance(preferences) {
appearance = preferences.bgs ?? {};
setPlayerSymbols(appearance.playerSymbols);
setPlayerColors(
preferences.bgs?.playerColors ?? [],
preferences.colorBlind !== true,
);
render();
},
setColorBlind,
render(s) {
state = viewerState(s);
state.replaying = replaying;
render();
},
setReplayMode(enabled) {
replaying = enabled;
if (state) state.replaying = enabled;
root.classList.toggle("replaying", enabled);
dialog.close();
render();
},
setChatNotifications: activity.setChatNotifications,
setAnalysisMode(enabled) {
analysis = enabled;
const button = $('[data-ui="chat"]');
if (button) button.hidden = enabled;
activity.setAnalysisMode(enabled);
showUndoMove();
},
setUndoAvailable(available) {
undoAvailable = available === true;
showUndoMove();
},
// An earlier position replaces the abandoned turn (BGS "Undo my move"):
// forget its local choices. The next render picks the defaults again, as
// for a new task (own colony, acting amoeba, food source).
resetSelection() {
oldTask = undefined;
selected = undefined;
number = 1;
$(".game-message").textContent = "";
},
setPlayer(p) {
seat = p;
viewPlayer = p;
render();
},
setEnabled(enabled) {
locked = !enabled;
render();
},
closeModal() {
dialog.close();
},
destroy() {
activity.destroy();
dialog.close();
root.remove();
},
};
}