From 1e4aed6c68061d2337c8438771d87f635cdf0204 Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Thu, 8 Oct 2026 11:36:07 +0200 Subject: [PATCH] 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 --- README.md | 8 +- package.json | 4 +- pnpm-lock.yaml | 10 +- pnpm-workspace.yaml | 2 +- test/replay.test.js | 37 +++++ test/undo-browser.mjs | 245 +++++++++++++++++++++++++++++++++ viewer/chat-preview.js | 13 ++ viewer/index.js | 14 +- viewer/localization/da.json | 3 +- viewer/localization/de.json | 3 +- viewer/localization/el.json | 3 +- viewer/localization/en.json | 3 +- viewer/localization/fa.json | 3 +- viewer/localization/fr.json | 3 +- viewer/localization/hi.json | 3 +- viewer/localization/it.json | 3 +- viewer/localization/ko.json | 3 +- viewer/localization/nl.json | 3 +- viewer/localization/pl.json | 3 +- viewer/localization/pt-BR.json | 3 +- viewer/localization/ro.json | 3 +- viewer/localization/ru.json | 3 +- viewer/localization/vi.json | 3 +- viewer/localization/zh-TW.json | 3 +- viewer/replay.js | 17 ++- viewer/style.css | 19 +++ viewer/ui.js | 48 ++++++- 27 files changed, 433 insertions(+), 32 deletions(-) create mode 100644 test/undo-browser.mjs diff --git a/README.md b/README.md index a3dc5d6..63adb43 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ pnpm dev Local practice: http://127.0.0.1:5221/ . Lessons start at `/?chapter=drift`. -Chat and journal preview: `/?chat=1`. This uses the BGS viewer protocol with local messages, unread notifications, mentions and send-failure controls; nothing is sent to other players. +Chat and journal preview: `/?chat=1`. This uses the BGS viewer protocol with local messages, unread notifications, mentions and send-failure controls; nothing is sent to other players. It also emulates BGS's **Undo my move** after each of your moves. The **Color-blind mode** button in the top toolbar adds matching colony symbols to amoebas, food and scoring markers: circle, triangle, square, diamond, cross and star. BGS saves the `colorBlind` preference to the signed-in account through the viewer protocol; both the BGS preference panel and the toolbar update the display immediately. Local practice and chat previews save it in the browser. It applies to any player count. @@ -53,6 +53,12 @@ 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. +In games against bots, BGS offers the only human **Undo my move** (protocol 0.10.0). +The top toolbar shows it while BGS reports it available and the board is live: not +in replays, analysis or to spectators, nor while a move is pending. BGS replays the +engine to the position before that saved move and sends it; the viewer then resets +local selections and drops replay positions cached beyond it. + 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`. diff --git a/package.json b/package.json index 1afe0fe..857faf5 100644 --- a/package.json +++ b/package.json @@ -11,11 +11,11 @@ "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 && node test/replay-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 && node test/undo-browser.mjs", "test:locales": "node scripts/check-locales.mjs viewer/localization && node --test scripts/localization.test.mjs" }, "dependencies": { - "@boardgamers/protocol": "0.9.0", + "@boardgamers/protocol": "0.10.0", "@noble/hashes": "2.0.1" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 56a6b8a..39ec1fa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,8 +9,8 @@ importers: .: dependencies: '@boardgamers/protocol': - specifier: 0.9.0 - version: 0.9.0 + specifier: 0.10.0 + version: 0.10.0 '@noble/hashes': specifier: 2.0.1 version: 2.0.1 @@ -27,8 +27,8 @@ importers: packages: - '@boardgamers/protocol@0.9.0': - resolution: {integrity: sha512-xDQMui0xqqRF/ERIJ7Rm79JonMA2+6zn1CrgxpM6Oy3SpFKF6i0Wo6oAyYYqMveqiWJCkC0WvHlePclVfbH/IQ==} + '@boardgamers/protocol@0.10.0': + resolution: {integrity: sha512-U+nOK8xeQANvjzwacHirBW+ItDf9AOmHLtkoyTI/XYFCOpL6lPsEgCbmcxnmkXv2a1/lgtVN3WpSERHUqkQkXw==} '@esbuild/aix-ppc64@0.25.12': resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} @@ -220,7 +220,7 @@ packages: snapshots: - '@boardgamers/protocol@0.9.0': + '@boardgamers/protocol@0.10.0': dependencies: zod: 4.6.5 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 7857ac3..2360188 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -2,4 +2,4 @@ allowBuilds: esbuild: true minimumReleaseAgeExclude: - - "@boardgamers/protocol@0.4.0 || 0.4.2 || 0.5.0 || 0.6.0 || 0.6.1 || 0.6.2 || 0.8.1" + - "@boardgamers/protocol@0.4.0 || 0.4.2 || 0.5.0 || 0.6.0 || 0.6.1 || 0.6.2 || 0.8.1 || 0.10.0" diff --git a/test/replay.test.js b/test/replay.test.js index 97bc813..a229a3c 100644 --- a/test/replay.test.js +++ b/test/replay.test.js @@ -165,6 +165,43 @@ test("live replay preserves its cursor as moves arrive and restores the newest l assert.equal(h.infos.at(-1).current, state.history.length); }); +test("taken-back moves (Undo my move) leave no cached replay positions behind", () => { + const h = harness(); + const before = game(); + let later = before; + for (let i = 0; i < 12; i++) later = E.moveAI(later, E.currentPlayer(later)); + h.replay.update(E.stripSecret(later, 0)); + h.replay.start(); + const stale = E.logSlice(later, h.requests.at(-1)); + h.replay.receive(stale); + h.replay.end(); + // BGS sends the earlier position, with fewer moves. + h.replay.update(E.stripSecret(before, 0)); + h.replay.start(); + assert.deepEqual(h.requests.at(-1), { + start: 0, + end: before.history.length - 1, + }); + h.replay.receive(E.logSlice(before, h.requests.at(-1))); + h.replay.end(); + // Different moves replace the taken-back ones. + const player = E.currentPlayer(before); + let replacement = E.move(before, E.legalMoves(before).at(-1), player); + while (replacement.history.length <= before.history.length) + replacement = E.moveAI(replacement, E.currentPlayer(replacement)); + assert.ok(replacement.history.length < later.history.length); + h.replay.update(E.stripSecret(replacement, 0)); + // A late response describing the taken-back moves is ignored. + h.replay.receive(stale); + h.replay.start(); + h.replay.receive(E.logSlice(replacement, h.requests.at(-1))); + assert.deepEqual(h.renders.at(-1), publicFrame(replacement)); + assert.notDeepEqual( + publicFrame(replacement), + publicFrame(E.replay(later, { to: replacement.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(); diff --git a/test/undo-browser.mjs b/test/undo-browser.mjs new file mode 100644 index 0000000..777e248 --- /dev/null +++ b/test/undo-browser.mjs @@ -0,0 +1,245 @@ +// "Undo my move": BGS lets the only human of a game against bots take back +// their last saved move (protocol 0.10.0 `undo:available` / `undo`). +import { serveAssets } from "./asset-server.mjs"; +const assetBase = await serveAssets("dist"); +import assert from "node:assert/strict"; +import { chromium } from "playwright"; +import * as E from "../engine/index.js"; +import { prepared } from "../viewer/tutorials.js"; + +// The human's (seat 0) turns, each after their move and the bots' replies. +function nextTurn(state) { + let next = E.moveAI(state, 0); + for (let i = 0; E.currentPlayer(next) !== 0; i++) { + assert.ok(i < 500); + next = E.moveAI(next, E.currentPlayer(next)); + } + return next; +} +let first = E.init(4, [], {}, "undo-browser"); +first.players.forEach((p, i) => (p.name = ["You", "Maya", "Leo", "Nina"][i])); +for (let i = 0; first.round < 2 || E.currentPlayer(first) !== 0; i++) { + assert.ok(i < 500); + first = E.moveAI(first, E.currentPlayer(first)); +} +const second = nextTurn(first); +const third = nextTurn(second); +assert.ok(first.history.length < second.history.length); +assert.ok(second.history.length < third.history.length); +// A round apart, the same division task; only the move count tells them apart. +assert.deepEqual(third.tasks[0], second.tasks[0]); +assert.equal(second.tasks[0].kind, "division"); +// Placing an amoeba stays undoable without a new saved move; the amoeba number +// chosen next must not survive taking the placement back. +const dividing = prepared({ + phase: 3, + bp: 20, + task: { kind: "division", p: 0 }, +}); +const divided = E.move( + dividing, + E.legalMoves(dividing).find((m) => m.type === "divide" && m.n === 3), + 0, +); +assert.equal(divided.history.length, dividing.history.length); + +const browser = await chromium.launch({ + executablePath: process.env.CHROMIUM_EXECUTABLE, +}); +try { + for (const width of [320, 1400]) { + const page = await browser.newPage({ viewport: { width, height: 1000 } }); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.setContent( + '
', + ); + await page.addStyleTag({ url: assetBase + "/viewer.css" }); + await page.addScriptTag({ url: assetBase + "/viewer.js" }); + let live; + await page.exposeFunction("loadReplay", (range) => E.logSlice(live, range)); + await page.evaluate(() => { + window.e = primordialSoup.launch("#app"); + window.moves = []; + window.undos = 0; + window.logRequests = []; + window.logResponses = 0; + e.on("move", (m) => moves.push(m)); + e.on("undo", () => undos++); + e.on("fetchLog", async (range) => { + logRequests.push(range); + e.emit("gamelog", { ...range, data: await loadReplay(range) }); + logResponses++; + }); + e.emit("player", { index: 0 }); + }); + const send = (name, value) => + page.evaluate( + async ([name, value]) => { + e.emit(name, value); + await new Promise((resolve) => setTimeout(resolve, 0)); + }, + [name, value], + ); + const show = (state) => { + live = state; + return send("state", E.stripSecret(state, 0)); + }; + const undo = page.locator('[data-ui="undo-move"]'); + const shown = (visible) => + page.waitForFunction( + (visible) => + !document.querySelector('[data-ui="undo-move"]').hidden === visible, + visible, + ); + const replayed = async () => { + await page.waitForFunction( + (count) => logResponses === count, + await page.evaluate(() => logRequests.length), + ); + await send("replay:end"); + }; + const heading = page.locator(".colony-heading h2"); + const picker = page.locator('.amoeba-picker [aria-label="Amoeba number"]'); + const destination = () => + page + .locator(".water-cell.valid") + .first() + .getAttribute("data-destination"); + + await show(second); + assert.ok(await undo.isHidden(), "hidden until BGS offers undo"); + await send("undo:available", true); + assert.ok(await undo.isVisible()); + assert.equal(await undo.getAttribute("title"), "Undo my move"); + assert.equal(await undo.getAttribute("aria-label"), "Undo my move"); + const box = await undo.boundingBox(); + assert.ok(box.x >= 0 && box.x + box.width <= width); + assert.ok( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + `no horizontal overflow at ${width}`, + ); + await page.screenshot({ path: `/tmp/soup-undo-${width}.png` }); + + // Not offered while a move is pending, in replays, analysis, to + // spectators or once the game is over. + await page.locator("[data-move]:visible").first().click(); + assert.equal(await page.evaluate(() => moves.length), 1); + assert.ok(await undo.isHidden(), "hidden while a move is pending"); + await show(second); + await shown(true); + await send("replay:start"); + assert.ok(await undo.isHidden(), "hidden while replaying"); + await replayed(); + assert.ok(await undo.isVisible()); + await send("preferences", { analysis: true }); + await shown(false); + await send("preferences", { analysis: false }); + await shown(true); + await send("player", {}); + assert.ok(await undo.isHidden(), "hidden from spectators"); + await send("player", { index: 0 }); + assert.ok(await undo.isVisible()); + await send("state", second); + assert.equal( + await page.locator(".phase-label").textContent(), + "Game ended", + ); + assert.ok(await undo.isHidden(), "hidden once the game is over"); + await show(second); + assert.ok(await undo.isVisible()); + + // Clicking asks BGS; the earlier position then replaces the local view. + await page.locator('[data-player="2"]').click(); + assert.equal(await heading.textContent(), "Leo"); + await undo.click(); + assert.equal(await page.evaluate(() => undos), 1); + assert.equal(await page.evaluate(() => moves.length), 1); + await show(first); + assert.equal( + await page.locator(".colony-heading .eyebrow").textContent(), + "YOUR COLONY", + ); + assert.equal(await heading.textContent(), "You"); + assert.equal( + await page.locator(".round-number").textContent(), + String(first.round), + ); + assert.equal( + await page.locator(".organisms .amoeba-button").count(), + first.amoebas.length, + ); + assert.deepEqual( + await page.locator(".player-bp").allTextContents(), + first.players.map((p) => String(p.bp)), + ); + assert.equal( + (await page.locator(".last-move").textContent()).trim(), + first.log.at(-1).text, + ); + assert.ok(await undo.isVisible(), "BGS may offer earlier moves too"); + // Replay must not reuse positions cached before the moves were taken back. + await send("replay:start"); + assert.deepEqual(await page.evaluate(() => logRequests.at(-1)), { + start: 0, + end: first.history.length - 1, + }); + await replayed(); + + // Moves taken back elsewhere (another tab): fewer moves, same task. + const specimen = () => + page + .locator('.amoeba-button[aria-pressed="true"]') + .getAttribute("data-amoeba"); + await show(third); + await picker.selectOption("6"); + await page.locator('[data-player="2"]').click(); + assert.equal(await heading.textContent(), "Leo"); + assert.match(await specimen(), /^2-/); + await show(second); + assert.equal(await picker.inputValue(), "4"); + assert.match(await destination(), /^#4 /); + assert.equal(await heading.textContent(), "You"); + assert.match(await specimen(), /^0-/); + + // Same number of saved moves: the undo request alone marks the rewind. + await show(dividing); + await show(divided); + await picker.selectOption("6"); + assert.match(await destination(), /^#6 /); + await undo.click(); + assert.equal(await page.evaluate(() => undos), 2); + await show(dividing); + assert.equal(await picker.inputValue(), "3"); + assert.match(await destination(), /^#3 /); + assert.equal( + await page.locator(".bio-balance strong").textContent(), + String(dividing.players[0].bp), + ); + + await send("preferences", { locale: "fr" }); + await page.waitForFunction( + () => + document.querySelector('[data-ui="undo-move"]')?.title === + "Annuler mon coup", + ); + assert.equal(await undo.getAttribute("aria-label"), "Annuler mon coup"); + await send("preferences", { locale: "en" }); + await page.waitForFunction( + () => + document.querySelector('[data-ui="undo-move"]')?.title === + "Undo my move", + ); + await send("undo:available", false); + assert.ok(await undo.isHidden(), "hidden again once unavailable"); + assert.deepEqual(errors, []); + await page.close(); + console.log( + `Undo my move ${width}: availability, pending moves, replay, analysis, spectators, ended games, earlier positions, selections and translation passed`, + ); + } +} finally { + await browser.close(); +} diff --git a/viewer/chat-preview.js b/viewer/chat-preview.js index 74c23cb..3b10dfb 100644 --- a/viewer/chat-preview.js +++ b/viewer/chat-preview.js @@ -122,9 +122,22 @@ export function mountChatPreview(nav) { emitter.on("player:clicked", ({ index }) => { status.textContent = `Player link: ${state.players[index].name}`; }); + // Like BGS for the only human of a game against bots, "Undo my move" brings + // back the position before each of their moves. + const undoStates = []; emitter.on("move", (move) => { + const before = state; state = E.move(state, move, 0); + undoStates.push(before); emitter.emit("state", E.stripSecret(state)); + emitter.emit("undo:available", true); + }); + emitter.on("undo", () => { + if (!undoStates.length) return; + state = undoStates.pop(); + emitter.emit("state", E.stripSecret(state)); + emitter.emit("undo:available", undoStates.length > 0); + status.textContent = "Move taken back locally"; }); const controls = [ [ diff --git a/viewer/index.js b/viewer/index.js index 0def57a..0eb0672 100644 --- a/viewer/index.js +++ b/viewer/index.js @@ -64,13 +64,17 @@ registerViewer( "primordialSoup", (ctx) => { const localization = mountLocalization(ctx.target); - let pending, timeout; + let pending, timeout, undoRequested, liveLength; const chat = new ChatController(); const ui = mountGame(ctx.target, { chat, onOpenPlayer: ctx.openPlayer, onColorBlindChange: (enabled) => ctx.updatePreference(COLOR_BLIND_PREFERENCE.name, enabled), + onUndo() { + undoRequested = true; + ctx.undo(); + }, onMove: (m) => new Promise((resolve, reject) => { pending = { resolve, reject }; @@ -122,8 +126,16 @@ registerViewer( onPlayer(player) { ui.setPlayer(player.index); }, + onUndoAvailable(available) { + ui.setUndoAvailable(available); + }, async onState(state) { await localization.ready; + // After "Undo my move", BGS sends the earlier position (fewer moves). + const length = state?.historyLength; + if (undoRequested || length < liveLength) ui.resetSelection(); + undoRequested = false; + liveLength = length; replay.update(state); if (pending) { clearTimeout(timeout); diff --git a/viewer/localization/da.json b/viewer/localization/da.json index 4705f26..1848ece 100644 --- a/viewer/localization/da.json +++ b/viewer/localization/da.json @@ -1201,5 +1201,6 @@ "{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.", "Replay": "Gengivelse", - "Loading replay…": "Indlæser gengivelse…" + "Loading replay…": "Indlæser gengivelse…", + "Undo my move": "Fortryd mit træk" } diff --git a/viewer/localization/de.json b/viewer/localization/de.json index 573d3b7..770c62c 100644 --- a/viewer/localization/de.json +++ b/viewer/localization/de.json @@ -1201,5 +1201,6 @@ "{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.", "Replay": "Wiederholung", - "Loading replay…": "Wiederholung wird geladen…" + "Loading replay…": "Wiederholung wird geladen…", + "Undo my move": "Zug zurücknehmen" } diff --git a/viewer/localization/el.json b/viewer/localization/el.json index 782f81b..594f56c 100644 --- a/viewer/localization/el.json +++ b/viewer/localization/el.json @@ -1201,5 +1201,6 @@ "{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} απορρίπτει το {p1}· υπόλοιπο ελλείμματος: {p2} ΒΠ.", "{p0} didn't buy any genes.": "{p0} δεν αγόρασε κανένα γονίδιο.", "Replay": "Επανάληψη", - "Loading replay…": "Φόρτωση επανάληψης…" + "Loading replay…": "Φόρτωση επανάληψης…", + "Undo my move": "Αναίρεση κίνησης" } diff --git a/viewer/localization/en.json b/viewer/localization/en.json index fbd5a34..924331a 100644 --- a/viewer/localization/en.json +++ b/viewer/localization/en.json @@ -1201,5 +1201,6 @@ "{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.", "Replay": "Replay", - "Loading replay…": "Loading replay…" + "Loading replay…": "Loading replay…", + "Undo my move": "Undo my move" } diff --git a/viewer/localization/fa.json b/viewer/localization/fa.json index 40d90e0..18ee454 100644 --- a/viewer/localization/fa.json +++ b/viewer/localization/fa.json @@ -1201,5 +1201,6 @@ "{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} ژن {p1} را دور می‌اندازد؛ کسری باقی‌مانده: {p2} امتیاز زیستی.", "{p0} didn't buy any genes.": "{p0} هیچ ژنی نخرید.", "Replay": "بازپخش", - "Loading replay…": "در حال بارگذاری بازپخش…" + "Loading replay…": "در حال بارگذاری بازپخش…", + "Undo my move": "بازگرداندن حرکت" } diff --git a/viewer/localization/fr.json b/viewer/localization/fr.json index d9f6dfc..92f7842 100644 --- a/viewer/localization/fr.json +++ b/viewer/localization/fr.json @@ -1201,5 +1201,6 @@ "{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.", "Replay": "Rediffusion", - "Loading replay…": "Chargement de la rediffusion…" + "Loading replay…": "Chargement de la rediffusion…", + "Undo my move": "Annuler mon coup" } diff --git a/viewer/localization/hi.json b/viewer/localization/hi.json index 77c5882..3637942 100644 --- a/viewer/localization/hi.json +++ b/viewer/localization/hi.json @@ -1201,5 +1201,6 @@ "{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} {p1} त्यागता है; शेष कमी: {p2} BP।", "{p0} didn't buy any genes.": "{p0} ने कोई जीन नहीं खरीदा।", "Replay": "रीप्ले", - "Loading replay…": "रीप्ले लोड हो रहा है…" + "Loading replay…": "रीप्ले लोड हो रहा है…", + "Undo my move": "अपनी चाल वापस लें" } diff --git a/viewer/localization/it.json b/viewer/localization/it.json index 1e94230..8d9fb9f 100644 --- a/viewer/localization/it.json +++ b/viewer/localization/it.json @@ -1201,5 +1201,6 @@ "{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.", "Replay": "Replay", - "Loading replay…": "Caricamento del replay…" + "Loading replay…": "Caricamento del replay…", + "Undo my move": "Annulla la mossa" } diff --git a/viewer/localization/ko.json b/viewer/localization/ko.json index 6efe617..5ab2f54 100644 --- a/viewer/localization/ko.json +++ b/viewer/localization/ko.json @@ -1201,5 +1201,6 @@ "{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} 이(가) {p1} 을(를) 버립니다. 남은 부족분: {p2} BP.", "{p0} didn't buy any genes.": "{p0} 은(는) 유전자를 구매하지 않았습니다.", "Replay": "다시 보기", - "Loading replay…": "다시 보기 불러오는 중…" + "Loading replay…": "다시 보기 불러오는 중…", + "Undo my move": "내 수 되돌리기" } diff --git a/viewer/localization/nl.json b/viewer/localization/nl.json index e2c9797..95e69c0 100644 --- a/viewer/localization/nl.json +++ b/viewer/localization/nl.json @@ -1201,5 +1201,6 @@ "{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.", "Replay": "Herhaling", - "Loading replay…": "Herhaling laden…" + "Loading replay…": "Herhaling laden…", + "Undo my move": "Zet ongedaan maken" } diff --git a/viewer/localization/pl.json b/viewer/localization/pl.json index dabd63d..d785f6d 100644 --- a/viewer/localization/pl.json +++ b/viewer/localization/pl.json @@ -1201,5 +1201,6 @@ "{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.", "Replay": "Powtórka", - "Loading replay…": "Wczytywanie powtórki…" + "Loading replay…": "Wczytywanie powtórki…", + "Undo my move": "Cofnij ruch" } diff --git a/viewer/localization/pt-BR.json b/viewer/localization/pt-BR.json index 93ea34a..d0e1e19 100644 --- a/viewer/localization/pt-BR.json +++ b/viewer/localization/pt-BR.json @@ -1201,5 +1201,6 @@ "{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.", "Replay": "Reprise", - "Loading replay…": "Carregando reprise…" + "Loading replay…": "Carregando reprise…", + "Undo my move": "Desfazer jogada" } diff --git a/viewer/localization/ro.json b/viewer/localization/ro.json index 3432005..85cf591 100644 --- a/viewer/localization/ro.json +++ b/viewer/localization/ro.json @@ -1201,5 +1201,6 @@ "{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.", "Replay": "Reluare", - "Loading replay…": "Se încarcă reluarea…" + "Loading replay…": "Se încarcă reluarea…", + "Undo my move": "Anulează mutarea" } diff --git a/viewer/localization/ru.json b/viewer/localization/ru.json index 58f4cd0..79b9f0f 100644 --- a/viewer/localization/ru.json +++ b/viewer/localization/ru.json @@ -1201,5 +1201,6 @@ "{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} сбрасывает {p1}; оставшийся дефицит: {p2} БО.", "{p0} didn't buy any genes.": "{p0} не покупает ни одного гена.", "Replay": "Повтор", - "Loading replay…": "Загрузка повтора…" + "Loading replay…": "Загрузка повтора…", + "Undo my move": "Отменить ход" } diff --git a/viewer/localization/vi.json b/viewer/localization/vi.json index f748f6b..c219045 100644 --- a/viewer/localization/vi.json +++ b/viewer/localization/vi.json @@ -1201,5 +1201,6 @@ "{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.", "Replay": "Phát lại", - "Loading replay…": "Đang tải phát lại…" + "Loading replay…": "Đang tải phát lại…", + "Undo my move": "Hoàn tác nước đi" } diff --git a/viewer/localization/zh-TW.json b/viewer/localization/zh-TW.json index e006806..fd1065c 100644 --- a/viewer/localization/zh-TW.json +++ b/viewer/localization/zh-TW.json @@ -1201,5 +1201,6 @@ "{p0} discards {p1}; remaining deficit: {p2} BP.": "{p0} 棄掉 {p1};剩餘差額:{p2} BP。", "{p0} didn't buy any genes.": "{p0} 沒有購買任何基因。", "Replay": "重播", - "Loading replay…": "正在載入重播…" + "Loading replay…": "正在載入重播…", + "Undo my move": "撤回我的行動" } diff --git a/viewer/replay.js b/viewer/replay.js index 6bde594..75a6b9f 100644 --- a/viewer/replay.js +++ b/viewer/replay.js @@ -10,7 +10,9 @@ export function createReplay({ }) { let latest, packet, requestedEnd, cursor; let active = false; - const length = () => latest?.historyLength ?? latest?.history?.length ?? 0; + const lengthOf = (state) => + state?.historyLength ?? state?.history?.length ?? 0; + const length = () => lengthOf(latest); const cachedEnd = () => (packet ? packet.start + packet.steps.length : -1); function show() { @@ -47,6 +49,12 @@ export function createReplay({ return active; }, update(state) { + // "Undo my move" rewinds the live game: positions after the earlier + // state were taken back, and later moves will replace them. + if (latest && lengthOf(state) < length()) { + packet = undefined; + requestedEnd = undefined; + } latest = state; if (!active) { render(state); @@ -59,7 +67,12 @@ export function createReplay({ receive(data) { if (!data?.replay) return false; const incoming = data.replay; - if (incoming.start === 0 && incoming.steps.length >= cachedEnd()) + // A response requested before a rewind may reach taken-back positions. + if ( + incoming.start === 0 && + incoming.steps.length >= cachedEnd() && + incoming.steps.length <= length() + ) packet = incoming; if (cachedEnd() >= requestedEnd) requestedEnd = undefined; // A delayed response may fill the cache after leaving replay, but must diff --git a/viewer/style.css b/viewer/style.css index b8534af..e91589b 100644 --- a/viewer/style.css +++ b/viewer/style.css @@ -24,6 +24,9 @@ background: #e0eacb; box-shadow: inset 0 0 0 1px #8eaa6e; } +.utilities [hidden] { + display: none; +} .amoeba-symbol, .food > .colony-symbol, .scoring-marker > .colony-symbol { @@ -1795,6 +1798,22 @@ } } +/* "Undo my move" adds a fifth header control on the narrowest phones. */ +@media (max-width: 340px) { + .soup .topbar:has([data-ui="undo-move"]:not([hidden])) { + gap: 4px; + } + .soup .topbar:has([data-ui="undo-move"]:not([hidden])) .brand { + gap: 6px; + } + .soup .topbar:has([data-ui="undo-move"]:not([hidden])) .brand > span { + width: 28px; + } + .soup .topbar:has([data-ui="undo-move"]:not([hidden])) .utilities { + gap: 3px; + } +} + @media (min-width: 1001px) and (max-height: 750px) { .board-reference { top: 1%; diff --git a/viewer/ui.js b/viewer/ui.js index fb32658..139a23a 100644 --- a/viewer/ui.js +++ b/viewer/ui.js @@ -224,6 +224,7 @@ export function mountGame( target, { onMove, + onUndo, onFullscreen, onOpenPlayer, onColorBlindChange, @@ -243,7 +244,7 @@ export function mountGame( let colonySymbols = onColorBlindChange ? false : readLocalColorBlindMode(); root.classList.toggle("colony-symbols", colonySymbols); target.append(root); - root.innerHTML = `
${amoeba("green", 0)}

primordial soup.

+ root.innerHTML = `
${amoeba("green", 0)}

primordial soup.

${chat ? `` : ""}
CURRENT
➜
ROUND
    @@ -267,6 +268,8 @@ export function mountGame( busy = false, locked = false, replaying = false, + analysis = false, + undoAvailable = false, modalKind, modalPlayer, oldTask, @@ -295,6 +298,20 @@ export function mountGame( 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; @@ -313,6 +330,7 @@ export function mountGame( return ``; } function render() { + showUndoMove(); if (!state) return; activity.update(state); const t = state.tasks[0], @@ -719,6 +737,13 @@ export function mountGame( 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); @@ -766,10 +791,25 @@ export function mountGame( render(); }, setChatNotifications: activity.setChatNotifications, - setAnalysisMode(analysis) { + setAnalysisMode(enabled) { + analysis = enabled; const button = $('[data-ui="chat"]'); - if (button) button.hidden = analysis; - activity.setAnalysisMode(analysis); + 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;