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 <noreply@anthropic.com>
This commit is contained in:
coyotte508 2026-10-08 11:32:52 +02:00
commit f806bdef1f
28 changed files with 385 additions and 30 deletions

10
pnpm-lock.yaml generated
View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -90,7 +90,15 @@
:enabled="canPass()"
@click="pass()"
/>
<!-- BGS's "Undo my move" stands in for the in-turn undo when that has nothing to undo. -->
<UndoMoveButton
v-if="canUndoMove()"
data-thumbnail-omit
transform="translate(1105, 36)"
@click="requestUndo()"
/>
<UndoButton
v-else
data-thumbnail-omit
transform="translate(1105, 36)"
:enabled="canUndo()"
@ -325,7 +333,7 @@
rx="2px"
/>
<Calculator
:key="changingBid ? editingBid : 'new-bid'"
:key="`${changingBid ? editingBid : 'new-bid'}:${draftsVersion}`"
:initialValue="changingBid ? submittedBid : undefined"
data-tutorial="bid"
transform="translate(140, 430)"
@ -738,7 +746,7 @@ import { groupBy, isEqual } from 'lodash';
import { ContainerState, DropZoneType, Piece, PieceType, ShipType, UIData, Preferences } from '../types/ui-data';
import { ContainerColor, ShipPosition } from 'container-engine/src/gamestate';
import { Container, Factory, Warehouse, Ship, LoanCard, Piece as PieceComponent } from './pieces';
import { Button, PassButton, UndoButton, LogButton, SoundButton, HelpButton } from './buttons';
import { Button, PassButton, UndoButton, UndoMoveButton, LogButton, SoundButton, HelpButton } from './buttons';
import PlayerBoard from './PlayerBoard.vue';
import PointCard from './PointCard.vue';
import DropZone from './DropZone.vue';
@ -761,6 +769,7 @@ import { GameEventName, LogMove } from 'container-engine/src/log';
Ship,
PassButton,
UndoButton,
UndoMoveButton,
LogButton,
SoundButton,
ColorBlindButton,
@ -787,6 +796,10 @@ export default class Game extends Vue {
@Prop({ default: false })
interactionDisabled!: boolean;
// BGS lets the only human of a game against bots take back their last saved move.
@Prop({ default: false })
undoAvailable!: boolean;
@Prop()
@ProvideReactive()
preferences!: Preferences;
@ -848,6 +861,11 @@ export default class Game extends Vue {
@Watch('state', { immediate: true })
onStateChanged(state: GameState) {
if (state && state.newTurn !== false) {
if (this.committedState && state.log.length < this.committedState.log.length) {
// Moves were taken back (BGS undo or replay): choices drafted in the later
// position no longer apply.
this.resetDrafts();
}
// Committed state: the previous turn is final, clear the turn buffer.
// Tentative states (newTurn === false) are only ever our own turn in
// progress, echoed back by the server — keep the buffer for those.
@ -1361,6 +1379,46 @@ export default class Game extends Vue {
// Empty buffer: nothing to send — nothing was ever persisted for this turn
}
/**
* BGS's "Undo my move" (games against bots): unlike `undo`, it takes back the last
* *saved* move, and the AI replies to it. BGS then sends the earlier state.
* A method, like the other `can*` checks: host preferences such as `analysis` are not
* reactive, so a cached computed would miss them.
*/
canUndoMove() {
return (
this.undoAvailable &&
!this.tutorialMove &&
!this.interactionDisabled &&
!this.preferences.analysis &&
this.player != null &&
!!this.G?.players[this.player] &&
!ended(this.G) &&
// Unsaved moves of the current turn are taken back with `undo` first.
this.turnMoves.length === 0
);
}
requestUndo() {
if (!this.canUndoMove()) return;
this.resetDrafts();
this.emitter.emit('undo');
}
// Bumped to remount the bid calculator, whose typed amount is local.
draftsVersion = 0;
/** Discard unsent choices: selection, bid drafts and pending confirmations. */
resetDrafts() {
this.ui.selected = null;
this.editingBid = null;
this.confirmBidVisible = false;
this.confirmBidRevision = null;
this.totalBid = 0;
this.confirmSailVisible = false;
this.draftsVersion++;
}
loan(event) {
const loan = event as LoanCard;
if (loan.owner == -1) {

View file

@ -0,0 +1,23 @@
<template>
<g
class="button enabled"
data-board-control="undo-move"
role="button"
aria-label="Undo my move"
tabindex="0"
@click="$emit('click')"
@keydown.enter.prevent="$emit('click')"
@keydown.space.prevent="$emit('click')"
>
<rect width="80" height="26" fill="gainsboro" stroke="black" rx="2" />
<image x="30" y="3" width="20" height="20" href="../../icons/undo.svg" aria-hidden="true" />
<title>Undo my move</title>
</g>
</template>
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';
/** Asks BGS to take back the player's last saved move (offered in games against bots). */
@Component
export default class UndoMoveButton extends Vue {}
</script>

View file

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

View file

@ -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<GameState, Move[]>({
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);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -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<ReturnType<typeof setTimeout>>();
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;
}

View file

@ -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', () => {

View file

@ -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<string, unknown> = {}) {
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<string, unknown>][]) {
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();
});
});