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 <noreply@anthropic.com>
This commit is contained in:
coyotte508 2026-10-08 10:49:28 +02:00
commit 3614e97d8d
24 changed files with 119 additions and 25 deletions

View file

@ -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"
},

10
pnpm-lock.yaml generated
View file

@ -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

View file

@ -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"

57
test/undo-browser.mjs Normal file
View file

@ -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");

View file

@ -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);

View file

@ -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"],

View file

@ -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"
}

View file

@ -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"
}

View file

@ -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": "Αναίρεση κίνησης"
}

View file

@ -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"
}

View file

@ -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": "بازگرداندن حرکت"
}

View file

@ -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"
}

View file

@ -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": "अपनी चाल वापस लें"
}

View file

@ -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"
}

View file

@ -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": "내 수 되돌리기"
}

View file

@ -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"
}

View file

@ -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"
}

View file

@ -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"
}

View file

@ -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"
}

View file

@ -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": "Отменить ход"
}

View file

@ -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"
}

View file

@ -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": "撤回我的行動"
}

View file

@ -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();

View file

@ -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 = `<header class="game-header"><div class="brand">${btn("🏝️ Vanuatu", "data-boardgame", "wordmark")}<div class="game-credits"><span>Designed by Alain Epron</span><span>Published by Quined Games</span></div></div><div class="round-track" aria-label="${t("round")} ${s.round}/8">${Array.from({ length: 8 }, (_, i) => `<span title="${t("round")} ${i + 1}/8" class="${i + 1 === s.round ? "current" : i + 1 < s.round ? "past" : ""}">${i + 1}</span>`).join("")}</div><nav class="header-tools">${analysis || !options.chat ? "" : titled(t("chat"), `${icon("chat")}<span class="unread-badge" hidden></span>`, 'data-activity="chat"', "icon-button")}${titled(t("journal"), icon("journal"), 'data-activity="journal"', "icon-button")}${titled(t("colorBlind"), icon("colorBlind"), `data-color-blind aria-pressed="${colorBlind}"`, "icon-button")}${titled(t("help"), icon("help"), "data-help", "icon-button")}${titled(t("full"), icon("fullscreen"), "data-fullscreen", "icon-button")}</nav></header>
const html = `<header class="game-header"><div class="brand">${btn("🏝️ Vanuatu", "data-boardgame", "wordmark")}<div class="game-credits"><span>Designed by Alain Epron</span><span>Published by Quined Games</span></div></div><div class="round-track" aria-label="${t("round")} ${s.round}/8">${Array.from({ length: 8 }, (_, i) => `<span title="${t("round")} ${i + 1}/8" class="${i + 1 === s.round ? "current" : i + 1 < s.round ? "past" : ""}">${i + 1}</span>`).join("")}</div><nav class="header-tools">${undoAvailable && enabled && !analysis ? titled(t("undoMove"), icon("undo"), "data-undo-move", "icon-button") : ""}${analysis || !options.chat ? "" : titled(t("chat"), `${icon("chat")}<span class="unread-badge" hidden></span>`, 'data-activity="chat"', "icon-button")}${titled(t("journal"), icon("journal"), 'data-activity="journal"', "icon-button")}${titled(t("colorBlind"), icon("colorBlind"), `data-color-blind aria-pressed="${colorBlind}"`, "icon-button")}${titled(t("help"), icon("help"), "data-help", "icon-button")}${titled(t("full"), icon("fullscreen"), "data-fullscreen", "icon-button")}</nav></header>
<div class="table">${dock()}<section class="sea-board"><div class="sea-dashboard"><div class="market-info"><span class="fish-price" title="${esc(marketHelp)}">${icon("fish", marketHelp)} = ${token("coin", s.market, marketHelp)}</span><span title="${t("tourist")}">${token("tourist", s.tourists, `${"Tourists available this round"}: ${s.tourists}`)}</span>${s.waterCountdown !== null ? `<span title="${t("waterLeft")}">${token("water", s.waterCountdown, `${t("waterLeft")}: ${s.waterCountdown}`)}</span>` : ""}</div>${tradeShips()}</div><div class="map-scroll"><div class="map-canvas">${renderBoard(targets)}</div></div><div class="map-tools">${titled("Zoom out", icon("zoomOut"), "data-zoom-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-zoom-in", "icon-button")}</div>${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}</section></div><section class="players">${s.players.map(playerCard).join("")}</section><footer class="play-footer"><span title="${"Automatic conversion"}">${token("coin", 10)} → ${token("point", 5)}</span>${btn(t("help"), "data-help", "text-button")}</footer>`;
// 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(
`<h2>${t("next")}</h2><div class="upcoming-details">${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 ?? {};