From 3614e97d8d95357820e9c10f8e2ac102f3ac92b8 Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Thu, 8 Oct 2026 10:49:28 +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 header tools show an undo control while BGS reports it available and the board is interactive (hidden during replays); it asks BGS to undo, which then sends the earlier state. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +-- pnpm-lock.yaml | 10 +++--- pnpm-workspace.yaml | 2 +- test/undo-browser.mjs | 57 ++++++++++++++++++++++++++++++++++ viewer/index.js | 4 +++ viewer/labels.js | 1 + 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/preview.js | 5 +++ viewer/ui.js | 13 +++++++- 24 files changed, 119 insertions(+), 25 deletions(-) create mode 100644 test/undo-browser.mjs diff --git a/package.json b/package.json index 4158752..3beca5a 100644 --- a/package.json +++ b/package.json @@ -11,13 +11,13 @@ "build": "node scripts/build.mjs", "test": "node --test test/*.test.js", "dev": "node scripts/dev.mjs", - "test:browser": "node test/browser.mjs && node test/journal-browser.mjs && node test/map-zoom-browser.mjs && node test/redraw-browser.mjs && node test/mobile-layout-browser.mjs && node test/prose-browser.mjs", + "test:browser": "node test/browser.mjs && node test/undo-browser.mjs && node test/journal-browser.mjs && node test/map-zoom-browser.mjs && node test/redraw-browser.mjs && node test/mobile-layout-browser.mjs && node test/prose-browser.mjs", "check": "pnpm test:locales && pnpm build && pnpm test && pnpm test:browser && pnpm test:tutorial:browser", "test:locales": "node scripts/check-locales.mjs viewer/localization && node --test scripts/localization.test.mjs", "test:tutorial:browser": "node test/tutorial-browser.mjs && node test/tutorial-walkthrough-browser.mjs && node test/tutorial-errors-browser.mjs" }, "dependencies": { - "@boardgamers/protocol": "0.9.0", + "@boardgamers/protocol": "0.10.0", "@noble/hashes": "2.0.1", "morphdom": "2.7.8" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 66f93c1..57060b7 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 @@ -30,8 +30,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==} @@ -226,7 +226,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 1a54af5..685376e 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,4 +1,4 @@ allowBuilds: esbuild: true minimumReleaseAgeExclude: - - "@boardgamers/protocol@0.6.1 || 0.6.2 || 0.8.1" + - "@boardgamers/protocol@0.6.1 || 0.6.2 || 0.8.1 || 0.10.0" diff --git a/test/undo-browser.mjs b/test/undo-browser.mjs new file mode 100644 index 0000000..5b31338 --- /dev/null +++ b/test/undo-browser.mjs @@ -0,0 +1,57 @@ +// The "Undo my move" header control BGS enables in games against bots (protocol `undo`). +import assert from "node:assert/strict"; +import { chromium } from "playwright"; +import { readFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { resolve, extname } from "node:path"; + +const dist = resolve("dist"); +const server = createServer(async (req, res) => { + try { + const url = new URL(req.url, "http://localhost"); + const path = resolve( + dist, + "." + (url.pathname === "/" ? "/index.html" : url.pathname), + ); + if (!path.startsWith(dist + "/")) throw Error("Invalid path"); + res.setHeader( + "Content-Type", + { ".js": "text/javascript", ".css": "text/css", ".html": "text/html" }[ + extname(path) + ] ?? "application/octet-stream", + ); + res.end(await readFile(path)); + } catch { + res.writeHead(404); + res.end(); + } +}); +await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); +server.unref(); +const browser = await chromium.launch({ + headless: true, + ...(process.env.CHROME_PATH + ? { executablePath: process.env.CHROME_PATH } + : {}), +}); +const errors = []; +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +page.on("pageerror", (e) => errors.push(e.message)); +await page.goto(`http://127.0.0.1:${server.address().port}/?new&hotseat`); +await page.waitForSelector("[data-character-choice]"); + +const undo = page.locator("[data-undo-move]"); +assert.equal(await undo.count(), 0, "hidden until BGS offers undo"); +await page.evaluate(() => window.vanuatuDemo.ui.setUndoAvailable(true)); +assert.equal(await undo.getAttribute("title"), "Undo my move"); +await undo.click(); +assert.equal(await page.evaluate(() => window.vanuatuDemo.undoRequests), 1); + +await page.evaluate(() => window.vanuatuDemo.ui.setEnabled(false)); +assert.equal(await undo.count(), 0, "hidden while replaying"); +await page.evaluate(() => window.vanuatuDemo.ui.setEnabled(true)); +await page.evaluate(() => window.vanuatuDemo.ui.setUndoAvailable(false)); +assert.equal(await undo.count(), 0); +assert.deepEqual(errors, []); +await browser.close(); +console.log("undo control ok"); diff --git a/viewer/index.js b/viewer/index.js index a2bfb59..354b839 100644 --- a/viewer/index.js +++ b/viewer/index.js @@ -23,6 +23,7 @@ registerViewer( onOpenPlayer: ctx.openPlayer, onOpenBoardgame: ctx.openBoardgame, onPreference: ctx.updatePreference, + onUndo: ctx.undo, onMove: (m) => new Promise((resolve, reject) => { pending = { resolve, reject }; @@ -81,6 +82,9 @@ registerViewer( onAvatars(avatars) { ui.setAvatars(avatars); }, + onUndoAvailable(available) { + ui.setUndoAvailable(available); + }, onError(e) { clearTimeout(timeout); pending?.reject(e); diff --git a/viewer/labels.js b/viewer/labels.js index 3960b77..955108e 100644 --- a/viewer/labels.js +++ b/viewer/labels.js @@ -20,6 +20,7 @@ const entries = { choose: ["Choose", "Choisir"], cancel: ["Cancel", "Annuler"], undo: ["Undo", "Annuler"], + undoMove: ["Undo my move", "Annuler mon coup"], waiting: ["Waiting for", "Au tour de"], you: ["You", "Vous"], spectator: ["Spectator", "Spectateur"], diff --git a/viewer/localization/da.json b/viewer/localization/da.json index b434893..e26da83 100644 --- a/viewer/localization/da.json +++ b/viewer/localization/da.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} har flere markører: {p1} mod {p2}.", "No majority on this action.": "Intet flertal på denne handling.", "Wait for your turn.": "Vent på din tur.", - "Choose an action to take back its markers without acting.": "Vælg en handling, hvis markører du tager tilbage uden at handle." + "Choose an action to take back its markers without acting.": "Vælg en handling, hvis markører du tager tilbage uden at handle.", + "Undo my move": "Fortryd mit træk" } diff --git a/viewer/localization/de.json b/viewer/localization/de.json index 4eaf8a2..5292519 100644 --- a/viewer/localization/de.json +++ b/viewer/localization/de.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} hat mehr Marker: {p1} gegen {p2}.", "No majority on this action.": "Keine Mehrheit bei dieser Aktion.", "Wait for your turn.": "Warte, bis du am Zug bist.", - "Choose an action to take back its markers without acting.": "Wähle eine Aktion, deren Marker du ohne Aktion zurücknimmst." + "Choose an action to take back its markers without acting.": "Wähle eine Aktion, deren Marker du ohne Aktion zurücknimmst.", + "Undo my move": "Zug zurücknehmen" } diff --git a/viewer/localization/el.json b/viewer/localization/el.json index 295595e..9b54461 100644 --- a/viewer/localization/el.json +++ b/viewer/localization/el.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "Ο/Η {p0} έχει περισσότερους δείκτες: {p1} έναντι {p2}.", "No majority on this action.": "Καμία πλειοψηφία σε αυτή τη δράση.", "Wait for your turn.": "Περιμένετε τη σειρά σας.", - "Choose an action to take back its markers without acting.": "Επίλεξε μια ενέργεια για να πάρεις πίσω τους δείκτες της χωρίς να την εκτελέσεις." + "Choose an action to take back its markers without acting.": "Επίλεξε μια ενέργεια για να πάρεις πίσω τους δείκτες της χωρίς να την εκτελέσεις.", + "Undo my move": "Αναίρεση κίνησης" } diff --git a/viewer/localization/en.json b/viewer/localization/en.json index 72c19ab..203ea8a 100644 --- a/viewer/localization/en.json +++ b/viewer/localization/en.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} has more markers: {p1} against {p2}.", "No majority on this action.": "No majority on this action.", "Wait for your turn.": "Wait for your turn.", - "Choose an action to take back its markers without acting.": "Choose an action to take back its markers without acting." + "Choose an action to take back its markers without acting.": "Choose an action to take back its markers without acting.", + "Undo my move": "Undo my move" } diff --git a/viewer/localization/fa.json b/viewer/localization/fa.json index 5a0a5a7..09263ae 100644 --- a/viewer/localization/fa.json +++ b/viewer/localization/fa.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} مهرهٔ بیشتری دارد: {p1} در برابر {p2}.", "No majority on this action.": "در این اقدام اکثریت ندارید.", "Wait for your turn.": "منتظر نوبت خود باشید.", - "Choose an action to take back its markers without acting.": "اقدامی را انتخاب کنید تا مهره‌هایش را بدون انجام آن پس بگیرید." + "Choose an action to take back its markers without acting.": "اقدامی را انتخاب کنید تا مهره‌هایش را بدون انجام آن پس بگیرید.", + "Undo my move": "بازگرداندن حرکت" } diff --git a/viewer/localization/fr.json b/viewer/localization/fr.json index f5e8c9c..2c19a46 100644 --- a/viewer/localization/fr.json +++ b/viewer/localization/fr.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} a plus de pions : {p1} contre {p2}.", "No majority on this action.": "Pas de majorité sur cette action.", "Wait for your turn.": "Attendez votre tour.", - "Choose an action to take back its markers without acting.": "Choisissez une action dont vous reprenez les marqueurs sans agir." + "Choose an action to take back its markers without acting.": "Choisissez une action dont vous reprenez les marqueurs sans agir.", + "Undo my move": "Annuler mon coup" } diff --git a/viewer/localization/hi.json b/viewer/localization/hi.json index 06f89ca..b6bc370 100644 --- a/viewer/localization/hi.json +++ b/viewer/localization/hi.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} के पास अधिक मार्कर हैं: {p1} बनाम {p2}।", "No majority on this action.": "इस क्रिया पर बहुमत नहीं है।", "Wait for your turn.": "अपनी बारी का इंतज़ार करें।", - "Choose an action to take back its markers without acting.": "एक कार्रवाई चुनें जिसके मार्कर आप बिना कार्रवाई किए वापस लेंगे।" + "Choose an action to take back its markers without acting.": "एक कार्रवाई चुनें जिसके मार्कर आप बिना कार्रवाई किए वापस लेंगे।", + "Undo my move": "अपनी चाल वापस लें" } diff --git a/viewer/localization/it.json b/viewer/localization/it.json index 7f86252..9aac5f0 100644 --- a/viewer/localization/it.json +++ b/viewer/localization/it.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} ha più segnalini: {p1} contro {p2}.", "No majority on this action.": "Nessuna maggioranza su questa azione.", "Wait for your turn.": "Attendi il tuo turno.", - "Choose an action to take back its markers without acting.": "Scegli un’azione di cui riprendere i segnalini senza agire." + "Choose an action to take back its markers without acting.": "Scegli un’azione di cui riprendere i segnalini senza agire.", + "Undo my move": "Annulla la mossa" } diff --git a/viewer/localization/ko.json b/viewer/localization/ko.json index d7645c3..042fe81 100644 --- a/viewer/localization/ko.json +++ b/viewer/localization/ko.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0}의 마커가 더 많습니다: {p1} 대 {p2}.", "No majority on this action.": "이 행동에서 과반을 차지하지 못했습니다.", "Wait for your turn.": "차례를 기다리세요.", - "Choose an action to take back its markers without acting.": "행동하지 않고 마커를 회수할 행동을 선택하세요." + "Choose an action to take back its markers without acting.": "행동하지 않고 마커를 회수할 행동을 선택하세요.", + "Undo my move": "내 수 되돌리기" } diff --git a/viewer/localization/nl.json b/viewer/localization/nl.json index 78122c3..00baf31 100644 --- a/viewer/localization/nl.json +++ b/viewer/localization/nl.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} heeft meer markers: {p1} tegen {p2}.", "No majority on this action.": "Geen meerderheid op deze actie.", "Wait for your turn.": "Wacht op je beurt.", - "Choose an action to take back its markers without acting.": "Kies een actie waarvan je de markers zonder actie terugneemt." + "Choose an action to take back its markers without acting.": "Kies een actie waarvan je de markers zonder actie terugneemt.", + "Undo my move": "Zet ongedaan maken" } diff --git a/viewer/localization/pl.json b/viewer/localization/pl.json index 0d8b377..7b10434 100644 --- a/viewer/localization/pl.json +++ b/viewer/localization/pl.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} ma więcej znaczników: {p1} wobec {p2}.", "No majority on this action.": "Brak większości w tej akcji.", "Wait for your turn.": "Poczekaj na swoją turę.", - "Choose an action to take back its markers without acting.": "Wybierz akcję, z której zabierasz znaczniki bez jej wykonywania." + "Choose an action to take back its markers without acting.": "Wybierz akcję, z której zabierasz znaczniki bez jej wykonywania.", + "Undo my move": "Cofnij ruch" } diff --git a/viewer/localization/pt-BR.json b/viewer/localization/pt-BR.json index 4851952..6f0a780 100644 --- a/viewer/localization/pt-BR.json +++ b/viewer/localization/pt-BR.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} tem mais marcadores: {p1} contra {p2}.", "No majority on this action.": "Sem maioria nesta ação.", "Wait for your turn.": "Aguarde sua vez.", - "Choose an action to take back its markers without acting.": "Escolha uma ação para recolher os marcadores dela sem agir." + "Choose an action to take back its markers without acting.": "Escolha uma ação para recolher os marcadores dela sem agir.", + "Undo my move": "Desfazer jogada" } diff --git a/viewer/localization/ro.json b/viewer/localization/ro.json index 9e3a022..bbcba3f 100644 --- a/viewer/localization/ro.json +++ b/viewer/localization/ro.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} are mai mulți marcatori: {p1} față de {p2}.", "No majority on this action.": "Nicio majoritate la această acțiune.", "Wait for your turn.": "Așteaptă-ți rândul.", - "Choose an action to take back its markers without acting.": "Alege o acțiune ale cărei marcaje le retragi fără a acționa." + "Choose an action to take back its markers without acting.": "Alege o acțiune ale cărei marcaje le retragi fără a acționa.", + "Undo my move": "Anulează mutarea" } diff --git a/viewer/localization/ru.json b/viewer/localization/ru.json index d5a0ae3..d523a4f 100644 --- a/viewer/localization/ru.json +++ b/viewer/localization/ru.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "У {p0} больше маркеров: {p1} против {p2}.", "No majority on this action.": "Нет большинства на этом действии.", "Wait for your turn.": "Дождитесь своего хода.", - "Choose an action to take back its markers without acting.": "Выберите действие, маркеры которого вы заберёте без выполнения действия." + "Choose an action to take back its markers without acting.": "Выберите действие, маркеры которого вы заберёте без выполнения действия.", + "Undo my move": "Отменить ход" } diff --git a/viewer/localization/vi.json b/viewer/localization/vi.json index c97b8f5..692bba3 100644 --- a/viewer/localization/vi.json +++ b/viewer/localization/vi.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} có nhiều điểm đánh dấu hơn: {p1} so với {p2}.", "No majority on this action.": "Không chiếm đa số ở hành động này.", "Wait for your turn.": "Hãy chờ đến lượt bạn.", - "Choose an action to take back its markers without acting.": "Chọn một hành động để thu hồi dấu của nó mà không thực hiện hành động." + "Choose an action to take back its markers without acting.": "Chọn một hành động để thu hồi dấu của nó mà không thực hiện hành động.", + "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 96207af..7a90bca 100644 --- a/viewer/localization/zh-TW.json +++ b/viewer/localization/zh-TW.json @@ -945,5 +945,6 @@ "{p0} has more markers: {p1} against {p2}.": "{p0} 的指示物較多:{p1} 對 {p2}。", "No majority on this action.": "此行動未取得多數。", "Wait for your turn.": "請等待輪到你。", - "Choose an action to take back its markers without acting.": "選擇一個行動,收回其標記但不執行行動。" + "Choose an action to take back its markers without acting.": "選擇一個行動,收回其標記但不執行行動。", + "Undo my move": "撤回我的行動" } diff --git a/viewer/preview.js b/viewer/preview.js index 840150f..fdf7b97 100644 --- a/viewer/preview.js +++ b/viewer/preview.js @@ -55,7 +55,9 @@ if (params.has("lesson")) { control.querySelector("[data-count]").value = state.players.length; control.querySelector("[data-water]").checked = state.options.risingWaters; control.querySelector("[data-hotseat]").checked = hotseat; + let undoRequests = 0; const ui = mountGame(document.querySelector("#game"), { + onUndo: () => (undoRequests += 1), onMove: (m) => { state = engine.move(state, m, hotseat ? state.actor : 0); save(); @@ -149,6 +151,9 @@ if (params.has("lesson")) { }, engine, ui, + get undoRequests() { + return undoRequests; + }, }; show(); scheduleBots(); diff --git a/viewer/ui.js b/viewer/ui.js index a8504dc..71a8a1b 100644 --- a/viewer/ui.js +++ b/viewer/ui.js @@ -102,6 +102,7 @@ export function mountGame(target, options = {}) { hostedLocale = false, colorBlind = false, sound = false, + undoAvailable = false, revision, stateKey, focusReturn; @@ -502,7 +503,7 @@ export function mountGame(target, options = {}) { .filter((m) => m.type === "place" && m.tile === tile) .map((m) => m.cell) : actualTargets(); - const html = `
${btn("🏝️ Vanuatu", "data-boardgame", "wordmark")}
Designed by Alain EpronPublished by Quined Games
${Array.from({ length: 8 }, (_, i) => `${i + 1}`).join("")}
+ const html = `
${btn("🏝️ Vanuatu", "data-boardgame", "wordmark")}
Designed by Alain EpronPublished by Quined Games
${Array.from({ length: 8 }, (_, i) => `${i + 1}`).join("")}
${dock()}
${icon("fish", marketHelp)} = ${token("coin", s.market, marketHelp)}${token("tourist", s.tourists, `${"Tourists available this round"}: ${s.tourists}`)}${s.waterCountdown !== null ? `${token("water", s.waterCountdown, `${t("waterLeft")}: ${s.waterCountdown}`)}` : ""}
${tradeShips()}
${renderBoard(targets)}
${titled("Zoom out", icon("zoomOut"), "data-zoom-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-zoom-in", "icon-button")}
${s.upcoming.length && s.phase !== "expand" ? titled(t("next"), `${s.upcoming.map((id) => tilePreviewSvg(id, { t, colorBlind, language: lang, prefix: "upcoming-" + id })).join("")}${icon("zoom", t("next"))}`, "data-upcoming", "upcoming") : ""}${trayHtml}
${s.players.map(playerCard).join("")}
${token("coin", 10)} → ${token("point", 5)}${btn(t("help"), "data-help", "text-button")}
`; // Patch in place so cached SVG tile images and focused controls survive // preference changes and incoming state updates. @@ -661,6 +662,10 @@ export function mountGame(target, options = {}) { } if (!button || button.disabled) return; const d = button.dataset; + if ("undoMove" in d) { + options.onUndo?.(); + return; + } if ("upcoming" in d) { showDialog( `

${t("next")}

${s.upcoming @@ -946,6 +951,12 @@ export function mountGame(target, options = {}) { enabled = v; render(); }, + // BGS takes back the player's last move in games against bots (protocol `undo`). + setUndoAvailable(v) { + if (undoAvailable === v) return; + undoAvailable = v; + render(); + }, setPreferences(p) { const previous = `${analysis}:${colorBlind}:${lang}:${playerColors.join()}:${JSON.stringify(appearance)}`; appearance = p.bgs ?? {};