primordial-soup/viewer/ui.js

415 lines
24 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,
COLOR_NAMES,
CELLS,
GENES,
GENE,
DIRECTIONS,
PHASES,
coordinate,
} from "../engine/catalog.js";
import {
colony,
mutation,
evolution,
geneCount,
amoeba as findAmoeba,
} from "../engine/index.js";
import { amoeba, icon, colors } from "./art.js";
import { pondArt } from "./pond.js";
export const RULES_URL =
"https://s3.fr-par.scw.cloud/bgs-assets/assets/primordial-soup/rules-en/69e877694adc4a15/rules-en.pdf";
export const esc = (x) =>
String(x ?? "").replace(
/[&<>"']/g,
(c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
c
],
);
const food = (p, n = 1) =>
`<span class="food-amount" role="img" aria-label="${n} ${COLOR_NAMES[p].toLowerCase()} nutrient${n === 1 ? "" : "s"}" title="${n} ${COLOR_NAMES[p].toLowerCase()} nutrient${n === 1 ? "" : "s"}"><span class="food ${COLORS[p]}" aria-hidden="true"></span><span>${n}</span></span>`;
const nutrients = (vector) =>
vector.map((n, p) => (n ? food(p, n) : "")).join("");
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}`;
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>${s.players[s.actor].genes.some((g) => g.id === "streamline") ? 0 : 1} BP</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.host === undefined ? "" : `<small>−1 BP for ${esc(s.players[m.host].name)}</small>`}`;
case "starve":
return `${icon("heart")} Take 1 injury`;
case "pay-defect":
return `Pay ${m.amount} BP`;
case "discard":
return `Give up ${GENE[m.gene].name}`;
case "buy":
return `Evolve · ${GENE[m.gene].cost} BP`;
case "divide":
return `New amoeba #${m.n}`;
case "done":
return "Done";
case "attack":
return `${m.attacker ? ref(m.attacker) + " → " : "Attack "}${ref(m.victim)} · 1 BP`;
case "accept-attack":
return "Accept attack";
case "defend":
return "Defend · 1 BP";
case "escape":
return `Escape · ${s.players[s.actor].genes.some((g) => g.id === "streamline") ? 0 : 1} BP`;
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.finished) return `${s.players[s.winner].name} wins!`;
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 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 nutrients of your colour." : "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 "You received 10 BP. Click a highlighted space to grow your colony, or finish with Done.";
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, onFullscreen, onOpenPlayer, practice = false } = {},
) {
const root = document.createElement("div");
root.className = "soup game-shell";
target.append(root);
root.innerHTML = `<header class="topbar"><div class="brand"><span>${amoeba("green", 0)}</span><div><h1>primordial soup<span class="title-dot">.</span></h1><span class="byline">DORIS MATTHÄUS & FRANK NESTEL</span></div></div><span class="edition-tag">Private playtest</span><nav class="utilities" aria-label="Game options"><button class="quiet-button" data-ui="genes">${icon("spark")} Genes</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="pond-toolbar"><div><span class="eyebrow">A LITTLE LIFE IN A BIG SOUP</span><span class="pond-subtitle" id="turn-order"></span></div><button class="quiet-button" data-ui="journal">${icon("history")} Journal</button></div><div class="board-wrap"><div class="board" data-tutorial="board"><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"><span>CURRENT</span><div class="compass-arrow">➜</div><b class="compass-label"></b><small>Ozone <strong class="ozone"></strong></small></div><div class="soup-board-key"><span>EVOLUTION</span><b>42</b><small>Finish the round<br>when a colony reaches 42.</small></div></div></div><div class="pond-bottom"><span class="last-move" aria-live="polite"></span><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><div class="phase-dots"></div></div><div class="action-buttons"></div></footer><div class="game-message" role="alert"></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)];
let state,
seat,
selected,
viewPlayer,
number = 1,
busy = false,
locked = false,
modalKind,
oldTask;
const dialog = $("dialog");
const canAct = () =>
!busy &&
!locked &&
!state?.finished &&
seat !== undefined &&
state?.actor === seat;
const actions = () => (canAct() ? state.moves : []);
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() {
if (!state) return;
const t = state.tasks[0],
taskKey = JSON.stringify(t),
actor = state.actor;
if (oldTask !== taskKey) {
oldTask = taskKey;
if (t?.a) selected = t.a;
viewPlayer = seat ?? actor ?? 0;
}
const a = findAmoeba(state, selected) ?? colony(state, viewPlayer ?? 0)[0];
selected = a?.id;
const shown = viewPlayer ?? seat ?? actor ?? 0,
pl = state.players[shown];
$(".players").style.gridTemplateColumns =
`repeat(${state.players.length},1fr)`;
$(".players").innerHTML = state.players
.map(
(p, i) =>
`<button class="player ${i === actor ? "active" : ""}" data-player="${i}" style="--player:${colors[p.color].shade}"><span class="player-color"></span><span class="player-portrait">${amoeba(p.color, i)}</span><span class="player-info"><span class="player-name">${esc(p.name)}${i === seat && p.name !== "You" ? '<span class="you-tag">You</span>' : ""}</span><span class="player-stat">${p.bp} BP · ${colony(state, i).length} amoeba${colony(state, i).length === 1 ? "" : "s"} · ${geneCount(state, i)} genes</span></span><span class="player-score" title="Evolution points">${icon("spark")}${p.score}</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"].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);
return `<button class="water-cell ${move ? "valid" : ""} ${move?.type === "drift" ? "drift" : ""} ${last ? "last-cell" : ""}" data-cell="${cell}" data-destination="${move ? esc(["place", "divide"].includes(move.type) ? `#${number}` : moveLabel(move, state)) : ""}" aria-label="Space ${coordinate(cell)}${move ? " · " + esc(moveLabel(move, state)) : ""}" ${move ? "" : 'aria-disabled="true"'}><span class="cell-coord">${coordinate(cell)}</span><span class="nutrients">${nutrients(state.food[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 ? 37 : 45),
dy = group.length > 3 ? Math.floor(i / 3) * 30 - 15 : 0;
const hp = a.hp
? `<span class="injury" title="${a.hp} injuries">${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="left:${(60 + (a.cell % 5) * 156 + 78 + dx) / 9}%;top:${(55 + Math.floor(a.cell / 5) * 105 + 49 + dy) / 6.5}%;--scale:${scale};--delay:-${a.n * 0.7}s">${amoeba(COLORS[a.p], a.n, state.players[a.p].genes.some((g) => g.id === "armor") ? "shield" : "")}<span class="amoeba-number">${a.n}</span>${hp}</button>`;
})
.join("");
const direction = state.environment.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;
$("#turn-order").textContent = state.finished
? "A new branch on the tree of life."
: `${state.deckRemaining} environment cards left · ${state.actor === seat ? "Your turn" : ` ${state.players[state.actor].name}'s turn`}`;
$(".last-move").textContent = state.log.at(-1)?.text ?? "";
$(".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)}</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 ? `${a.hp} ${a.hp === 1 ? "injury" : "injuries"}` : "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></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" data-gene="${g.id}"><span class="gene-art">${icon(g.id === "movement1" || g.id === "movement2" ? "wave" : g.id === "division" ? "divide" : g.id === "armor" || g.id === "defense" ? "shield" : "spark")}</span><span class="gene-text"><strong>${GENE[g.id].name}</strong><p>${GENE[g.id].points === 2 ? "Advanced gene" : "Colony adaptation"}</p></span><span class="gene-sensitivity" title="Mutation sensitivity">${icon("sun")}${GENE[g.id].mutation}</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 before any further division or deaths">${icon("spark")} <strong>+${evolution(state, shown)}</strong> evolution</span></div>`;
$(".round-number").textContent = state.round || "—";
$(".phase-label").textContent = state.finished
? "Evolution complete"
: typeof state.phase === "number"
? `${state.phase + 1} / 6 · ${PHASES[state.phase]}`
: "Life begins · Setup";
$(".phase-instruction").textContent = instruction(state, seat);
$(".phase-dots").innerHTML = PHASES.map(
(p, i) =>
`<span title="${i + 1}. ${p}" class="${typeof state.phase === "number" && i <= state.phase ? "active" : ""}"></span>`,
).join("");
$(".action-buttons").innerHTML =
`${canAct() && t.kind === "genes" ? '<button class="action primary" data-ui="genes">' + icon("spark") + " Evolve genes</button>" : ""}${actions()
.map((m, i) =>
["place", "divide", "buy", "direction", "drift"].includes(m.type)
? ""
: actionButton(m, i),
)
.join(
"",
)}${state.finished ? '<button class="action primary" data-ui="results">Final scores</button>' : ""}`;
if (dialog.open) renderModal();
}
function renderModal() {
if (!state) return;
let html = "";
if (modalKind === "genes")
html = `<span class="eyebrow">THE GENE POOL</span><h2>Little changes. New possibilities.</h2><p>Each gene affects your whole colony. ${canAct() && state.tasks[0].kind === "genes" ? `You have ${state.players[seat].bp} BP to evolve.` : "Buy genes during phase 3."}</p><div class="shop-grid">${GENES.filter(
(g) => g.copies[state.players.length - 3],
)
.map((g) => {
const held = state.players.reduce(
(n, p) => n + p.genes.filter((x) => x.id === g.id).length,
0,
),
remaining = g.copies[state.players.length - 3] - held;
const moves = actions()
.map((m, i) => ({ m, i }))
.filter(({ m }) => m.type === "buy" && m.gene === g.id);
return `<article class="shop-card" data-tutorial="gene-${g.id}"><div class="shop-art">${amoeba("green", g.cost, g.id.includes("movement") ? "movement" : g.id === "armor" ? "shield" : g.id === "frugality" ? "food" : "")}</div><div class="shop-body"><h3>${g.name}</h3><span class="gene-price">${g.cost} BP · ${g.mutation} mutation · ${remaining} left</span><p>${g.text}</p>${g.base.length ? `<small>Trade in ${g.base.map((id) => GENE[id].name).join(" or ")}, owned since a previous round.</small>` : ""}${moves.map(({ m, i }) => actionButton(m, i)).join("") || `<span class="gene-unavailable">${state.players[seat ?? 0].genes.some((x) => x.id === g.id) ? "Already owned" : !remaining ? "All copies owned" : g.base.length ? "Requires an earlier gene" : `${g.cost} BP`}</span>`}</div></article>`;
})
.join("")}</div>`;
else if (modalKind === "journal")
html = `<span class="eyebrow">LIFE IN THE SOUP</span><h2>Journal</h2><ol class="journal-list">${state.log
.slice(-150)
.reverse()
.map(
(l) =>
`<li><small>Round ${l.round}</small><span>${esc(l.text)}</span></li>`,
)
.join("")}</ol>`;
else if (modalKind === "results")
html = `<h2>A little life goes a long way.</h2><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)}</strong><b>${p.score}</b></li>`,
)
.join("")}</ol>`;
else if (GENE[modalKind]) {
const g = GENE[modalKind];
html = `<div class="gene-explainer-art">${amoeba("green", g.cost)}</div><span class="eyebrow">${g.points === 2 ? "ADVANCED GENE" : "COLONY GENE"}</span><h2>${g.name}</h2><p>${g.text}</p><p>${g.cost} BP · ${g.mutation} mutation · counts as ${g.points} gene${g.points === 1 ? "" : "s"} for evolution.</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, advance along the evolution track. When a colony reaches 42 — or the last environment card is revealed — finish the round. The highest score wins.</p><p class="playtest-note">Private playtest: the exact printed environment-card distribution still needs verification. Full games currently use a provisional deck; tutorial positions are prepared.</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>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. Leave two of your own. If you cannot eat, 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><section><h3>4 · Cell division</h3><p>Receive 10 BP. 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</h3><p>3 / 4 / 5 / 6 / 7 amoebas advance 1 / 2 / 4 / 5 / 6 spaces. 3 / 4 / 5 / 6+ genes add 1 / 2 / 3 / 4. Advanced genes count twice; Ray Protection does not count. Jump over occupied scores.</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><a href="${RULES_URL}" target="_blank" rel="noopener">Read the original English rules (PDF) ↗</a></p>`;
$(".modal-content").innerHTML = html;
}
function open(kind) {
modalKind = kind;
renderModal();
if (!dialog.open) dialog.showModal();
}
root.addEventListener("click", (e) => {
const el = e.target.closest("button");
if (!el) 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 === "fullscreen") {
if (onFullscreen) onFullscreen();
else if (!document.fullscreenElement)
root.requestFullscreen?.().catch(() => {});
else document.exitFullscreen?.().catch(() => {});
return;
}
if (el.dataset.ui) open(el.dataset.ui);
});
root.addEventListener("change", (e) => {
if (e.target.matches("select")) {
number = Number(e.target.value);
render();
}
});
return {
root,
guide: $(".tutorial-slot"),
render(s) {
state = s;
render();
},
setPlayer(p) {
seat = p;
viewPlayer = p;
render();
},
setEnabled(enabled) {
locked = !enabled;
render();
},
closeModal() {
dialog.close();
},
destroy() {
dialog.close();
root.remove();
},
};
}