Add replay navigation and document BGS source delivery
This commit is contained in:
parent
b96dcf69ce
commit
ed6325b7f5
33 changed files with 679 additions and 26 deletions
15
AGENTS.md
Normal file
15
AGENTS.md
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# Agent instructions
|
||||
|
||||
## BGS publication and Git delivery
|
||||
|
||||
Whenever changes are published to BGS, commit the corresponding source, tests,
|
||||
dependency/lockfile changes and version bumps, then push them to this repository's
|
||||
`main` or `master` release branch in the same task. A BGS upload or a push only to
|
||||
a feature branch does not complete delivery. This is standing authorization to
|
||||
commit and push published changes without asking for separate confirmation.
|
||||
|
||||
Fetch and integrate the latest release-branch changes, run the relevant repository
|
||||
checks, and push without force. Update any public mirrors required by this repo's
|
||||
existing workflow too. Keep credentials, generated artifacts excluded by the repo,
|
||||
and unrelated unfinished work out of the commit. Verify the remote branch contains
|
||||
the delivered commit and report any blocker instead of claiming delivery.
|
||||
10
README.md
10
README.md
|
|
@ -43,6 +43,16 @@ Gene buying and cell division skip automatically on entry when no legal action i
|
|||
|
||||
## Publication
|
||||
|
||||
Replay uses BGS's first/previous/next/last controls with `viewer.replayable: true`.
|
||||
Positions count committed moves, so BGS can start an analysis at the same point.
|
||||
Completed and cancelled games reconstruct locally from their saved history.
|
||||
Ongoing games request a bounded `logSlice` (inclusive `end`), which adds public
|
||||
board changes and appended journal entries without exposing seeds, future cards,
|
||||
Foresight or pending undoable moves. Ordinary unbounded move notifications retain
|
||||
their original compact format. Returning from replay restores the latest live
|
||||
state. Preview the integration at `/?replay` (optionally `&players=6`). Deploy the
|
||||
engine and viewer together when enabling replay for the first time.
|
||||
|
||||
BGS entry: `primordial-soup`, version 1. Keep `public: false`, metadata `unlisted: true`, and restrict beta access. The private engine is uploaded as an npm-pack tarball to BGS storage; it is not published to npm. The original rules PDF is hosted as a separate BGS asset and linked from the rules panel.
|
||||
|
||||
Artwork is newly drawn SVG, not scans. All 26 new genes have individual illustrations in the gene pool and detail view, following the selected colony's colour. Thirteen also add board traits, including sensing antennae, camouflage, healing patches, suction tubes, a hard crust and a PhD cap. Struggle for Survival adds fangs; Aggression adds fangs, angled brows and spines. Traits combine while retaining the colony's colour and colour-blind symbol. Compare them locally at `/?appearance=genes&newGenes=1` or `/?appearance=genes`.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { sha256 } from "@noble/hashes/sha2.js";
|
||||
import { replayChange } from "./replay-view.js";
|
||||
import {
|
||||
CELLS,
|
||||
COLORS,
|
||||
|
|
@ -1508,8 +1509,15 @@ 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 logSlice(s, { start = 0, end } = {}) {
|
||||
const stop = Math.min(s.history.length, (end ?? s.history.length - 1) + 1);
|
||||
const log = s.history.slice(start, stop);
|
||||
// Ordinary move notifications remain small. The replay viewer explicitly
|
||||
// requests a bounded slice to obtain its public positions (inclusive end).
|
||||
return end === undefined
|
||||
? log
|
||||
: { log, replay: replayFrames(s, { start, end: stop }) };
|
||||
}
|
||||
export function setPlayerMetaData(s, p, meta) {
|
||||
if (typeof meta.name === "string") s.players[p].name = meta.name;
|
||||
return s;
|
||||
|
|
@ -1535,6 +1543,7 @@ export function stripSecret(data, player) {
|
|||
s.newGeneMarket = publicNewGeneMarket(data.newGeneMarket);
|
||||
s.moves = legalMoves(data);
|
||||
s.actor = currentPlayer(data);
|
||||
s.historyLength = data.history.length;
|
||||
return s;
|
||||
}
|
||||
export function dropPlayer(data, p) {
|
||||
|
|
@ -1673,6 +1682,41 @@ export function replay(data, { to = data.history.length } = {}) {
|
|||
return commitPending(state);
|
||||
}
|
||||
|
||||
/** Positions use the number of committed moves, matching BGS analysis cursors. */
|
||||
export function replayFrames(
|
||||
data,
|
||||
{ start = 0, end = data.history.length } = {},
|
||||
) {
|
||||
requireThat(
|
||||
Number.isInteger(start) &&
|
||||
Number.isInteger(end) &&
|
||||
start >= 0 &&
|
||||
start <= end &&
|
||||
end <= data.history.length,
|
||||
"Invalid replay range.",
|
||||
);
|
||||
const view = (state, position) => {
|
||||
// Spectator projection: even a player's past Foresight is not included.
|
||||
const frame = stripSecret(state);
|
||||
delete frame.undoPlayer;
|
||||
frame.moves = [];
|
||||
frame.historyLength = position;
|
||||
return frame;
|
||||
};
|
||||
let state = replay(data, { to: start });
|
||||
const initial = view(state, start),
|
||||
steps = [];
|
||||
let previous = initial;
|
||||
for (let index = start; index < end; index++) {
|
||||
const entry = data.history[index];
|
||||
state = applyMove(state, entry.move, entry.player);
|
||||
const next = view(state, index + 1);
|
||||
steps.push(replayChange(previous, next));
|
||||
previous = next;
|
||||
}
|
||||
return { start, state: initial, steps };
|
||||
}
|
||||
|
||||
export function canLaunchAnalysisMode(data) {
|
||||
return (
|
||||
!!data.initialEnvironment ||
|
||||
|
|
@ -1690,7 +1734,13 @@ export function createAnalysisScenario(data, { player, seed }) {
|
|||
);
|
||||
const s = stripSecret(data, player);
|
||||
const known = s.foreseenEnvironment;
|
||||
for (const key of ["moves", "actor", "undoPlayer", "foreseenEnvironment"])
|
||||
for (const key of [
|
||||
"moves",
|
||||
"actor",
|
||||
"undoPlayer",
|
||||
"foreseenEnvironment",
|
||||
"historyLength",
|
||||
])
|
||||
delete s[key];
|
||||
s._seed = seed;
|
||||
s._counter = 0;
|
||||
|
|
|
|||
20
engine/replay-view.js
Normal file
20
engine/replay-view.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
// Replay packets contain public board changes, never seeds or future draws.
|
||||
// Journal entries are appended separately so a full replay stays linear in size.
|
||||
export function replayChange(before, after) {
|
||||
const set = {};
|
||||
for (const [key, value] of Object.entries(after)) {
|
||||
if (key !== "log" && JSON.stringify(value) !== JSON.stringify(before[key]))
|
||||
set[key] = value;
|
||||
}
|
||||
return {
|
||||
set,
|
||||
remove: Object.keys(before).filter((key) => !(key in after)),
|
||||
log: after.log.slice(before.log.length),
|
||||
};
|
||||
}
|
||||
|
||||
export function applyReplayChange(state, change) {
|
||||
const next = { ...state, ...change.set, log: [...state.log, ...change.log] };
|
||||
for (const key of change.remove) delete next[key];
|
||||
return next;
|
||||
}
|
||||
|
|
@ -11,7 +11,7 @@
|
|||
"build": "node scripts/build.mjs",
|
||||
"test": "node --test test/*.test.js",
|
||||
"dev": "node scripts/dev.mjs",
|
||||
"test:browser": "pnpm build && node test/analysis-chat-browser.mjs && node test/preferences-browser.mjs && node test/new-genes-browser.mjs && node test/turn-controls-browser.mjs",
|
||||
"test:browser": "pnpm build && node test/analysis-chat-browser.mjs && node test/preferences-browser.mjs && node test/new-genes-browser.mjs && node test/turn-controls-browser.mjs && node test/replay-browser.mjs",
|
||||
"test:locales": "node scripts/check-locales.mjs viewer/localization && node --test scripts/localization.test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
|
|
|
|||
|
|
@ -78,6 +78,7 @@ await api("/1", "PUT", {
|
|||
url: viewer.url,
|
||||
scriptBytes: files.scriptBytes,
|
||||
topLevelVariable: "primordialSoup",
|
||||
replayable: true,
|
||||
fullScreen: true,
|
||||
fullScreenMobile: true,
|
||||
dependencies: { scripts: [], stylesheets: [style.url] },
|
||||
|
|
|
|||
|
|
@ -225,6 +225,9 @@ try {
|
|||
await page.setViewportSize({ width, height: 950 });
|
||||
}
|
||||
const journalState = prepared();
|
||||
const quotedName = `O'Brien & "Co" <img src=x>`;
|
||||
journalState.players[0].name = quotedName;
|
||||
journalState.players[3].name = "coyotte508";
|
||||
journalState.log = [
|
||||
{ round: 2, phase: 0, text: "Maya #1 chooses south with Movement II." },
|
||||
{ round: 2, phase: 0, text: "Maya #1 moves to C5." },
|
||||
|
|
@ -235,6 +238,8 @@ try {
|
|||
},
|
||||
{ round: 2, phase: 0, text: "Maya #1 excretes 2 red nutrients at C5." },
|
||||
{ round: 2, phase: 0, text: "Leo #1 moves to C5.", genes: ["holding"] },
|
||||
{ round: 2, phase: 2, text: "coyotte508 didn't buy any genes." },
|
||||
{ round: 2, phase: 2, text: `${quotedName} didn't buy any genes.` },
|
||||
];
|
||||
await page.evaluate(
|
||||
(state) => e.emit("state", state),
|
||||
|
|
@ -252,6 +257,15 @@ try {
|
|||
.count(),
|
||||
1,
|
||||
);
|
||||
const passEntry = page
|
||||
.locator(".journal-event")
|
||||
.filter({ hasText: "coyotte508" });
|
||||
assert.equal(
|
||||
await passEntry
|
||||
.locator("[data-localized-rich-text]")
|
||||
.getAttribute("data-localized-rich-text"),
|
||||
"coyotte508 didn't buy any genes.",
|
||||
);
|
||||
for (const locale of ["fr", "en"]) {
|
||||
await page.evaluate(
|
||||
(locale) => e.emit("preferences", { sound: false, locale }),
|
||||
|
|
@ -268,6 +282,20 @@ try {
|
|||
);
|
||||
assert.equal(await combined.locator(".journal-amoeba").count(), 1);
|
||||
assert.equal(await combined.locator(".food-amount").count(), 4);
|
||||
const passText =
|
||||
locale === "fr" ? "n’a acheté aucun gène." : "didn't buy any genes.";
|
||||
assert.equal(
|
||||
(await passEntry.textContent()).trim(),
|
||||
`coyotte508 ${passText}`,
|
||||
);
|
||||
assert.equal(
|
||||
(await page.locator(".last-move").textContent()).trim(),
|
||||
`${quotedName} ${passText}`,
|
||||
);
|
||||
assert.equal(
|
||||
await page.locator(".last-move img, .journal-event img").count(),
|
||||
0,
|
||||
);
|
||||
assert.ok(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth,
|
||||
|
|
|
|||
|
|
@ -409,6 +409,9 @@ test("replay restores a playable analysis boundary without running dropped-playe
|
|||
const view = E.stripSecret(copy);
|
||||
const expected = E.stripSecret(snapshots[to]);
|
||||
delete expected.undoPlayer;
|
||||
// Replay commits the requested prefix, including moves which were still
|
||||
// undoable in the original snapshot at this point.
|
||||
expected.historyLength = to;
|
||||
assert.deepEqual(view, expected);
|
||||
assert.deepEqual(copy.history, state.history.slice(0, to));
|
||||
assert.equal(E.logLength(copy), to);
|
||||
|
|
|
|||
|
|
@ -63,7 +63,7 @@ test("journal preserves amoeba identities, coordinates and resource amounts", ()
|
|||
assert.match(html, /aria-label="Maya_2, amoeba 2"/);
|
||||
assert.match(html, /title="Space D2"/);
|
||||
assert.match(html, /aria-label="2 blue nutrients"/);
|
||||
assert.doesNotMatch(html, /Maya #1|Maya_2 #2/);
|
||||
assert.doesNotMatch(html.replace(/<[^>]*>/g, ""), /Maya #1|Maya_2 #2/);
|
||||
});
|
||||
|
||||
test("gene causes appear as chips on the affected journal entry and the last-move line", () => {
|
||||
|
|
|
|||
131
test/replay-browser.mjs
Normal file
131
test/replay-browser.mjs
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { chromium } from "playwright";
|
||||
import { serveAssets } from "./asset-server.mjs";
|
||||
import * as E from "../engine/index.js";
|
||||
|
||||
const assetBase = await serveAssets("dist");
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.CHROMIUM_EXECUTABLE,
|
||||
});
|
||||
let live = E.init(4, [], { newGenes: true }, "replay-browser");
|
||||
for (let i = 0; live.round < 2 || E.currentPlayer(live) !== 0; i++) {
|
||||
assert.ok(i < 500);
|
||||
live = E.moveAI(live, E.currentPlayer(live));
|
||||
}
|
||||
let finished = live;
|
||||
for (let i = 0; !finished.finished && i < 2000; i++)
|
||||
finished = E.moveAI(finished, E.currentPlayer(finished));
|
||||
assert.equal(finished.finished, true);
|
||||
|
||||
try {
|
||||
for (const width of [390, 1400]) {
|
||||
const page = await browser.newPage({ viewport: { width, height: 1000 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
await page.setContent(
|
||||
'<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div>',
|
||||
);
|
||||
await page.addStyleTag({ url: assetBase + "/viewer.css" });
|
||||
await page.addScriptTag({ url: assetBase + "/viewer.js" });
|
||||
await page.exposeFunction("loadReplay", (range) => E.logSlice(live, range));
|
||||
await page.evaluate(() => {
|
||||
window.e = primordialSoup.launch("#app");
|
||||
window.moves = [];
|
||||
e.on("move", (move) => moves.push(move));
|
||||
e.on("replay:info", (value) => (window.replayInfo = value));
|
||||
e.on("fetchLog", async (range) =>
|
||||
e.emit("gamelog", { ...range, data: await loadReplay(range) }),
|
||||
);
|
||||
e.emit("player", { index: 0 });
|
||||
});
|
||||
await page.evaluate(
|
||||
(state) => e.emit("state", state),
|
||||
E.stripSecret(live, 0),
|
||||
);
|
||||
await page.waitForSelector("[data-move]");
|
||||
await page.locator('[data-ui="genes"]').first().click();
|
||||
assert.equal(await page.locator("dialog").evaluate((el) => el.open), true);
|
||||
await page.evaluate(() => {
|
||||
e.emit("replay:start");
|
||||
e.emit("replay:to", 12);
|
||||
});
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
window.replayInfo?.current === 12 &&
|
||||
document.querySelectorAll(".organisms .amoeba-button").length === 8,
|
||||
);
|
||||
assert.equal(await page.locator("dialog").evaluate((el) => el.open), false);
|
||||
assert.equal(await page.locator(".round-number").textContent(), "1");
|
||||
assert.equal(
|
||||
await page.locator("[data-move], .water-cell.valid").count(),
|
||||
0,
|
||||
);
|
||||
assert.equal(
|
||||
await page.locator(".phase-instruction").textContent(),
|
||||
"Replay",
|
||||
);
|
||||
await page.locator('.water-cell[data-cell="6"]').click({ force: true });
|
||||
await page.locator(".amoeba-button").first().click();
|
||||
await page.locator('[data-ui="genes"]').first().click();
|
||||
assert.equal(await page.locator("dialog [data-move]").count(), 0);
|
||||
await page.locator('[data-ui="close"]').click();
|
||||
assert.deepEqual(await page.evaluate(() => moves), []);
|
||||
// Setup, ordinary moves and the journal all move backwards together.
|
||||
await page.evaluate(() => e.emit("replay:to", 0));
|
||||
assert.equal(await page.locator(".organisms .amoeba-button").count(), 0);
|
||||
assert.equal(await page.locator(".round-number").textContent(), "—");
|
||||
assert.equal(await page.locator(".journal-event").count(), 1);
|
||||
assert.match(
|
||||
await page.locator(".journal-event").textContent(),
|
||||
/Choose your starting evolution position/,
|
||||
);
|
||||
await page.evaluate(() => e.emit("replay:to", 12));
|
||||
await page.screenshot({
|
||||
path: `/tmp/soup-replay-${width}.png`,
|
||||
fullPage: true,
|
||||
});
|
||||
await page.evaluate(() => e.emit("preferences", { locale: "fr" }));
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector(".phase-instruction")?.textContent ===
|
||||
"Rediffusion",
|
||||
);
|
||||
await page.evaluate(() => e.emit("preferences", { locale: "en" }));
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector(".phase-instruction")?.textContent === "Replay",
|
||||
);
|
||||
await page.evaluate(() => e.emit("replay:end"));
|
||||
await page.waitForSelector("[data-move]");
|
||||
assert.equal(
|
||||
await page.locator(".round-number").textContent(),
|
||||
String(live.round),
|
||||
);
|
||||
// Completed games receive raw state from BGS and need no log request.
|
||||
await page.evaluate((state) => e.emit("state", state), finished);
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector(".phase-label")?.textContent === "Game complete",
|
||||
);
|
||||
await page.evaluate(() => {
|
||||
e.emit("replay:start");
|
||||
e.emit("replay:to", 12);
|
||||
});
|
||||
assert.equal(await page.locator(".round-number").textContent(), "1");
|
||||
await page.evaluate(() => e.emit("replay:to", replayInfo.end));
|
||||
assert.equal(
|
||||
await page.locator(".phase-label").textContent(),
|
||||
"Game complete",
|
||||
);
|
||||
assert.deepEqual(
|
||||
await page.locator(".player-score").allTextContents(),
|
||||
finished.players.map((p) => String(p.score)),
|
||||
);
|
||||
assert.equal(await page.locator("[data-move]").count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.close();
|
||||
console.log(`Replay browser checks passed at ${width}px`);
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
179
test/replay.test.js
Normal file
179
test/replay.test.js
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import * as E from "../engine/index.js";
|
||||
import { applyReplayChange } from "../engine/replay-view.js";
|
||||
import { createReplay } from "../viewer/replay.js";
|
||||
|
||||
function game(players = 3, complete = false) {
|
||||
let state = E.init(players, [], { newGenes: true }, "replay-support");
|
||||
state.players.forEach((p, i) => (p.name = `Colony ${i + 1}`));
|
||||
for (let i = 0; !state.finished && i < (complete ? 2000 : 25); i++)
|
||||
state = E.moveAI(state, E.currentPlayer(state));
|
||||
return state;
|
||||
}
|
||||
function publicFrame(state, position = state.history.length) {
|
||||
const view = E.stripSecret(state);
|
||||
delete view.undoPlayer;
|
||||
view.moves = [];
|
||||
view.historyLength = position;
|
||||
return view;
|
||||
}
|
||||
function at(packet, position) {
|
||||
return packet.steps
|
||||
.slice(0, position - packet.start)
|
||||
.reduce(applyReplayChange, packet.state);
|
||||
}
|
||||
function harness() {
|
||||
const renders = [],
|
||||
requests = [],
|
||||
infos = [],
|
||||
modes = [];
|
||||
const replay = createReplay({
|
||||
render: (state) => renders.push(state),
|
||||
fetchLog: (range) => requests.push(range),
|
||||
setReplayInfo: (info) => infos.push(info),
|
||||
setReplayMode: (mode) => modes.push(mode),
|
||||
});
|
||||
return { replay, renders, requests, infos, modes };
|
||||
}
|
||||
|
||||
test("completed games replay setup, intermediate positions and final scores for 3–6 colonies", () => {
|
||||
for (const count of [3, 4, 5, 6]) {
|
||||
const state = game(count, true);
|
||||
assert.equal(state.finished, true);
|
||||
const original = structuredClone(state);
|
||||
const packet = E.replayFrames(state);
|
||||
for (const position of [
|
||||
0,
|
||||
1,
|
||||
count * 3,
|
||||
Math.floor(state.history.length / 2),
|
||||
state.history.length,
|
||||
]) {
|
||||
assert.deepEqual(
|
||||
at(packet, position),
|
||||
publicFrame(E.replay(state, { to: position })),
|
||||
);
|
||||
}
|
||||
assert.deepEqual(at(packet, state.history.length), publicFrame(state));
|
||||
assert.deepEqual(state, original, "Replay must not mutate the saved game");
|
||||
assert.equal(
|
||||
packet.steps.reduce(
|
||||
(n, step) => n + step.log.length,
|
||||
packet.state.log.length,
|
||||
),
|
||||
state.log.length,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("bounded log slices use inclusive endpoints and expose only public replay data", () => {
|
||||
const state = game();
|
||||
state._knowledge = { 0: state._deck[0], 1: state._deck[1] };
|
||||
const first = E.logSlice(state, { start: 0, end: 0 });
|
||||
assert.deepEqual(first.log, state.history.slice(0, 1));
|
||||
assert.equal(first.replay.steps.length, 1);
|
||||
const part = E.logSlice(state, { start: 3, end: 7, player: 0 });
|
||||
assert.deepEqual(part.log, state.history.slice(3, 8));
|
||||
assert.equal(part.replay.start, 3);
|
||||
assert.equal(part.replay.steps.length, 5);
|
||||
assert.deepEqual(at(part.replay, 8), publicFrame(E.replay(state, { to: 8 })));
|
||||
function safe(value) {
|
||||
if (!value || typeof value !== "object") return;
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
assert.ok(!key.startsWith("_"), `Secret ${key} leaked`);
|
||||
assert.ok(
|
||||
!["history", "foreseenEnvironment", "undoPlayer"].includes(key),
|
||||
key,
|
||||
);
|
||||
safe(item);
|
||||
}
|
||||
}
|
||||
safe(part.replay);
|
||||
assert.deepEqual(
|
||||
E.logSlice(state),
|
||||
state.history,
|
||||
"Normal move notifications remain unchanged",
|
||||
);
|
||||
assert.throws(() => E.replayFrames(state, { start: -1 }), /range/);
|
||||
});
|
||||
|
||||
test("replay excludes undoable actions and records only the replacement once committed", () => {
|
||||
let state = E.init(3, [], {}, "pending-replay");
|
||||
while (state.round === 0)
|
||||
state = E.move(state, E.chooseAI(state), E.currentPlayer(state));
|
||||
const player = E.currentPlayer(state);
|
||||
const drift = E.legalMoves(state).find((m) => m.type === "drift");
|
||||
const before = E.replayFrames(state);
|
||||
const pending = E.move(state, drift, player);
|
||||
assert.equal(E.canUndo(pending, player), true);
|
||||
assert.equal(E.stripSecret(pending).historyLength, state.history.length);
|
||||
assert.deepEqual(E.replayFrames(pending), before);
|
||||
const undone = E.move(pending, { type: "undo" }, player);
|
||||
assert.deepEqual(E.replayFrames(undone), before);
|
||||
state = E.moveAI(undone, player);
|
||||
assert.deepEqual(
|
||||
at(E.replayFrames(state), state.history.length),
|
||||
publicFrame(state),
|
||||
);
|
||||
});
|
||||
|
||||
test("live replay preserves its cursor as moves arrive and restores the newest live state", () => {
|
||||
const h = harness();
|
||||
let state = game();
|
||||
h.replay.update(E.stripSecret(state, 0));
|
||||
h.replay.start();
|
||||
assert.equal(h.replay.active, true);
|
||||
assert.deepEqual(h.requests.at(-1), {
|
||||
start: 0,
|
||||
end: state.history.length - 1,
|
||||
});
|
||||
h.replay.receive(E.logSlice(state, h.requests.at(-1)));
|
||||
h.replay.to(3);
|
||||
const displayed = h.renders.at(-1);
|
||||
assert.equal(displayed.historyLength, 3);
|
||||
state = E.moveAI(state, E.currentPlayer(state));
|
||||
const latest = E.stripSecret(state, 0);
|
||||
h.replay.update(latest);
|
||||
assert.deepEqual(h.renders.at(-1), displayed);
|
||||
assert.deepEqual(h.infos.at(-1), {
|
||||
start: 0,
|
||||
current: 3,
|
||||
end: state.history.length,
|
||||
});
|
||||
assert.equal(
|
||||
h.requests.length,
|
||||
1,
|
||||
"Live updates do not refetch history while browsing an older position",
|
||||
);
|
||||
h.replay.to(state.history.length);
|
||||
const response = E.logSlice(state, h.requests.at(-1));
|
||||
h.replay.end();
|
||||
assert.equal(h.renders.at(-1), latest);
|
||||
const count = h.renders.length;
|
||||
h.replay.receive(response);
|
||||
assert.equal(
|
||||
h.renders.length,
|
||||
count,
|
||||
"A late replay response must not repaint the live board",
|
||||
);
|
||||
assert.deepEqual(h.modes, [true, false]);
|
||||
h.replay.start();
|
||||
h.replay.to(-10);
|
||||
assert.equal(h.infos.at(-1).current, 0);
|
||||
h.replay.to(1e9);
|
||||
assert.equal(h.infos.at(-1).current, state.history.length);
|
||||
});
|
||||
|
||||
test("archived, cancelled and empty games use local history without a server request", () => {
|
||||
for (const state of [game(3, true), game(), E.init(3, [], {}, "empty")]) {
|
||||
const h = harness();
|
||||
h.replay.update(state);
|
||||
h.replay.start();
|
||||
h.replay.to(0);
|
||||
assert.equal(h.requests.length, 0);
|
||||
assert.equal(h.infos.at(-1).current, 0);
|
||||
h.replay.end();
|
||||
assert.equal(h.renders.at(-1), state);
|
||||
}
|
||||
});
|
||||
|
|
@ -13,6 +13,7 @@ import { chapters } from "./tutorials.js";
|
|||
import { richText } from "./rich-text.js";
|
||||
import { mountGame } from "./ui.js";
|
||||
import { COLOR_BLIND_PREFERENCE } from "./preferences.js";
|
||||
import { createReplay } from "./replay.js";
|
||||
export async function mountLesson(target, options) {
|
||||
const chapter = chapters[options.chapter];
|
||||
if (!chapter) throw new Error("Unknown tutorial chapter.");
|
||||
|
|
@ -86,8 +87,23 @@ registerViewer(
|
|||
});
|
||||
const thumbnail = createBoardThumbnail(ctx.target);
|
||||
const removeCards = installPlayerCards(ctx.target, ctx);
|
||||
const replay = createReplay({
|
||||
render(state) {
|
||||
localization.setState(state);
|
||||
ui.render(state);
|
||||
},
|
||||
setReplayMode: ui.setReplayMode,
|
||||
fetchLog: ctx.fetchLog,
|
||||
setReplayInfo: ctx.setReplayInfo,
|
||||
});
|
||||
return {
|
||||
chat,
|
||||
onReplayStart: replay.start,
|
||||
onReplayTo: replay.to,
|
||||
onReplayEnd: replay.end,
|
||||
onLog({ data }) {
|
||||
if (!replay.receive(data)) ctx.fetchState();
|
||||
},
|
||||
onThumbnail(size) {
|
||||
return thumbnail.render(
|
||||
ctx.target.querySelector(".board"),
|
||||
|
|
@ -108,8 +124,7 @@ registerViewer(
|
|||
},
|
||||
async onState(state) {
|
||||
await localization.ready;
|
||||
localization.setState(state);
|
||||
ui.render(state);
|
||||
replay.update(state);
|
||||
if (pending) {
|
||||
clearTimeout(timeout);
|
||||
pending.resolve();
|
||||
|
|
|
|||
|
|
@ -180,7 +180,7 @@ export function renderJournalSentence(
|
|||
|
||||
function journalSentence(source, players, omitSubject) {
|
||||
const data = players.map(({ name, color }) => ({ name, color }));
|
||||
return `<span data-localized-rich-text="${escape(source).replaceAll("#", "#")}" data-journal-players="${escape(JSON.stringify(data))}"${omitSubject ? ` data-journal-omit-subject="${escape(JSON.stringify(omitSubject))}"` : ""} translate="no">${renderJournalSentence(source, data, undefined, omitSubject)}</span>`;
|
||||
return `<span data-localized-rich-text="${escape(source)}" data-journal-players="${escape(JSON.stringify(data))}"${omitSubject ? ` data-journal-omit-subject="${escape(JSON.stringify(omitSubject))}"` : ""} translate="no">${renderJournalSentence(source, data, undefined, omitSubject)}</span>`;
|
||||
}
|
||||
|
||||
function renderEntry(line, renderText, players, omitSubject) {
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} køber {p1} for {p2} BP.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} køber {p1} fra {p2} for {p3} BP.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} kasserer {p1}; resterende underskud: {p2} BP.",
|
||||
"{p0} didn't buy any genes.": "{p0} købte ingen gener."
|
||||
"{p0} didn't buy any genes.": "{p0} købte ingen gener.",
|
||||
"Replay": "Gengivelse",
|
||||
"Loading replay…": "Indlæser gengivelse…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} kauft {p1} für {p2} BP.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} kauft {p1} von {p2} für {p3} BP.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} legt {p1} ab; verbleibender Fehlbetrag: {p2} BP.",
|
||||
"{p0} didn't buy any genes.": "{p0} hat keine Gene gekauft."
|
||||
"{p0} didn't buy any genes.": "{p0} hat keine Gene gekauft.",
|
||||
"Replay": "Wiederholung",
|
||||
"Loading replay…": "Wiederholung wird geladen…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} αγοράζει το {p1} για {p2} ΒΠ.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} αγοράζει το {p1} από τον {p2} για {p3} ΒΠ.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} απορρίπτει το {p1}· υπόλοιπο ελλείμματος: {p2} ΒΠ.",
|
||||
"{p0} didn't buy any genes.": "{p0} δεν αγόρασε κανένα γονίδιο."
|
||||
"{p0} didn't buy any genes.": "{p0} δεν αγόρασε κανένα γονίδιο.",
|
||||
"Replay": "Επανάληψη",
|
||||
"Loading replay…": "Φόρτωση επανάληψης…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} buys {p1} for {p2} BP.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} buys {p1} from {p2} for {p3} BP.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} discards {p1}; remaining deficit: {p2} BP.",
|
||||
"{p0} didn't buy any genes.": "{p0} didn't buy any genes."
|
||||
"{p0} didn't buy any genes.": "{p0} didn't buy any genes.",
|
||||
"Replay": "Replay",
|
||||
"Loading replay…": "Loading replay…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} ژن {p1} را با {p2} امتیاز زیستی میخرد.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} ژن {p1} را از {p2} با پرداخت {p3} امتیاز زیستی میخرد.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} ژن {p1} را دور میاندازد؛ کسری باقیمانده: {p2} امتیاز زیستی.",
|
||||
"{p0} didn't buy any genes.": "{p0} هیچ ژنی نخرید."
|
||||
"{p0} didn't buy any genes.": "{p0} هیچ ژنی نخرید.",
|
||||
"Replay": "بازپخش",
|
||||
"Loading replay…": "در حال بارگذاری بازپخش…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} achète {p1} pour {p2} PB.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} achète {p1} à {p2} pour {p3} PB.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} défausse {p1} ; déficit restant : {p2} PB.",
|
||||
"{p0} didn't buy any genes.": "{p0} n’a acheté aucun gène."
|
||||
"{p0} didn't buy any genes.": "{p0} n’a acheté aucun gène.",
|
||||
"Replay": "Rediffusion",
|
||||
"Loading replay…": "Chargement de la rediffusion…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} {p1} को {p2} BP में खरीदता है।",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} {p2} से {p1} को {p3} BP में खरीदता है।",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} {p1} त्यागता है; शेष कमी: {p2} BP।",
|
||||
"{p0} didn't buy any genes.": "{p0} ने कोई जीन नहीं खरीदा।"
|
||||
"{p0} didn't buy any genes.": "{p0} ने कोई जीन नहीं खरीदा।",
|
||||
"Replay": "रीप्ले",
|
||||
"Loading replay…": "रीप्ले लोड हो रहा है…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} compra {p1} per {p2} PB.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} compra {p1} da {p2} per {p3} PB.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} scarta {p1}; deficit rimanente: {p2} PB.",
|
||||
"{p0} didn't buy any genes.": "{p0} non ha comprato alcun gene."
|
||||
"{p0} didn't buy any genes.": "{p0} non ha comprato alcun gene.",
|
||||
"Replay": "Replay",
|
||||
"Loading replay…": "Caricamento del replay…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} 이(가) {p1} 을(를) {p2} BP에 구매합니다.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} 이(가) {p2} 에게서 {p1} 을(를) {p3} BP에 구매합니다.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} 이(가) {p1} 을(를) 버립니다. 남은 부족분: {p2} BP.",
|
||||
"{p0} didn't buy any genes.": "{p0} 은(는) 유전자를 구매하지 않았습니다."
|
||||
"{p0} didn't buy any genes.": "{p0} 은(는) 유전자를 구매하지 않았습니다.",
|
||||
"Replay": "다시 보기",
|
||||
"Loading replay…": "다시 보기 불러오는 중…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} koopt {p1} voor {p2} BP.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} koopt {p1} van {p2} voor {p3} BP.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} legt {p1} af; resterend tekort: {p2} BP.",
|
||||
"{p0} didn't buy any genes.": "{p0} heeft geen genen gekocht."
|
||||
"{p0} didn't buy any genes.": "{p0} heeft geen genen gekocht.",
|
||||
"Replay": "Herhaling",
|
||||
"Loading replay…": "Herhaling laden…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} kupuje {p1} za {p2} PB.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} kupuje {p1} od {p2} za {p3} PB.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} odrzuca {p1}; pozostały niedobór: {p2} PB.",
|
||||
"{p0} didn't buy any genes.": "{p0} nie kupuje żadnych genów."
|
||||
"{p0} didn't buy any genes.": "{p0} nie kupuje żadnych genów.",
|
||||
"Replay": "Powtórka",
|
||||
"Loading replay…": "Wczytywanie powtórki…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} compra {p1} por {p2} PB.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} compra {p1} de {p2} por {p3} PB.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} descarta {p1}; déficit restante: {p2} PB.",
|
||||
"{p0} didn't buy any genes.": "{p0} não comprou nenhum gene."
|
||||
"{p0} didn't buy any genes.": "{p0} não comprou nenhum gene.",
|
||||
"Replay": "Reprise",
|
||||
"Loading replay…": "Carregando reprise…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} cumpără {p1} pentru {p2} PB.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} cumpără {p1} de la {p2} pentru {p3} PB.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} decartează {p1}; deficit rămas: {p2} PB.",
|
||||
"{p0} didn't buy any genes.": "{p0} nu a cumpărat niciun gen."
|
||||
"{p0} didn't buy any genes.": "{p0} nu a cumpărat niciun gen.",
|
||||
"Replay": "Reluare",
|
||||
"Loading replay…": "Se încarcă reluarea…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} покупает {p1} за {p2} БО.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} покупает {p1} у {p2} за {p3} БО.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} сбрасывает {p1}; оставшийся дефицит: {p2} БО.",
|
||||
"{p0} didn't buy any genes.": "{p0} не покупает ни одного гена."
|
||||
"{p0} didn't buy any genes.": "{p0} не покупает ни одного гена.",
|
||||
"Replay": "Повтор",
|
||||
"Loading replay…": "Загрузка повтора…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} mua {p1} với giá {p2} BP.",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} mua {p1} từ {p2} với giá {p3} BP.",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} loại bỏ {p1}; thiếu hụt còn lại: {p2} BP.",
|
||||
"{p0} didn't buy any genes.": "{p0} không mua gen nào."
|
||||
"{p0} didn't buy any genes.": "{p0} không mua gen nào.",
|
||||
"Replay": "Phát lại",
|
||||
"Loading replay…": "Đang tải phát lại…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1199,5 +1199,7 @@
|
|||
"{p0} buys {p1} for {p2} BP.": "{p0} 花費 {p2} BP購買 {p1}。",
|
||||
"{p0} buys {p1} from {p2} for {p3} BP.": "{p0} 花費 {p3} BP向 {p2} 購買 {p1}。",
|
||||
"{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} 棄掉 {p1};剩餘差額:{p2} BP。",
|
||||
"{p0} didn't buy any genes.": "{p0} 沒有購買任何基因。"
|
||||
"{p0} didn't buy any genes.": "{p0} 沒有購買任何基因。",
|
||||
"Replay": "重播",
|
||||
"Loading replay…": "正在載入重播…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ const params = new URLSearchParams(location.search),
|
|||
appearance = params.get("appearance") === "genes",
|
||||
waterPreview = params.get("appearance") === "water",
|
||||
chatPreview = params.has("chat"),
|
||||
replayPreview = params.has("replay"),
|
||||
target = document.querySelector("#game"),
|
||||
nav = document.querySelector("#preview-nav");
|
||||
nav.className = "practice-nav";
|
||||
|
|
@ -18,7 +19,12 @@ nav.innerHTML = `<span>Local preview</span><a href="/">Practice game</a><a href=
|
|||
nav.querySelector("select").addEventListener("change", (e) => {
|
||||
location.href = e.target.value ? `/?chapter=${e.target.value}` : "/";
|
||||
});
|
||||
if (waterPreview) {
|
||||
nav.insertAdjacentHTML("beforeend", '<a href="/?replay">Replay preview</a>');
|
||||
if (replayPreview) {
|
||||
const { mountReplayPreview } = await import("./replay-preview.js");
|
||||
const count = Number(params.get("players"));
|
||||
mountReplayPreview(nav, [3, 4, 5, 6].includes(count) ? count : 4);
|
||||
} else if (waterPreview) {
|
||||
const { mountWaterPreview } = await import("./water-preview.js");
|
||||
mountWaterPreview(target, params);
|
||||
} else if (chatPreview) {
|
||||
|
|
|
|||
61
viewer/replay-preview.js
Normal file
61
viewer/replay-preview.js
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import * as E from "../engine/index.js";
|
||||
|
||||
// Standalone host for exercising the same replay events used by BGS.
|
||||
export function mountReplayPreview(nav, players = 4) {
|
||||
let state = E.init(players, [], { newGenes: true }, "replay-preview");
|
||||
state.players.forEach(
|
||||
(p, i) => (p.name = ["You", "Maya", "Leo", "Nina", "Sam", "Alex"][i]),
|
||||
);
|
||||
for (let turn = 0; !state.finished && turn < 2000; turn++)
|
||||
state = E.moveAI(state, E.currentPlayer(state));
|
||||
nav
|
||||
.querySelectorAll("#new-genes, #new-three, #new-four, #new-five, #new-six")
|
||||
.forEach((el) =>
|
||||
el.id === "new-genes" ? el.closest("label").remove() : el.remove(),
|
||||
);
|
||||
nav.insertAdjacentHTML(
|
||||
"beforeend",
|
||||
`<button data-replay="start">Replay</button><button data-replay="first" aria-label="First position">⏮</button><button data-replay="previous" aria-label="Previous position">◀</button><span data-replay-position></span><button data-replay="next" aria-label="Next position">▶</button><button data-replay="last" aria-label="Last position">⏭</button><button data-replay="end">Close replay</button>`,
|
||||
);
|
||||
const emitter = window.primordialSoup.launch("#game");
|
||||
let info;
|
||||
emitter.on("replay:info", (value) => {
|
||||
info = value;
|
||||
nav.querySelector("[data-replay-position]").textContent =
|
||||
`${value.current} / ${value.end}`;
|
||||
for (const name of ["first", "previous", "next", "last"]) {
|
||||
nav.querySelector(`[data-replay="${name}"]`).disabled = [
|
||||
"first",
|
||||
"previous",
|
||||
].includes(name)
|
||||
? value.current === value.start
|
||||
: value.current === value.end;
|
||||
}
|
||||
});
|
||||
emitter.on("ready", () => {
|
||||
emitter.emit("replay:start");
|
||||
emitter.emit("replay:to", players * 3);
|
||||
});
|
||||
nav.addEventListener("click", (event) => {
|
||||
const command = event.target.closest("[data-replay]")?.dataset.replay;
|
||||
if (command === "start" || command === "end")
|
||||
emitter.emit(`replay:${command}`);
|
||||
else if (command && info)
|
||||
emitter.emit(
|
||||
"replay:to",
|
||||
{
|
||||
first: info.start,
|
||||
previous: info.current - 1,
|
||||
next: info.current + 1,
|
||||
last: info.end,
|
||||
}[command],
|
||||
);
|
||||
});
|
||||
emitter.emit("player", { index: 0 });
|
||||
emitter.emit("chat:state", {
|
||||
canSend: false,
|
||||
reason: "not-a-player",
|
||||
mentions: [],
|
||||
});
|
||||
emitter.emit("state", state);
|
||||
}
|
||||
90
viewer/replay.js
Normal file
90
viewer/replay.js
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { replayFrames } from "../engine/index.js";
|
||||
import { applyReplayChange } from "../engine/replay-view.js";
|
||||
|
||||
/** BGS owns the controls; the viewer owns the displayed historical position. */
|
||||
export function createReplay({
|
||||
render,
|
||||
setReplayMode,
|
||||
fetchLog,
|
||||
setReplayInfo,
|
||||
}) {
|
||||
let latest, packet, requestedEnd, cursor;
|
||||
let active = false;
|
||||
const length = () => latest?.historyLength ?? latest?.history?.length ?? 0;
|
||||
const cachedEnd = () => (packet ? packet.start + packet.steps.length : -1);
|
||||
|
||||
function show() {
|
||||
if (!active || !latest) return;
|
||||
if (packet && cursor >= packet.start && cursor <= cachedEnd()) {
|
||||
let state = packet.state;
|
||||
for (let i = 0; i < cursor - packet.start; i++)
|
||||
state = applyReplayChange(state, packet.steps[i]);
|
||||
render(state);
|
||||
} else if (length() === 0) {
|
||||
render(latest);
|
||||
} else {
|
||||
render({ ...latest, replayLoading: true });
|
||||
}
|
||||
setReplayInfo({ start: 0, current: cursor, end: length() });
|
||||
}
|
||||
|
||||
function load() {
|
||||
const end = length();
|
||||
if (!latest || end === 0 || cachedEnd() >= cursor || requestedEnd === end)
|
||||
return;
|
||||
// BGS provides raw saved data for ended/cancelled games. Reconstruct those
|
||||
// locally; ongoing games fetch only server-filtered public replay packets.
|
||||
if (Array.isArray(latest.history) && typeof latest._seed === "string") {
|
||||
packet = replayFrames(latest);
|
||||
return;
|
||||
}
|
||||
requestedEnd = end;
|
||||
fetchLog({ start: 0, end: end - 1 });
|
||||
}
|
||||
|
||||
return {
|
||||
get active() {
|
||||
return active;
|
||||
},
|
||||
update(state) {
|
||||
latest = state;
|
||||
if (!active) {
|
||||
render(state);
|
||||
return;
|
||||
}
|
||||
cursor = Math.min(cursor ?? length(), length());
|
||||
load();
|
||||
show();
|
||||
},
|
||||
receive(data) {
|
||||
if (!data?.replay) return false;
|
||||
const incoming = data.replay;
|
||||
if (incoming.start === 0 && incoming.steps.length >= cachedEnd())
|
||||
packet = incoming;
|
||||
if (cachedEnd() >= requestedEnd) requestedEnd = undefined;
|
||||
// A delayed response may fill the cache after leaving replay, but must
|
||||
// never repaint the live board or reopen BGS's controls.
|
||||
show();
|
||||
return true;
|
||||
},
|
||||
start() {
|
||||
active = true;
|
||||
cursor = latest ? length() : undefined;
|
||||
setReplayMode(true);
|
||||
load();
|
||||
show();
|
||||
},
|
||||
to(position) {
|
||||
if (!active || !Number.isInteger(position)) return;
|
||||
cursor = Math.min(length(), Math.max(0, position));
|
||||
load();
|
||||
show();
|
||||
},
|
||||
end() {
|
||||
active = false;
|
||||
requestedEnd = undefined;
|
||||
setReplayMode(false);
|
||||
if (latest) render(latest);
|
||||
},
|
||||
};
|
||||
}
|
||||
14
viewer/ui.js
14
viewer/ui.js
|
|
@ -171,6 +171,7 @@ export function moveLabel(m, s) {
|
|||
}
|
||||
}
|
||||
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}.`;
|
||||
|
|
@ -265,6 +266,7 @@ export function mountGame(
|
|||
number = 1,
|
||||
busy = false,
|
||||
locked = false,
|
||||
replaying = false,
|
||||
modalKind,
|
||||
modalPlayer,
|
||||
oldTask,
|
||||
|
|
@ -288,6 +290,7 @@ export function mountGame(
|
|||
const canAct = () =>
|
||||
!busy &&
|
||||
!locked &&
|
||||
!replaying &&
|
||||
!state?.closed &&
|
||||
seat !== undefined &&
|
||||
state?.actor === seat;
|
||||
|
|
@ -319,7 +322,8 @@ export function mountGame(
|
|||
oldTask = taskKey;
|
||||
mealSource = undefined;
|
||||
if (t?.a) selected = t.a;
|
||||
viewPlayer = seat ?? actor ?? 0;
|
||||
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;
|
||||
|
|
@ -751,6 +755,14 @@ export function mountGame(
|
|||
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,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue