Render ended and cancelled BGS games from saved snapshots

This commit is contained in:
coyotte508 2026-09-19 14:10:24 +02:00
commit 037325e655
3 changed files with 75 additions and 8 deletions

52
test/viewer-state.test.js Normal file
View file

@ -0,0 +1,52 @@
import test from "node:test";
import assert from "node:assert/strict";
import * as E from "../engine/index.js";
import { viewerState } from "../viewer/state.js";
const saved = (state) => JSON.parse(JSON.stringify(state));
test("a cancelled game's raw snapshot is read-only even with unfinished tasks", () => {
let state = E.init(3, [], {}, "cancelled-viewer");
for (let i = 0; i < 30; i++) state = E.moveAI(state, E.currentPlayer(state));
const raw = saved(state);
assert.ok(!raw.finished && raw.tasks.length);
assert.ok(E.legalMoves(raw).length);
const active = viewerState(saved(E.stripSecret(raw)));
assert.equal(active.closed, false);
assert.equal(active.actor, E.currentPlayer(raw));
assert.deepEqual(active.moves, E.legalMoves(raw));
const cancelled = viewerState(raw);
assert.equal(cancelled.closed, true);
assert.equal(cancelled.actor, undefined);
assert.deepEqual(cancelled.moves, []);
assert.equal(cancelled.winner, undefined);
assert.deepEqual(cancelled.players, raw.players);
assert.deepEqual(
raw,
saved(state),
"Rendering must not mutate the saved game",
);
});
test("completed games reload from raw and stripped snapshots with the same winner and scores", () => {
for (const count of [3, 4]) {
let state = E.init(count, [], {}, "completed-viewer");
for (let i = 0; !E.ended(state) && i < 2000; i++)
state = E.moveAI(state, E.currentPlayer(state));
assert.ok(E.ended(state));
for (const snapshot of [state, E.stripSecret(state)]) {
const view = viewerState(saved(snapshot));
assert.equal(view.closed, true);
assert.equal(view.finished, true);
assert.equal(view.winner, state.winner);
assert.deepEqual(
view.players.map((p) => p.score),
E.scores(state),
);
assert.equal(view.actor, undefined);
assert.deepEqual(view.moves, []);
}
}
});

11
viewer/state.js Normal file
View file

@ -0,0 +1,11 @@
export function viewerState(data) {
// BGS sends the raw saved state after a game ends or is cancelled. Only
// active games carry the moves and actor fields added by stripSecret.
const closed = !!data.finished || !Array.isArray(data.moves);
return {
...data,
closed,
actor: closed ? undefined : data.actor,
moves: closed ? [] : data.moves,
};
}

View file

@ -30,6 +30,7 @@ import {
} from "./rich-text.js";
import { mountActivity } from "./activity.js";
import { pondArt } from "./pond.js";
import { viewerState } from "./state.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 =
@ -114,6 +115,7 @@ export function moveLabel(m, s) {
}
function instruction(s, seat) {
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);
@ -189,7 +191,7 @@ export function mountGame(
const canAct = () =>
!busy &&
!locked &&
!state?.finished &&
!state?.closed &&
seat !== undefined &&
state?.actor === seat;
const actions = () => (canAct() ? state.moves : []);
@ -275,8 +277,8 @@ export function mountGame(
`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."
$("#turn-order").textContent = state.closed
? "Game ended."
: `${state.deckRemaining} environment cards left · ${state.actor === seat ? "Your turn" : ` ${state.players[state.actor].name}'s turn`}`;
$(".last-move").innerHTML = richText(state.log.at(-1)?.text ?? "");
$(".food-reserve").innerHTML =
@ -284,8 +286,10 @@ export function mountGame(
$(".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></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">${geneIcon(g.id)}</span><span class="gene-text"><strong>${GENE[g.id].name}</strong><p>${richText(geneSummary(g.id, state.players.length))}</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 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.finished
? "Game complete"
$(".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";
@ -303,7 +307,7 @@ export function mountGame(
)
.join(
"",
)}${state.finished ? '<button class="action primary" data-ui="results">Final scores</button>' : ""}`;
)}${state.closed ? `<button class="action primary" data-ui="results">${state.finished ? "Final scores" : "Scores"}</button>` : ""}`;
if (dialog.open) renderModal();
}
function renderModal() {
@ -329,7 +333,7 @@ export function mountGame(
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">${scoringLegend(colony(state, player).length, geneCount(state, player), state.players[player].color, 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>A little life goes a long way.</h2><p>${esc(state.players[state.winner]?.name ?? "")} wins.</p><ol class="results-list">${state.players
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(
@ -435,7 +439,7 @@ export function mountGame(
root,
guide: $(".tutorial-slot"),
render(s) {
state = s;
state = viewerState(s);
render();
},
setPlayer(p) {