From f806bdef1f3e737f01f32f5e6cc280f90999baf8 Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Thu, 8 Oct 2026 11:32:52 +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 board toolbar's undo slot shows an "Undo my move" control while BGS reports it available and the current turn has no unsaved moves (those keep the in-turn undo); it stays hidden for spectators, in analysis, during replays and in lessons. Clicking it asks BGS to undo, which then sends the earlier state: going back in history discards the local selection, bid drafts and confirmations. The dev app mimics BGS's undo against its AI players. Also fixes the import order that failed the prettier check. Co-Authored-By: Claude Opus 5.5 --- pnpm-lock.yaml | 10 +- pnpm-workspace.yaml | 2 +- viewer/package.json | 2 +- viewer/scripts/protocol-smoke.mjs | 2 + viewer/scripts/undo-move-smoke.mjs | 80 +++++++++++ viewer/src/components/Game.vue | 62 ++++++++- .../src/components/buttons/UndoMoveButton.vue | 23 ++++ viewer/src/components/buttons/index.js | 3 +- viewer/src/launch.ts | 22 +++ viewer/src/localization/da.json | 3 +- viewer/src/localization/de.json | 3 +- viewer/src/localization/el.json | 3 +- viewer/src/localization/en.json | 3 +- viewer/src/localization/fa.json | 3 +- viewer/src/localization/fr.json | 3 +- viewer/src/localization/hi.json | 3 +- viewer/src/localization/it.json | 3 +- viewer/src/localization/ko.json | 3 +- viewer/src/localization/nl.json | 3 +- viewer/src/localization/pl.json | 3 +- viewer/src/localization/pt-BR.json | 3 +- viewer/src/localization/ro.json | 3 +- viewer/src/localization/ru.json | 3 +- viewer/src/localization/vi.json | 3 +- viewer/src/localization/zh-TW.json | 3 +- viewer/src/self-contained.ts | 32 ++++- viewer/tests/unit/bid-revision.spec.ts | 2 +- viewer/tests/unit/undo-move.spec.ts | 127 ++++++++++++++++++ 28 files changed, 385 insertions(+), 30 deletions(-) create mode 100644 viewer/scripts/undo-move-smoke.mjs create mode 100644 viewer/src/components/buttons/UndoMoveButton.vue create mode 100644 viewer/tests/unit/undo-move.spec.ts diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e1ca33c..ce274ea 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -86,8 +86,8 @@ importers: viewer: dependencies: '@boardgamers/protocol': - specifier: 0.9.0 - version: 0.9.0 + specifier: 0.10.0 + version: 0.10.0 container-engine: specifier: workspace:../engine version: link:../engine @@ -1042,10 +1042,10 @@ packages: } engines: { node: '>=6.9.0' } - '@boardgamers/protocol@0.9.0': + '@boardgamers/protocol@0.10.0': resolution: { - integrity: sha512-xDQMui0xqqRF/ERIJ7Rm79JonMA2+6zn1CrgxpM6Oy3SpFKF6i0Wo6oAyYYqMveqiWJCkC0WvHlePclVfbH/IQ==, + integrity: sha512-U+nOK8xeQANvjzwacHirBW+ItDf9AOmHLtkoyTI/XYFCOpL6lPsEgCbmcxnmkXv2a1/lgtVN3WpSERHUqkQkXw==, } '@cspotcode/source-map-support@0.8.1': @@ -11587,7 +11587,7 @@ snapshots: '@babel/helper-string-parser': 7.29.7 '@babel/helper-validator-identifier': 7.29.7 - '@boardgamers/protocol@0.9.0': + '@boardgamers/protocol@0.10.0': dependencies: zod: 4.6.2 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 2fe2342..8092318 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -18,7 +18,7 @@ allowBuilds: autoInstallPeers: false minimumReleaseAgeExclude: - - '@boardgamers/protocol@0.2.2 || 0.3.0 || 0.3.1 || 0.3.3 || 0.4.0 || 0.4.2 || 0.5.0 || 0.6.0 || 0.6.1 || 0.6.2 || 0.8.1' + - '@boardgamers/protocol@0.2.2 || 0.3.0 || 0.3.1 || 0.3.3 || 0.4.0 || 0.4.2 || 0.5.0 || 0.6.0 || 0.6.1 || 0.6.2 || 0.8.1 || 0.10.0' # The cli-plugin-typescript fork-ts-checker shim does a bare # require('@vue/compiler-sfc') expecting the vue-3 parse shape ({descriptor}). # It declares no such dependency, so resolution falls back to pnpm's hidden diff --git a/viewer/package.json b/viewer/package.json index c52021b..d6c79ac 100644 --- a/viewer/package.json +++ b/viewer/package.json @@ -19,7 +19,7 @@ "preview:tutorial": "node scripts/tutorial-preview.mjs" }, "dependencies": { - "@boardgamers/protocol": "0.9.0", + "@boardgamers/protocol": "0.10.0", "container-engine": "workspace:../engine", "core-js": "^3.6.5", "lodash": "^4.17.19", diff --git a/viewer/scripts/protocol-smoke.mjs b/viewer/scripts/protocol-smoke.mjs index 08e83ed..e69ff36 100644 --- a/viewer/scripts/protocol-smoke.mjs +++ b/viewer/scripts/protocol-smoke.mjs @@ -7,6 +7,7 @@ import { chromium } from 'playwright'; import { checkAuctionMessages } from './auction-messages-smoke.mjs'; import { checkFinalScore } from './final-score-smoke.mjs'; import { checkHostPresentation } from './host-presentation-smoke.mjs'; +import { checkUndoMove } from './undo-move-smoke.mjs'; const game = 'container'; const require = createRequire(import.meta.url); @@ -414,6 +415,7 @@ try { ); await checkHostPresentation(page, 'host', `/tmp/container-board-thumbnail-${width}.png`); await checkAuctionMessages(page, state); + await checkUndoMove(page, engine); assert.deepEqual(errors, []); await page.close(); console.log(`${game} ${width}px: protocol/chat smoke passed`); diff --git a/viewer/scripts/undo-move-smoke.mjs b/viewer/scripts/undo-move-smoke.mjs new file mode 100644 index 0000000..cc2c219 --- /dev/null +++ b/viewer/scripts/undo-move-smoke.mjs @@ -0,0 +1,80 @@ +import assert from 'node:assert/strict'; + +// "Undo my move": BGS offers it in games against bots (protocol `undo:available` / `undo`). +export async function checkUndoMove(page, engine) { + const earlier = JSON.parse(JSON.stringify(engine.setup(3, {}, 'undo-move'))); + earlier.players.forEach((player, index) => { + player.name = ['You', 'Bot 1', 'Bot 2'][index]; + }); + const seat = earlier.currentPlayers[0]; + const later = engine.move(JSON.parse(JSON.stringify(earlier)), { name: 'pass', data: true }, seat); + assert.ok(later.log.length > earlier.log.length); + await page.evaluate( + ({ later, seat }) => { + window.undoRequests = 0; + host.on('undo', () => undoRequests++); + host.emit('preferences', { sound: false, analysis: false }); + host.emit('player', { index: seat }); + host.emit('state', later); + }, + { later, seat } + ); + const control = page.locator('[data-board-control="undo-move"]'); + const turnUndo = page.locator('[data-board-control="undo"]'); + const status = page.locator('.statusBar span'); + await turnUndo.waitFor(); + assert.equal(await control.count(), 0, 'hidden until BGS offers it'); + + await page.evaluate(() => host.emit('undo:available', true)); + await control.waitFor(); + assert.equal(await control.getAttribute('aria-label'), 'Undo my move'); + assert.equal(await control.locator('title').textContent(), 'Undo my move'); + assert.equal(await turnUndo.count(), 0, 'it stands in for the in-turn undo'); + assert.doesNotMatch(await status.textContent(), /your turn/); + await control.click(); + assert.equal(await page.evaluate(() => undoRequests), 1, 'clicking asks BGS to undo'); + + // BGS then sends the earlier position: the move count goes down. + await page.evaluate((earlier) => host.emit('state', earlier), earlier); + await page.waitForFunction(() => document.querySelector('.statusBar span')?.textContent === "It's your turn!"); + assert.equal( + await page.locator('.journal-entry').count(), + earlier.log.length, + 'the journal drops the moves taken back' + ); + + // Hidden while BGS replays history, for spectators and in analysis. + const emit = (event) => + page.evaluate((event) => { + if (typeof event === 'string') host.emit(event); + else for (const [name, value] of Object.entries(event)) host.emit(name, value); + }, event); + for (const [enter, leave] of [ + ['replay:start', 'replay:end'], + [{ player: {} }, { player: { index: seat } }], + [{ preferences: { sound: false, analysis: true } }, { preferences: { sound: false, analysis: false } }], + ]) { + await emit(enter); + await control.waitFor({ state: 'detached' }); + assert.equal(await turnUndo.count(), 1); + await emit(leave); + await control.waitFor(); + } + + // Translated like the other board controls. + await page.evaluate(() => host.emit('preferences', { sound: false, analysis: false, locale: 'fr' })); + await page.waitForFunction( + () => + document.querySelector('[data-board-control="undo-move"]')?.getAttribute('aria-label') === + 'Annuler mon coup' + ); + await page.evaluate(() => host.emit('preferences', { sound: false, analysis: false, locale: 'en' })); + await page.waitForFunction( + () => document.querySelector('[data-board-control="undo-move"]')?.getAttribute('aria-label') === 'Undo my move' + ); + + await page.evaluate(() => host.emit('undo:available', false)); + await control.waitFor({ state: 'detached' }); + assert.equal(await turnUndo.count(), 1); + assert.equal(await page.evaluate(() => undoRequests), 1); +} diff --git a/viewer/src/components/Game.vue b/viewer/src/components/Game.vue index fae49ac..60fe57e 100644 --- a/viewer/src/components/Game.vue +++ b/viewer/src/components/Game.vue @@ -90,7 +90,15 @@ :enabled="canPass()" @click="pass()" /> + + + + + + Undo my move + + + diff --git a/viewer/src/components/buttons/index.js b/viewer/src/components/buttons/index.js index 6d801e9..e9a5425 100644 --- a/viewer/src/components/buttons/index.js +++ b/viewer/src/components/buttons/index.js @@ -4,5 +4,6 @@ import LogButton from './LogButton.vue'; import PassButton from './PassButton.vue'; import SoundButton from './SoundButton.vue'; import UndoButton from './UndoButton.vue'; +import UndoMoveButton from './UndoMoveButton.vue'; -export { Button, HelpButton, LogButton, PassButton, SoundButton, UndoButton }; +export { Button, HelpButton, LogButton, PassButton, SoundButton, UndoButton, UndoMoveButton }; diff --git a/viewer/src/launch.ts b/viewer/src/launch.ts index cdd515b..7376fc3 100644 --- a/viewer/src/launch.ts +++ b/viewer/src/launch.ts @@ -28,9 +28,11 @@ function launch(selector: string) { player?: number; emitter: EventEmitter; preferences: Preferences; + undoAvailable: boolean; } = { state: null, emitter: new EventEmitter(), + undoAvailable: false, // Observable so preference changes update the UI immediately: Game receives // this object as a prop, and Vue 2 does not deep-observe prop values coming // from a non-reactive parent — plain-object mutations (the in-game sound/help @@ -49,6 +51,13 @@ function launch(selector: string) { const thumbnail = createBoardThumbnail(app.$el); const localization = mountLocalization(target.ownerDocument.body); + // "Undo my move" (games against bots): offered by BGS, hidden while replaying history. + let undoOffered = false; + let replaying = false; + const updateUndo = () => { + params.undoAvailable = undoOffered && !replaying; + app.$forceUpdate(); + }; const viewer = createViewer({ async onThumbnail(size) { await app.$nextTick(); @@ -65,6 +74,10 @@ function launch(selector: string) { params.player = data.index; app.$forceUpdate(); }, + onUndoAvailable(available) { + undoOffered = available; + updateUndo(); + }, async onPreferences(data) { if (!(await localization.setLocale(data.locale))) { return; @@ -90,6 +103,15 @@ function launch(selector: string) { params.emitter.on('replaceLog', (data: string[]) => viewer.replaceLog(data)); params.emitter.on('replay:info', (info) => viewer.setReplayInfo(info)); params.emitter.on('update:preference', ({ name, value }) => viewer.updatePreference(name, value)); + params.emitter.on('undo', () => viewer.undo()); + item.on('replay:start', () => { + replaying = true; + updateUndo(); + }); + item.on('replay:end', () => { + replaying = false; + updateUndo(); + }); installActionSounds(item); const removeCards = installPlayerCards(app.$el, viewer); const removeChat = mountGameChat(item, app.$el); diff --git a/viewer/src/localization/da.json b/viewer/src/localization/da.json index ac203a0..abe773d 100644 --- a/viewer/src/localization/da.json +++ b/viewer/src/localization/da.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Øens værdi hvis spillet sluttede nu, inklusive den kasserede farve og bonussen for et komplet sæt.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} accepterer buddet fra {p1} på ${p2} og modtager ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} afviser alle bud og køber lasten for ${p1}", - "Change bid": "Ændr bud" + "Change bid": "Ændr bud", + "Undo my move": "Fortryd mit træk" } diff --git a/viewer/src/localization/de.json b/viewer/src/localization/de.json index 9b80da5..650dcdc 100644 --- a/viewer/src/localization/de.json +++ b/viewer/src/localization/de.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Inselwertung bei sofortigem Spielende, einschließlich der entfernten Farbe und des Bonus für alle fünf Farben.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} nimmt das Gebot von {p1} über ${p2} an und erhält ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} lehnt alle Gebote ab und kauft die Ladung für ${p1}", - "Change bid": "Gebot ändern" + "Change bid": "Gebot ändern", + "Undo my move": "Zug zurücknehmen" } diff --git a/viewer/src/localization/el.json b/viewer/src/localization/el.json index e411804..bc749f9 100644 --- a/viewer/src/localization/el.json +++ b/viewer/src/localization/el.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Βαθμολογία νησιού αν το παιχνίδι τελείωνε τώρα, με την αφαίρεση του χρώματος και το μπόνους πλήρους σετ.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} δέχεται την προσφορά ${p2} του παίκτη {p1} και λαμβάνει ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} απορρίπτει όλες τις προσφορές και αγοράζει το φορτίο για ${p1}", - "Change bid": "Αλλαγή προσφοράς" + "Change bid": "Αλλαγή προσφοράς", + "Undo my move": "Αναίρεση κίνησης" } diff --git a/viewer/src/localization/en.json b/viewer/src/localization/en.json index da27e12..ce756c8 100644 --- a/viewer/src/localization/en.json +++ b/viewer/src/localization/en.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Island score if the game ended now, including the discarded colour and full-set bonus.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} declines all bids and buys the cargo for ${p1}", - "Change bid": "Change bid" + "Change bid": "Change bid", + "Undo my move": "Undo my move" } diff --git a/viewer/src/localization/fa.json b/viewer/src/localization/fa.json index cd8355a..dd74e77 100644 --- a/viewer/src/localization/fa.json +++ b/viewer/src/localization/fa.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "امتیاز جزیره اگر بازی همین حالا تمام شود، با احتساب رنگ حذف‌شده و پاداش مجموعهٔ کامل رنگ‌ها.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} پیشنهاد ${p2} از {p1} را می‌پذیرد و ${p3} دریافت می‌کند", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} همهٔ پیشنهادها را رد می‌کند و محموله را به قیمت ${p1} می‌خرد", - "Change bid": "تغییر پیشنهاد" + "Change bid": "تغییر پیشنهاد", + "Undo my move": "بازگرداندن حرکت" } diff --git a/viewer/src/localization/fr.json b/viewer/src/localization/fr.json index f7b3c0e..4470ae2 100644 --- a/viewer/src/localization/fr.json +++ b/viewer/src/localization/fr.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Score de votre île si la partie se terminait maintenant, après retrait de la couleur défaussée et application du bonus des cinq couleurs.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} accepte l’enchère de {p1} de ${p2} et reçoit ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} refuse toutes les enchères et achète la cargaison pour ${p1}", - "Change bid": "Modifier l’enchère" + "Change bid": "Modifier l’enchère", + "Undo my move": "Annuler mon coup" } diff --git a/viewer/src/localization/hi.json b/viewer/src/localization/hi.json index 759bc4d..d0f616d 100644 --- a/viewer/src/localization/hi.json +++ b/viewer/src/localization/hi.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "यदि खेल अभी समाप्त हो जाए तो द्वीप का स्कोर, हटाए गए रंग और पूरे सेट के बोनस सहित।", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0}, {p1} की ${p2} की बोली स्वीकार करता है और ${p3} प्राप्त करता है", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} सभी बोलियाँ अस्वीकार करके ${p1} में माल खरीदता है", - "Change bid": "बोली बदलें" + "Change bid": "बोली बदलें", + "Undo my move": "अपनी चाल वापस लें" } diff --git a/viewer/src/localization/it.json b/viewer/src/localization/it.json index 522301d..97cf1ec 100644 --- a/viewer/src/localization/it.json +++ b/viewer/src/localization/it.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Punteggio dell’isola se la partita finisse ora, inclusi il colore scartato e il bonus del set completo.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} accetta l’offerta di ${p2} di {p1} e riceve ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} rifiuta tutte le offerte e acquista il carico per ${p1}", - "Change bid": "Modifica offerta" + "Change bid": "Modifica offerta", + "Undo my move": "Annulla la mossa" } diff --git a/viewer/src/localization/ko.json b/viewer/src/localization/ko.json index 8e71e2c..4ea3cc5 100644 --- a/viewer/src/localization/ko.json +++ b/viewer/src/localization/ko.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "지금 게임이 끝날 경우의 섬 점수입니다. 버리는 색상과 전체 색상 세트 보너스를 반영합니다.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0}: {p1}의 ${p2} 입찰을 수락하고 ${p3}를 받습니다", "{p0} declines all bids and buys the cargo for ${p1}": "{p0}: 모든 입찰을 거절하고 화물을 ${p1}에 구매합니다", - "Change bid": "입찰 변경" + "Change bid": "입찰 변경", + "Undo my move": "내 수 되돌리기" } diff --git a/viewer/src/localization/nl.json b/viewer/src/localization/nl.json index f4b591b..fc9d6ee 100644 --- a/viewer/src/localization/nl.json +++ b/viewer/src/localization/nl.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Eilandscore als het spel nu zou eindigen, inclusief de verwijderde kleur en de bonus voor een volledige set.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} accepteert het bod van {p1} van ${p2} en ontvangt ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} wijst alle biedingen af en koopt de lading voor ${p1}", - "Change bid": "Bod wijzigen" + "Change bid": "Bod wijzigen", + "Undo my move": "Zet ongedaan maken" } diff --git a/viewer/src/localization/pl.json b/viewer/src/localization/pl.json index ec94401..7b8ebee 100644 --- a/viewer/src/localization/pl.json +++ b/viewer/src/localization/pl.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Wynik wyspy, gdyby gra skończyła się teraz, z uwzględnieniem odrzuconego koloru i premii za komplet kolorów.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} przyjmuje ofertę {p1} w wysokości ${p2} i otrzymuje ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} odrzuca wszystkie oferty i kupuje ładunek za ${p1}", - "Change bid": "Zmień ofertę" + "Change bid": "Zmień ofertę", + "Undo my move": "Cofnij ruch" } diff --git a/viewer/src/localization/pt-BR.json b/viewer/src/localization/pt-BR.json index 9df541b..3993962 100644 --- a/viewer/src/localization/pt-BR.json +++ b/viewer/src/localization/pt-BR.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Pontuação da ilha se a partida terminasse agora, considerando a cor descartada e o bônus do conjunto completo.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} aceita o lance de ${p2} de {p1} e recebe ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} recusa todos os lances e compra a carga por ${p1}", - "Change bid": "Alterar lance" + "Change bid": "Alterar lance", + "Undo my move": "Desfazer jogada" } diff --git a/viewer/src/localization/ro.json b/viewer/src/localization/ro.json index 9e8ae9c..4cfa462 100644 --- a/viewer/src/localization/ro.json +++ b/viewer/src/localization/ro.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Scorul insulei dacă jocul s-ar termina acum, incluzând culoarea eliminată și bonusul pentru setul complet.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} acceptă oferta de ${p2} a lui {p1} și primește ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} refuză toate ofertele și cumpără încărcătura pentru ${p1}", - "Change bid": "Modifică oferta" + "Change bid": "Modifică oferta", + "Undo my move": "Anulează mutarea" } diff --git a/viewer/src/localization/ru.json b/viewer/src/localization/ru.json index a325c35..68ff9a5 100644 --- a/viewer/src/localization/ru.json +++ b/viewer/src/localization/ru.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Стоимость острова, если бы игра закончилась сейчас, с учётом сброшенного цвета и бонуса за полный набор.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} принимает ставку {p1} в размере ${p2} и получает ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} отклоняет все ставки и покупает груз за ${p1}", - "Change bid": "Изменить ставку" + "Change bid": "Изменить ставку", + "Undo my move": "Отменить ход" } diff --git a/viewer/src/localization/vi.json b/viewer/src/localization/vi.json index da9416a..66a5674 100644 --- a/viewer/src/localization/vi.json +++ b/viewer/src/localization/vi.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "Điểm đảo nếu trò chơi kết thúc ngay bây giờ, đã tính màu bị loại và thưởng đủ bộ màu.", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} chấp nhận giá ${p2} của {p1} và nhận ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} từ chối mọi giá đấu và mua hàng với giá ${p1}", - "Change bid": "Đổi giá đấu" + "Change bid": "Đổi giá đấu", + "Undo my move": "Hoàn tác nước đi" } diff --git a/viewer/src/localization/zh-TW.json b/viewer/src/localization/zh-TW.json index 2b91f6c..207fcda 100644 --- a/viewer/src/localization/zh-TW.json +++ b/viewer/src/localization/zh-TW.json @@ -652,5 +652,6 @@ "Island score if the game ended now, including the discarded colour and full-set bonus.": "若遊戲現在結束,島嶼的計分價值,已計入棄置顏色與完整顏色組合加成。", "{p0} accepts {p1}'s bid of ${p2} and receives ${p3}": "{p0} 接受 {p1} 的 ${p2} 出價並獲得 ${p3}", "{p0} declines all bids and buys the cargo for ${p1}": "{p0} 拒絕所有出價並以 ${p1} 購買貨物", - "Change bid": "更改出價" + "Change bid": "更改出價", + "Undo my move": "撤回我的行動" } diff --git a/viewer/src/self-contained.ts b/viewer/src/self-contained.ts index 7dda3ee..db386fd 100644 --- a/viewer/src/self-contained.ts +++ b/viewer/src/self-contained.ts @@ -30,6 +30,30 @@ function launchSelfContained(selector = '#app') { playerIndex = AbstractJudge.currentPlayers[0]; } + // Delayed deliveries (AI replies, echoes), cancelled when a move is taken back. + const timers = new Set>(); + const later = (deliver: () => void, delay: number) => { + const timer = setTimeout(() => { + timers.delete(timer); + deliver(); + }, delay); + timers.add(timer); + }; + + // Mimic BGS's "Undo my move" in games against bots: each saved move of the player is an + // undo point, and undoing restores the position before it, without the AI replies. + const undoPoints: GameState[] = []; + const offerUndo = () => emitter.emit('undo:available', undoPoints.length > 0); + emitter.on('undo', () => { + const previous = undoPoints.pop(); + if (!previous) return; + timers.forEach(clearTimeout); + timers.clear(); + gameState = previous; + emitter.emit('state', cloneDeep(strip ? stripSecret(gameState, playerIndex) : gameState)); + offerUndo(); + }); + emitter.on('move', async (moves: Move | Move[]) => { console.log('moves received', moves); @@ -45,12 +69,14 @@ function launchSelfContained(selector = '#app') { // Tentative: just echo the state back to the acting player. Delayed like on // the real platform, where the echo arrives over the network mid-animation. const echo = cloneDeep(strip ? stripSecret(newState, playerIndex) : newState); - setTimeout(() => emitter.emit('state', echo), 300); + later(() => emitter.emit('state', echo), 300); return; } + undoPoints.push(cloneDeep(gameState)); gameState = newState; emitter.emit('state', cloneDeep(strip ? stripSecret(gameState, playerIndex) : gameState)); + offerUndo(); let delay = 800; while (gameState.players.some((pl) => pl.isAI && pl.availableMoves)) { @@ -59,7 +85,7 @@ function launchSelfContained(selector = '#app') { gameState.players.findIndex((pl) => pl.isAI && pl.availableMoves) ); let newState = cloneDeep(strip ? stripSecret(gameState, playerIndex) : gameState); - setTimeout(() => emitter.emit('state', newState), delay); + later(() => emitter.emit('state', newState), delay); delay += 800; } @@ -80,7 +106,7 @@ function launchSelfContained(selector = '#app') { gameState.players.findIndex((pl) => pl.isAI && pl.availableMoves) ); let newState = cloneDeep(strip ? stripSecret(gameState, playerIndex) : gameState); - setTimeout(() => emitter.emit('state', newState), delay); + later(() => emitter.emit('state', newState), delay); delay += 800; } diff --git a/viewer/tests/unit/bid-revision.spec.ts b/viewer/tests/unit/bid-revision.spec.ts index 9651ba5..86bb511 100644 --- a/viewer/tests/unit/bid-revision.spec.ts +++ b/viewer/tests/unit/bid-revision.spec.ts @@ -1,5 +1,5 @@ -import { expect } from 'chai'; import Game from '@/components/Game.vue'; +import { expect } from 'chai'; const options = (Game as any).options; describe('bid revision controls', () => { it('prefills the additional amount during a tied auction', () => { diff --git a/viewer/tests/unit/undo-move.spec.ts b/viewer/tests/unit/undo-move.spec.ts new file mode 100644 index 0000000..5ab62c8 --- /dev/null +++ b/viewer/tests/unit/undo-move.spec.ts @@ -0,0 +1,127 @@ +import { UndoButton, UndoMoveButton } from '@/components/buttons'; +import Game from '@/components/Game.vue'; +import { shallowMount } from '@vue/test-utils'; +import { expect } from 'chai'; +import { move, Move, MoveName, setup } from 'container-engine'; +import { EventEmitter } from 'events'; + +const copy = (value) => JSON.parse(JSON.stringify(value)); +const pass: Move = { name: MoveName.Pass, data: true }; +const getLoan: Move = { name: MoveName.GetLoan, data: true }; + +function mountGame(props: Record = {}) { + const state = setup(3, {}, 'undo-move'); + const player = state.currentPlayers[0]; + const emitter = new EventEmitter(); + const undos: unknown[] = []; + emitter.on('undo', () => undos.push(true)); + const wrapper = shallowMount(Game, { + propsData: { state, player, emitter, preferences: { sound: false }, ...props }, + }); + const shown = () => wrapper.findComponent(UndoMoveButton).exists(); + return { wrapper, vm: wrapper.vm as any, state, player, undos, shown }; +} + +describe('Undo my move', () => { + it('is hidden by default, shown while BGS offers it, and requests the undo', async () => { + const { wrapper, undos, shown } = mountGame(); + expect(shown()).to.equal(false); + expect(wrapper.findComponent(UndoButton).exists()).to.equal(true); + await wrapper.setProps({ undoAvailable: true }); + expect(shown()).to.equal(true); + expect(wrapper.findComponent(UndoButton).exists(), 'it takes the in-turn undo slot').to.equal(false); + wrapper.findComponent(UndoMoveButton).vm.$emit('click'); + expect(undos).to.have.length(1); + await wrapper.setProps({ undoAvailable: false }); + expect(shown()).to.equal(false); + expect(wrapper.findComponent(UndoButton).exists()).to.equal(true); + wrapper.destroy(); + }); + + for (const [mode, props] of [ + ['spectators', { player: undefined }], + ['analysis', { preferences: { sound: false, analysis: true } }], + ['lessons', { tutorialMove: () => undefined }], + ['a non-interactive board', { interactionDisabled: true }], + ] as [string, Record][]) { + it(`is hidden for ${mode}`, async () => { + const { wrapper, vm, undos, shown } = mountGame({ undoAvailable: true, ...props }); + expect(shown()).to.equal(false); + vm.requestUndo(); + expect(undos).to.have.length(0); + wrapper.destroy(); + }); + } + + it('is hidden once the game has ended', async () => { + const { wrapper, state, shown } = mountGame({ undoAvailable: true }); + expect(shown()).to.equal(true); + await wrapper.setProps({ state: { ...copy(state), phase: 'gameEnd' } }); + expect(shown()).to.equal(false); + wrapper.destroy(); + }); + + it('leaves the slot to the in-turn undo while the turn has unsaved moves', async () => { + const { wrapper, vm, shown } = mountGame({ undoAvailable: true }); + vm.sendMove(getLoan); + expect(vm.turnMoves).to.have.length(1); + await wrapper.vm.$nextTick(); + expect(shown()).to.equal(false); + expect(wrapper.findComponent(UndoButton).props('enabled')).to.equal(true); + vm.undo(); + await wrapper.vm.$nextTick(); + expect(shown()).to.equal(true); + wrapper.destroy(); + }); + + it('renders an earlier state and discards drafts when moves are taken back', async () => { + const { wrapper, vm, state, player } = mountGame({ undoAvailable: true }); + const later = move(copy(state), pass, player); + expect(later.newTurn).to.not.equal(false); + await wrapper.setProps({ state: later }); + const drafts = () => ({ + selected: vm.ui.selected, + editingBid: vm.editingBid, + confirmBid: vm.confirmBidVisible, + confirmBidRevision: vm.confirmBidRevision, + totalBid: vm.totalBid, + confirmSail: vm.confirmSailVisible, + }); + const draft = () => + Object.assign(vm, { + editingBid: '1:3:0:initial', + confirmBidVisible: true, + confirmBidRevision: '1:3:0:initial', + totalBid: 7, + confirmSailVisible: true, + }); + draft(); + vm.ui.selected = { pieceType: 'container', pieceId: 'C1', canDrag: true }; + const version = vm.draftsVersion; + + // A later position (the game moving on) keeps the drafts. + await wrapper.setProps({ state: copy(later) }); + expect(drafts().totalBid).to.equal(7); + + await wrapper.setProps({ state: copy(state) }); + expect(copy(vm.G)).to.deep.equal(copy(state)); + expect(vm.turnMoves).to.deep.equal([]); + expect(drafts()).to.deep.equal({ + selected: null, + editingBid: null, + confirmBid: false, + confirmBidRevision: null, + totalBid: 0, + confirmSail: false, + }); + expect(vm.draftsVersion, 'the bid calculator is remounted').to.equal(version + 1); + + // Requesting the undo discards drafts right away, even before the state arrives. + draft(); + wrapper.findComponent(UndoMoveButton).vm.$emit('click'); + expect(drafts().totalBid).to.equal(0); + expect(drafts().confirmBid).to.equal(false); + expect(vm.draftsVersion).to.equal(version + 2); + wrapper.destroy(); + }); +});