From e90041904b1f73680e66c85575ec07f2a5936bc5 Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Thu, 8 Oct 2026 11:41:51 +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 `undo:available` / `undo`). The board's Undo button offers it once the turn in progress has nothing left to undo locally, and never during replays, analyses or round planning, for spectators, or while a move is on its way. A double click on Undo cannot reach it. BGS then sends the earlier state. A committed state that takes back the player's own moves drops the turn buffer, a bid being edited, open dialogs, a hybrid plant's fuel choice and the bid dialled into the calculator. The label is translated in all 16 languages. Unit tests and the protocol browser smoke cover the control, and the development sandbox mimics BGS's undo. Co-Authored-By: Claude Opus 5.5 --- viewer/README.md | 4 + viewer/package.json | 2 +- viewer/pnpm-lock.yaml | 8 +- viewer/scripts/protocol-smoke.mjs | 2 + viewer/scripts/undo-smoke.mjs | 120 ++++++++++++++ viewer/src/components/Game.vue | 109 ++++++++++++- .../components/boards/PowerPlantMarket.vue | 6 +- viewer/src/components/buttons/UndoButton.vue | 6 +- viewer/src/launch.ts | 8 + 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 | 17 +- viewer/src/util/turn-buffer.ts | 26 +++ viewer/tests/unit/undo-move.spec.ts | 149 ++++++++++++++++++ 28 files changed, 478 insertions(+), 27 deletions(-) create mode 100644 viewer/scripts/undo-smoke.mjs create mode 100644 viewer/tests/unit/undo-move.spec.ts diff --git a/viewer/README.md b/viewer/README.md index f281b49..805f903 100644 --- a/viewer/README.md +++ b/viewer/README.md @@ -56,6 +56,10 @@ Lessons live in `src/tutorial/lessons.ts`. Keep their IDs stable and increase a See the [desktop and mobile screenshots](docs/tutorials/README.md) for examples of the tutorial UI. +## Undo against bots + +When the only human of a game plays against bots, BGS can take back their last saved move (protocol 0.10.0 `undo:available` / `undo`). The board's Undo button then becomes "Undo my move" once the turn in progress has nothing left to undo locally. It stays hidden during replays, analyses and round planning, for spectators, and while a move is on its way. BGS answers with the earlier state, and the viewer drops the turn buffer, open dialogs and the bid being dialled. The development sandbox (`npm run serve`) offers the same undo against its bots. + ## Shared accessibility preference The viewer accepts BGS's `colorBlind` boolean preference (default `false`). The eye button on the board changes it through `update:preference`, so BGS saves the setting across games. It also works locally in tutorials. diff --git a/viewer/package.json b/viewer/package.json index a4cc50e..221ddd5 100644 --- a/viewer/package.json +++ b/viewer/package.json @@ -23,7 +23,7 @@ "tutorial:manifest": "node scripts/tutorial-manifest.cjs" }, "dependencies": { - "@boardgamers/protocol": "0.9.0", + "@boardgamers/protocol": "0.10.0", "core-js": "^3.6.5", "lodash": "^4.17.19", "powergrid-engine": "workspace:../engine", diff --git a/viewer/pnpm-lock.yaml b/viewer/pnpm-lock.yaml index eb21060..f9175fa 100644 --- a/viewer/pnpm-lock.yaml +++ b/viewer/pnpm-lock.yaml @@ -1,7 +1,7 @@ lockfileVersion: 5.4 specifiers: - '@boardgamers/protocol': 0.9.0 + '@boardgamers/protocol': 0.10.0 '@types/assert': ^1.4.7 '@types/chai': ^4.2.11 '@types/events': ^3.0.0 @@ -34,7 +34,7 @@ specifiers: zod: 4.6.4 dependencies: - '@boardgamers/protocol': 0.9.0 + '@boardgamers/protocol': 0.10.0 core-js: 3.50.0 lodash: 4.18.1 powergrid-engine: link:../engine @@ -1547,10 +1547,10 @@ packages: '@babel/helper-string-parser': 7.29.7 '@babel/helper-validator-identifier': 7.29.7 - /@boardgamers/protocol/0.9.0: + /@boardgamers/protocol/0.10.0: resolution: { - integrity: sha512-xDQMui0xqqRF/ERIJ7Rm79JonMA2+6zn1CrgxpM6Oy3SpFKF6i0Wo6oAyYYqMveqiWJCkC0WvHlePclVfbH/IQ==, + integrity: sha512-U+nOK8xeQANvjzwacHirBW+ItDf9AOmHLtkoyTI/XYFCOpL6lPsEgCbmcxnmkXv2a1/lgtVN3WpSERHUqkQkXw==, } dependencies: zod: 4.6.4 diff --git a/viewer/scripts/protocol-smoke.mjs b/viewer/scripts/protocol-smoke.mjs index 783ab93..c9ef242 100644 --- a/viewer/scripts/protocol-smoke.mjs +++ b/viewer/scripts/protocol-smoke.mjs @@ -1,5 +1,6 @@ import { checkHostPresentation } from './host-presentation-smoke.mjs'; import { checkMiddleEastReplay } from './replay-smoke.mjs'; +import { checkUndoMove } from './undo-smoke.mjs'; import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { createServer } from 'node:http'; @@ -429,6 +430,7 @@ try { assert.deepEqual(await page.evaluate(() => preferenceUpdates), [{ name: 'colorBlind', value: false }]); await checkHostPresentation(page, 'host', `/tmp/powergrid-board-thumbnail-${width}.png`); if (width === 1400) await checkMiddleEastReplay(page); + await checkUndoMove(page); assert.deepEqual(errors, []); await page.close(); console.log(`${game} ${width}px: protocol/chat smoke passed`); diff --git a/viewer/scripts/undo-smoke.mjs b/viewer/scripts/undo-smoke.mjs new file mode 100644 index 0000000..28640b1 --- /dev/null +++ b/viewer/scripts/undo-smoke.mjs @@ -0,0 +1,120 @@ +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; + +const require = createRequire(import.meta.url); +const engine = require(fileURLToPath(new URL('../../engine/dist/index.js', import.meta.url))); + +// You (seat 0) against two bots in the first auction, as BGS sends it to your viewer. +function auction() { + let G = engine.setup(3, { map: 'Germany', variant: 'recharged', showMoney: true }, 'undo'); + G.players.forEach((player, index) => { + player.name = ['You', 'Ada', 'Bob'][index]; + }); + let time = 1; + const view = () => JSON.parse(JSON.stringify(engine.stripSecret(G, 0))); + const play = (seat, name, data = G.players[seat].availableMoves.Bid[0]) => { + G = engine.move(G, { name, data, time: time++ }, seat); + }; + const choosing = view(); + play(0, 'ChoosePowerPlant', G.players[0].availableMoves.ChoosePowerPlant[1]); + play(0, 'Bid'); + play(1, 'Bid'); + play(2, 'Bid'); + // Where "Undo my move" brings you back: before your second bid. + const firstRaise = view(); + play(0, 'Bid'); + play(1, 'Bid'); + play(2, 'Pass', true); + return { choosing, firstRaise, secondRaise: view() }; +} + +// BGS's "Undo my move" in games against bots (protocol `undo:available` / `undo`). +export async function checkUndoMove(page) { + const { choosing, firstRaise, secondRaise } = auction(); + assert.equal(firstRaise.currentBid + 1, 9); + assert.equal(secondRaise.currentBid + 1, 11); + const control = page.locator('[data-board-control="undo-move"]'); + const localUndo = page.locator('[data-board-control="undo"]'); + const visor = page.locator('.calculator .visor'); + const label = (text) => + page.waitForFunction( + (text) => document.querySelector('[data-board-control="undo-move"]')?.getAttribute('aria-label') === text, + text + ); + const emit = (event, payload) => page.evaluate(([event, payload]) => host.emit(event, payload), [event, payload]); + + await page.evaluate((state) => { + window.host = window.powergrid.launch('#app'); + window.undoRequests = 0; + window.undoReady = false; + host.on('ready', () => (window.undoReady = true)); + host.on('undo', () => window.undoRequests++); + host.emit('preferences', { sound: false, locale: 'en' }); + host.emit('player', { index: 0 }); + host.emit('state', state); + }, secondRaise); + await page.waitForFunction(() => window.undoReady); + await visor.waitFor(); + assert.equal(await control.count(), 0, 'hidden until BGS offers undo'); + assert.equal(await localUndo.getAttribute('aria-disabled'), 'true'); + + await 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 control.locator('image').count(), 1, 'uses the undo icon'); + assert.equal(await localUndo.count(), 0, 'takes the place of the empty local Undo'); + assert.equal(await page.locator('[data-board-slot="buttons"] [data-board-control="undo-move"]').count(), 1); + await emit('preferences', { sound: false, locale: 'fr' }); + await label('Annuler mon coup'); + assert.equal(await control.locator('title').textContent(), 'Annuler mon coup'); + await emit('preferences', { sound: false, locale: 'en' }); + await label('Undo my move'); + + // Only on the live board of a seated player. + await emit('replay:start'); + await control.waitFor({ state: 'detached' }); + await emit('replay:end'); + await control.waitFor(); + await emit('preferences', { sound: false, locale: 'en', analysis: true }); + await control.waitFor({ state: 'detached' }); + await emit('preferences', { sound: false, locale: 'en', analysis: false }); + await control.waitFor(); + await emit('player', {}); + await control.waitFor({ state: 'detached' }); + await emit('player', { index: 0 }); + await control.waitFor(); + + // Undo asks BGS, which answers with the earlier state: a bid dialled on the newer + // position must not survive it. + assert.equal(await visor.textContent(), '11'); + for (let i = 0; i < 2; i++) await page.locator('.calculator > g').nth(0).click(); + assert.equal(await visor.textContent(), '13'); + await control.click(); + assert.equal(await page.evaluate(() => undoRequests), 1); + await control.waitFor({ state: 'detached' }); + await emit('state', firstRaise); + await control.waitFor(); + assert.equal(await visor.textContent(), '9', 'the earlier bid floor, not the dialled bid'); + assert.match(await page.locator('.status-message').textContent(), /your turn to bid/); + + // A turn in progress is taken back by the board's own Undo first. + await emit('state', choosing); + await control.waitFor(); + await visor.waitFor({ state: 'detached' }); + await page.locator('[data-tutorial="plants"] g.canClick').first().click(); + await visor.waitFor(); + assert.equal(await control.count(), 0, 'buffered moves are undone locally first'); + assert.equal(await localUndo.getAttribute('aria-disabled'), null, 'the local Undo is enabled'); + await localUndo.click(); + assert.equal(await control.count(), 0, 'a double click on Undo cannot reach the saved move'); + await visor.waitFor({ state: 'detached' }); + await control.waitFor(); + + await emit('undo:available', false); + await control.waitFor({ state: 'detached' }); + assert.equal(await localUndo.getAttribute('aria-disabled'), 'true'); + assert.equal(await page.evaluate(() => undoRequests), 1); + console.log('powergrid "Undo my move": availability, translation, undo request and rewound state passed'); +} diff --git a/viewer/src/components/Game.vue b/viewer/src/components/Game.vue index f3068d5..7f43c7c 100644 --- a/viewer/src/components/Game.vue +++ b/viewer/src/components/Game.vue @@ -176,6 +176,7 @@ :minBid="changingBid ? revisionBids[0] : G.currentBid + 1 || G.minimunBid" :initialBid="changingBid ? replacementBid : undefined" :editingBid="changingBid" + :draftKey="draftKey" :maxBid="G.players[player] ? G.players[player].money : 0" :nextCardWeak="G.nextCardWeak" :plantDiscountActive="G.plantDiscountActive" @@ -462,12 +463,28 @@ :icon="phaseButtonIcon" @click="usePhaseButton" /> + + (this.recentLocalUndo = false), 1000); + if (this.changingBid) this.editingBid = null; + else this.undo(); + } + + // An "Undo my move" request is on its way to BGS. + undoRequested = false; + private undoRequestTimer: ReturnType | undefined; + // The board's Undo was just used, see `useUndoButton`. + recentLocalUndo = false; + private recentLocalUndoTimer: ReturnType | undefined; + // Changing it remounts drafts kept in child components (the bid calculator). + draftKey = 0; + + /** + * BGS's "Undo my move", in games against bots: BGS takes back the player's last SAVED + * move, with the bots' replies, and sends the earlier state. The turn in progress only + * lives in this viewer's buffer and the board's Undo takes it back, so BGS's undo is + * offered in that button's place once nothing is left to undo locally. Never while + * replaying, analysing, planning or spectating, nor while a move, premove or undo + * request is on its way. A method, like the other checks: preferences such as + * `analysis` arrive as plain properties that a cached computed would not see change. + */ + canUndoMove(): boolean { + return ( + this.undoAvailable && + !!this.G && + this.player != undefined && + !!this.G.players[this.player] && + !this.paused && + !this.interactionDisabled && + !this.tutorialMove && + !this.preferences.analysis && + !this.roundPlan && + !this.pendingPlanId && + !this.changingBid && + !this.poweringSubmitting && + !this.undoRequested && + !this.recentLocalUndo && + !this.canUndo() + ); + } + + undoMove() { + if (!this.canUndoMove()) return; + this.undoRequested = true; + if (this.undoRequestTimer) clearTimeout(this.undoRequestTimer); + // BGS answers with the earlier state; offer the control again if it never does. + this.undoRequestTimer = setTimeout(() => (this.undoRequested = false), 10000); + this.emitter.emit('undo'); + } + + /** + * Forget what was prepared on a position that no longer exists: the turn buffer, a bid + * being edited, open choice dialogs, a hybrid plant's fuel choice (kept in G, see + * `replaceState`) and the bid dialled into the calculator. + */ + abandonLocalTurn() { + this.turnMoves = []; + this.editingBid = null; + this.confirmVisible = this.discardVisible = this.freeJumpVisible = false; + this.discardedPowerPlant = null; + this.freeJumpCity = null; + this.soleBuyerPlant = null; + this.draftKey++; + // A round plan keeps showing its own board; the live one is rebuilt on return. + if (!this.roundPlan) this.G = null; + } + choosePowerPlant(powerPlant: PowerPlant) { const currentPlayer = this.G!.players[this.player!]; const availableMoves = currentPlayer.availableMoves!; @@ -3091,6 +3196,8 @@ export default class Game extends Vue { beforeDestroy() { if (this.pendingPlanTimer) clearTimeout(this.pendingPlanTimer); + if (this.undoRequestTimer) clearTimeout(this.undoRequestTimer); + if (this.recentLocalUndoTimer) clearTimeout(this.recentLocalUndoTimer); window.removeEventListener('resize', this.onViewportResize); window.removeEventListener('orientationchange', this.onViewportResize); window.removeEventListener('load', this.onViewportResize); diff --git a/viewer/src/components/boards/PowerPlantMarket.vue b/viewer/src/components/boards/PowerPlantMarket.vue index c880a0c..7ab457a 100644 --- a/viewer/src/components/boards/PowerPlantMarket.vue +++ b/viewer/src/components/boards/PowerPlantMarket.vue @@ -30,10 +30,11 @@ :powerPlant="chosenPowerPlant.powerPlant" /> + instance would keep displaying the previous auction's bid floor. The + draft key also resets a bid dialled before the game was rewound. --> diff --git a/viewer/src/launch.ts b/viewer/src/launch.ts index e16f58f..c2c39a5 100644 --- a/viewer/src/launch.ts +++ b/viewer/src/launch.ts @@ -30,6 +30,7 @@ function launch(selector: string) { emitter: EventEmitter; preferences: Preferences; avatars: string[]; + undoAvailable: boolean; } = { state: null, emitter: new EventEmitter(), @@ -50,6 +51,7 @@ function launch(selector: string) { geographicBackground: 'terrain', }), avatars: [], + undoAvailable: false, }; const app = new Vue({ @@ -85,6 +87,11 @@ function launch(selector: string) { params.avatars = data; app.$forceUpdate(); }, + // Games against bots: BGS can take back the player's last saved move. + onUndoAvailable(available) { + params.undoAvailable = available; + app.$forceUpdate(); + }, onTheme({ dark }) { target.ownerDocument.documentElement.dataset.powergridTheme = dark ? 'dark' : 'light'; }, @@ -122,6 +129,7 @@ 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()); 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 9e55088..6b3dda5 100644 --- a/viewer/src/localization/da.json +++ b/viewer/src/localization/da.json @@ -2006,5 +2006,6 @@ "Finish building": "Afslut byggeri", "Finish powering": "Afslut strømproduktion", "Cancel bid edit": "Annuller budændring", - "Power capacity: {count} cities": "Forsyningskapacitet: {count} byer" + "Power capacity: {count} cities": "Forsyningskapacitet: {count} byer", + "Undo my move": "Fortryd mit træk" } diff --git a/viewer/src/localization/de.json b/viewer/src/localization/de.json index 5059566..bf43263 100644 --- a/viewer/src/localization/de.json +++ b/viewer/src/localization/de.json @@ -2006,5 +2006,6 @@ "Finish building": "Bauen abschließen", "Finish powering": "Stromerzeugung abschließen", "Cancel bid edit": "Gebotsänderung abbrechen", - "Power capacity: {count} cities": "Versorgungskapazität: {count} Städte" + "Power capacity: {count} cities": "Versorgungskapazität: {count} Städte", + "Undo my move": "Zug zurücknehmen" } diff --git a/viewer/src/localization/el.json b/viewer/src/localization/el.json index 80b56f5..4ea27c5 100644 --- a/viewer/src/localization/el.json +++ b/viewer/src/localization/el.json @@ -2006,5 +2006,6 @@ "Finish building": "Ολοκλήρωση κατασκευής", "Finish powering": "Ολοκλήρωση ηλεκτροδότησης", "Cancel bid edit": "Ακύρωση αλλαγής προσφοράς", - "Power capacity: {count} cities": "Δυναμικότητα τροφοδοσίας: {count} πόλεις" + "Power capacity: {count} cities": "Δυναμικότητα τροφοδοσίας: {count} πόλεις", + "Undo my move": "Αναίρεση κίνησης" } diff --git a/viewer/src/localization/en.json b/viewer/src/localization/en.json index 8b66454..d6c47cd 100644 --- a/viewer/src/localization/en.json +++ b/viewer/src/localization/en.json @@ -2006,5 +2006,6 @@ "Finish building": "Finish building", "Finish powering": "Finish powering", "Cancel bid edit": "Cancel bid edit", - "Power capacity: {count} cities": "Power capacity: {count} cities" + "Power capacity: {count} cities": "Power capacity: {count} cities", + "Undo my move": "Undo my move" } diff --git a/viewer/src/localization/fa.json b/viewer/src/localization/fa.json index 3bd2056..0710ef6 100644 --- a/viewer/src/localization/fa.json +++ b/viewer/src/localization/fa.json @@ -2006,5 +2006,6 @@ "Finish building": "پایان ساخت‌وساز", "Finish powering": "پایان تولید برق", "Cancel bid edit": "لغو ویرایش پیشنهاد", - "Power capacity: {count} cities": "ظرفیت تأمین برق: {count} شهر" + "Power capacity: {count} cities": "ظرفیت تأمین برق: {count} شهر", + "Undo my move": "بازگرداندن حرکت" } diff --git a/viewer/src/localization/fr.json b/viewer/src/localization/fr.json index 047b70d..faf0a6b 100644 --- a/viewer/src/localization/fr.json +++ b/viewer/src/localization/fr.json @@ -2006,5 +2006,6 @@ "Finish building": "Terminer la construction", "Finish powering": "Terminer la production", "Cancel bid edit": "Annuler la modification", - "Power capacity: {count} cities": "Capacité électrique : {count} villes" + "Power capacity: {count} cities": "Capacité électrique : {count} villes", + "Undo my move": "Annuler mon coup" } diff --git a/viewer/src/localization/hi.json b/viewer/src/localization/hi.json index fc84013..fa0c98a 100644 --- a/viewer/src/localization/hi.json +++ b/viewer/src/localization/hi.json @@ -2006,5 +2006,6 @@ "Finish building": "निर्माण पूरा करें", "Finish powering": "बिजली उत्पादन पूरा करें", "Cancel bid edit": "बोली का बदलाव रद्द करें", - "Power capacity: {count} cities": "बिजली क्षमता: {count} शहर" + "Power capacity: {count} cities": "बिजली क्षमता: {count} शहर", + "Undo my move": "अपनी चाल वापस लें" } diff --git a/viewer/src/localization/it.json b/viewer/src/localization/it.json index bdddce0..773fb95 100644 --- a/viewer/src/localization/it.json +++ b/viewer/src/localization/it.json @@ -2006,5 +2006,6 @@ "Finish building": "Termina costruzione", "Finish powering": "Termina produzione", "Cancel bid edit": "Annulla modifica offerta", - "Power capacity: {count} cities": "Capacità di alimentazione: {count} città" + "Power capacity: {count} cities": "Capacità di alimentazione: {count} città", + "Undo my move": "Annulla la mossa" } diff --git a/viewer/src/localization/ko.json b/viewer/src/localization/ko.json index 601339e..b676d79 100644 --- a/viewer/src/localization/ko.json +++ b/viewer/src/localization/ko.json @@ -2006,5 +2006,6 @@ "Finish building": "건설 완료", "Finish powering": "발전 완료", "Cancel bid edit": "입찰 수정 취소", - "Power capacity: {count} cities": "전력 공급 용량: 도시 {count}개" + "Power capacity: {count} cities": "전력 공급 용량: 도시 {count}개", + "Undo my move": "내 수 되돌리기" } diff --git a/viewer/src/localization/nl.json b/viewer/src/localization/nl.json index 70d95e7..5a70d25 100644 --- a/viewer/src/localization/nl.json +++ b/viewer/src/localization/nl.json @@ -2006,5 +2006,6 @@ "Finish building": "Bouwen afronden", "Finish powering": "Stroomproductie afronden", "Cancel bid edit": "Bodwijziging annuleren", - "Power capacity: {count} cities": "Stroomcapaciteit: {count} steden" + "Power capacity: {count} cities": "Stroomcapaciteit: {count} steden", + "Undo my move": "Zet ongedaan maken" } diff --git a/viewer/src/localization/pl.json b/viewer/src/localization/pl.json index a4b3d81..16b804c 100644 --- a/viewer/src/localization/pl.json +++ b/viewer/src/localization/pl.json @@ -2006,5 +2006,6 @@ "Finish building": "Zakończ budowę", "Finish powering": "Zakończ produkcję energii", "Cancel bid edit": "Anuluj zmianę oferty", - "Power capacity: {count} cities": "Moc elektrowni: {count} miast" + "Power capacity: {count} cities": "Moc elektrowni: {count} miast", + "Undo my move": "Cofnij ruch" } diff --git a/viewer/src/localization/pt-BR.json b/viewer/src/localization/pt-BR.json index fdd20ca..0f3a4aa 100644 --- a/viewer/src/localization/pt-BR.json +++ b/viewer/src/localization/pt-BR.json @@ -2006,5 +2006,6 @@ "Finish building": "Concluir construção", "Finish powering": "Concluir geração", "Cancel bid edit": "Cancelar edição do lance", - "Power capacity: {count} cities": "Capacidade de energia: {count} cidades" + "Power capacity: {count} cities": "Capacidade de energia: {count} cidades", + "Undo my move": "Desfazer jogada" } diff --git a/viewer/src/localization/ro.json b/viewer/src/localization/ro.json index 1ebf760..9a537f2 100644 --- a/viewer/src/localization/ro.json +++ b/viewer/src/localization/ro.json @@ -2006,5 +2006,6 @@ "Finish building": "Încheie construcția", "Finish powering": "Încheie producția", "Cancel bid edit": "Anulează modificarea ofertei", - "Power capacity: {count} cities": "Capacitate de alimentare: {count} orașe" + "Power capacity: {count} cities": "Capacitate de alimentare: {count} orașe", + "Undo my move": "Anulează mutarea" } diff --git a/viewer/src/localization/ru.json b/viewer/src/localization/ru.json index 1d5eae7..affc8d8 100644 --- a/viewer/src/localization/ru.json +++ b/viewer/src/localization/ru.json @@ -2006,5 +2006,6 @@ "Finish building": "Завершить строительство", "Finish powering": "Завершить выработку", "Cancel bid edit": "Отменить изменение ставки", - "Power capacity: {count} cities": "Мощность: {count} городов" + "Power capacity: {count} cities": "Мощность: {count} городов", + "Undo my move": "Отменить ход" } diff --git a/viewer/src/localization/vi.json b/viewer/src/localization/vi.json index 7f5ee68..d358825 100644 --- a/viewer/src/localization/vi.json +++ b/viewer/src/localization/vi.json @@ -2006,5 +2006,6 @@ "Finish building": "Hoàn tất xây dựng", "Finish powering": "Hoàn tất phát điện", "Cancel bid edit": "Hủy sửa giá đấu", - "Power capacity: {count} cities": "Công suất cấp điện: {count} thành phố" + "Power capacity: {count} cities": "Công suất cấp điện: {count} thành phố", + "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 2f67675..6d4609c 100644 --- a/viewer/src/localization/zh-TW.json +++ b/viewer/src/localization/zh-TW.json @@ -2006,5 +2006,6 @@ "Finish building": "完成建設", "Finish powering": "完成發電", "Cancel bid edit": "取消修改出價", - "Power capacity: {count} cities": "供電容量:{count} 座城市" + "Power capacity: {count} cities": "供電容量:{count} 座城市", + "Undo my move": "撤回我的行動" } diff --git a/viewer/src/self-contained.ts b/viewer/src/self-contained.ts index 3b355f1..e2b13f8 100644 --- a/viewer/src/self-contained.ts +++ b/viewer/src/self-contained.ts @@ -1,6 +1,6 @@ import { cloneDeep } from 'lodash'; import { Move, Phase, setup, stripSecret } from 'powergrid-engine'; -import type { MapName, Variant } from 'powergrid-engine/src/gamestate'; +import type { GameState, MapName, Variant } from 'powergrid-engine/src/gamestate'; import type { PremoveCommand } from 'powergrid-engine/src/premoves'; import { move as wrapperMove, moveAI as wrapperAI } from 'powergrid-engine/wrapper'; import { installLocalChat } from './game-chat'; @@ -61,6 +61,19 @@ function launchSelfContained(selector = '#app') { if (player.id != playerIndex) player.isAI = true; } + // Mimic BGS's "Undo my move" in a game against bots: every committed move of the + // human records the state before it, and undo goes back to the latest of these, + // dropping the bots' replies. + const undoPoints: GameState[] = []; + const offerUndo = () => emitter.emit('undo:available', undoPoints.length > 0); + emitter.on('undo', () => { + const previous = undoPoints.pop(); + if (!previous) return; + gameState = previous; + emitter.emit('state', cloneDeep(strip ? stripSecret(gameState, playerIndex) : gameState)); + offerUndo(); + }); + emitter.on('move', async (moves: Move[] | PremoveCommand) => { setTimeout(async () => { console.log('moves received', moves); @@ -76,8 +89,10 @@ function launchSelfContained(selector = '#app') { return; } + undoPoints.push(gameState); gameState = newState; emitter.emit('state', cloneDeep(strip ? stripSecret(gameState, playerIndex) : gameState)); + offerUndo(); let delay = delayBase; const moveAIAux = () => { diff --git a/viewer/src/util/turn-buffer.ts b/viewer/src/util/turn-buffer.ts index e37f982..881034b 100644 --- a/viewer/src/util/turn-buffer.ts +++ b/viewer/src/util/turn-buffer.ts @@ -137,6 +137,32 @@ export function rebaseTurnBuffer( return remaining; } +/** + * Does an incoming COMMITTED state take back moves this player had already committed? + * + * That is what BGS's "Undo my move" does in a game against bots: it replays the game to + * the position before the player's last saved move, dropping the bots' replies, and + * sends that earlier state. Whatever the viewer prepared on the newer position (turn + * buffer, dialogs, a dialled bid) no longer applies. Another player reopening their + * powering only removes THEIR moves, and an ordinary update only appends, so neither + * counts. + */ +export function takesBackOwnMoves( + previousLog: LogItem[] | null, + committed: GameState, + player: number | undefined +): boolean { + if (!previousLog || player === undefined) { + return false; + } + + const ownMoves = (log: LogItem[]) => + log.filter((item): item is LogMove => item.type === 'move' && item.player === player); + const kept = ownMoves(committed.log); + + return ownMoves(previousLog).some((item, i) => !kept[i] || !isEqual(item.move, kept[i].move)); +} + /** * Replays the turn buffer on the last committed state, truncating it at the first * move the engine rejects (possible after a rebase), and returns the preview plus the diff --git a/viewer/tests/unit/undo-move.spec.ts b/viewer/tests/unit/undo-move.spec.ts new file mode 100644 index 0000000..ce696cd --- /dev/null +++ b/viewer/tests/unit/undo-move.spec.ts @@ -0,0 +1,149 @@ +import UndoButton from '@/components/buttons/UndoButton.vue'; +import Game from '@/components/Game.vue'; +import { takesBackOwnMoves } from '@/util/turn-buffer'; +import { mount } from '@vue/test-utils'; +import { expect } from 'chai'; +import type { GameState, LogItem } from 'powergrid-engine'; +import { MoveName } from 'powergrid-engine'; + +const options = (Game as any).options; +const canUndoMove = (context: any) => options.methods.canUndoMove.call(context); + +const move = (player: number, name: MoveName, data: unknown, time: number): LogItem => ({ + type: 'move', + player, + move: { name, data, time } as any, + simple: '', + pretty: '', +}); +const withLog = (log: LogItem[]) => ({ log } as GameState); + +describe('Undo my move', () => { + const start: LogItem[] = [{ type: 'event', event: 'Game Start!' }]; + const mine = move(0, MoveName.ChoosePowerPlant, 3, 1); + const bot = move(1, MoveName.Bid, 4, 2); + const mineAgain = move(0, MoveName.Bid, 5, 3); + + it('recognizes a committed state that takes back the player’s own moves', () => { + const before = [...start, mine, bot, mineAgain]; + expect(takesBackOwnMoves(before, withLog([...start, mine, bot]), 0)).to.equal(true); + expect(takesBackOwnMoves(before, withLog(start), 0)).to.equal(true); + expect(takesBackOwnMoves(before, withLog([...before, move(1, MoveName.Pass, true, 4)]), 0)).to.equal(false); + // Another player's revision only removes their own moves. + expect(takesBackOwnMoves(before, withLog([...start, mine, mineAgain]), 0)).to.equal(false); + expect(takesBackOwnMoves(before, withLog([...start, mine, bot]), 1)).to.equal(false); + expect(takesBackOwnMoves(null, withLog(start), 0)).to.equal(false); + expect(takesBackOwnMoves(before, withLog(start), undefined)).to.equal(false); + }); + + const offered = () => ({ + undoAvailable: true, + G: { players: [{}, {}] }, + player: 0, + paused: false, + interactionDisabled: false, + tutorialMove: undefined, + preferences: {}, + roundPlan: null, + pendingPlanId: '', + changingBid: false, + poweringSubmitting: false, + undoRequested: false, + recentLocalUndo: false, + canUndo: () => false, + }); + + it('is offered only while BGS allows it and the player can act on the live board', () => { + expect(canUndoMove(offered())).to.equal(true); + expect(canUndoMove({ ...offered(), undoAvailable: false }), 'hidden by default').to.equal(false); + expect(canUndoMove({ ...offered(), player: undefined }), 'spectators').to.equal(false); + expect(canUndoMove({ ...offered(), G: null }), 'no state yet').to.equal(false); + expect(canUndoMove({ ...offered(), paused: true }), 'replaying').to.equal(false); + expect(canUndoMove({ ...offered(), preferences: { analysis: true } }), 'analyses').to.equal(false); + expect(canUndoMove({ ...offered(), interactionDisabled: true })).to.equal(false); + expect(canUndoMove({ ...offered(), tutorialMove: () => undefined }), 'tutorials').to.equal(false); + expect(canUndoMove({ ...offered(), roundPlan: { entries: [] } }), 'round planning').to.equal(false); + expect(canUndoMove({ ...offered(), pendingPlanId: 'request' }), 'premoves on their way').to.equal(false); + expect(canUndoMove({ ...offered(), poweringSubmitting: true }), 'powering on its way').to.equal(false); + expect(canUndoMove({ ...offered(), undoRequested: true }), 'undo on its way').to.equal(false); + expect(canUndoMove({ ...offered(), changingBid: true }), 'bid edit in progress').to.equal(false); + expect(canUndoMove({ ...offered(), canUndo: () => true }), 'buffered moves come first').to.equal(false); + expect(canUndoMove({ ...offered(), recentLocalUndo: true }), 'just after the local Undo').to.equal(false); + }); + + it('asks BGS once per request', () => { + const emitted: unknown[][] = []; + const context: any = { ...offered(), emitter: { emit: (...args: unknown[]) => emitted.push(args) } }; + context.canUndoMove = () => canUndoMove(context); + options.methods.undoMove.call(context); + // A second click before BGS answers with the earlier state. + options.methods.undoMove.call(context); + clearTimeout(context.undoRequestTimer); + expect(emitted).to.deep.equal([['undo']]); + expect(context.undoRequested).to.equal(true); + }); + + it('drops drafts made on the newer position', () => { + const context: any = { + turnMoves: [{ name: MoveName.BuyResource }], + editingBid: 'auction', + confirmVisible: true, + discardVisible: true, + freeJumpVisible: true, + discardedPowerPlant: {}, + freeJumpCity: {}, + soleBuyerPlant: {}, + draftKey: 2, + roundPlan: null, + G: {}, + }; + options.methods.abandonLocalTurn.call(context); + expect(context).to.deep.include({ + turnMoves: [], + editingBid: null, + confirmVisible: false, + discardVisible: false, + freeJumpVisible: false, + discardedPowerPlant: null, + freeJumpCity: null, + soleBuyerPlant: null, + draftKey: 3, + G: null, + }); + const planning: any = { ...context, roundPlan: { entries: [] }, G: { plan: true } }; + options.methods.abandonLocalTurn.call(planning); + expect(planning.G).to.deep.equal({ plan: true }); + }); + + it('keeps a double click on the board’s Undo away from the saved move', () => { + let undone = 0; + const context: any = { changingBid: false, editingBid: null, undo: () => undone++ }; + options.methods.useUndoButton.call(context); + clearTimeout(context.recentLocalUndoTimer); + expect(undone).to.equal(1); + expect(context.recentLocalUndo).to.equal(true); + const editing: any = { changingBid: true, editingBid: 'auction', undo: () => undone++ }; + options.methods.useUndoButton.call(editing); + clearTimeout(editing.recentLocalUndoTimer); + expect(editing.editingBid).to.equal(null); + expect(undone).to.equal(1); + }); + + it('renders an accessible board control with the undo icon', async () => { + const wrapper = mount(UndoButton, { + propsData: { control: 'undo-move', text: 'Undo my move', enabled: true, highlightButton: true }, + }); + expect(wrapper.attributes('data-board-control')).to.equal('undo-move'); + expect(wrapper.attributes('aria-label')).to.equal('Undo my move'); + expect(wrapper.find('title').text()).to.equal('Undo my move'); + expect(wrapper.find('image').exists()).to.equal(true); + await wrapper.trigger('click'); + await wrapper.trigger('keydown.enter'); + expect(wrapper.emitted('click')).to.have.length(2); + await wrapper.setProps({ control: 'undo', text: 'Cancel bid edit', icon: 'cancel' }); + expect(wrapper.attributes('data-board-control')).to.equal('undo'); + expect(wrapper.find('image').exists()).to.equal(false); + expect(wrapper.find('path').exists()).to.equal(true); + wrapper.destroy(); + }); +});