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 <noreply@anthropic.com>
This commit is contained in:
parent
6555a17222
commit
e90041904b
28 changed files with 478 additions and 27 deletions
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
8
viewer/pnpm-lock.yaml
generated
8
viewer/pnpm-lock.yaml
generated
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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`);
|
||||
|
|
|
|||
120
viewer/scripts/undo-smoke.mjs
Normal file
120
viewer/scripts/undo-smoke.mjs
Normal file
|
|
@ -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');
|
||||
}
|
||||
|
|
@ -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"
|
||||
/>
|
||||
<!-- BGS's "Undo my move" (games against bots) takes this button's
|
||||
place once nothing is left to take back locally, so undo stays in
|
||||
one place and the authored layout needs no new space. -->
|
||||
<UndoButton
|
||||
v-if="canUndoMove()"
|
||||
key="undo-move"
|
||||
transform="translate(15, 56)"
|
||||
control="undo-move"
|
||||
text="Undo my move"
|
||||
:enabled="true"
|
||||
:highlightButton="true"
|
||||
@click="undoMove()"
|
||||
/>
|
||||
<UndoButton
|
||||
v-else
|
||||
key="undo"
|
||||
transform="translate(15, 56)"
|
||||
:enabled="changingBid || canUndo()"
|
||||
:highlightButton="changingBid || canUndo()"
|
||||
:icon="changingBid ? 'cancel' : 'undo'"
|
||||
:text="changingBid ? 'Cancel bid edit' : 'Undo last move'"
|
||||
@click="changingBid ? (editingBid = null) : undo()"
|
||||
@click="useUndoButton()"
|
||||
/>
|
||||
<BoardOption
|
||||
transform="translate(15, 97)"
|
||||
|
|
@ -890,6 +907,7 @@ import {
|
|||
matchesTurnBuffer,
|
||||
rebaseTurnBuffer,
|
||||
replayTurnBuffer as replayBuffer,
|
||||
takesBackOwnMoves,
|
||||
} from '../util/turn-buffer';
|
||||
import { UIData, Preferences } from '../types/ui-data';
|
||||
import { Card, House, Coal, Oil, Garbage, Uranium } from './pieces';
|
||||
|
|
@ -1118,6 +1136,10 @@ export default class Game extends Vue {
|
|||
@Prop()
|
||||
avatars!: string[];
|
||||
|
||||
/** BGS can take back this player's last saved move (protocol `undo:available`). */
|
||||
@Prop({ default: false })
|
||||
undoAvailable!: boolean;
|
||||
|
||||
@Prop()
|
||||
@ProvideReactive()
|
||||
preferences!: Preferences;
|
||||
|
|
@ -1514,6 +1536,14 @@ export default class Game extends Vue {
|
|||
this.replaceState(state);
|
||||
return;
|
||||
}
|
||||
if (state && state.newTurn !== false) {
|
||||
// BGS answers "Undo my move" with the earlier committed state.
|
||||
this.undoRequested = false;
|
||||
if (this.undoRequestTimer) clearTimeout(this.undoRequestTimer);
|
||||
if (takesBackOwnMoves(this.committedState ? this.committedState.log : null, state, this.player)) {
|
||||
this.abandonLocalTurn();
|
||||
}
|
||||
}
|
||||
if (
|
||||
state &&
|
||||
state.newTurn !== false &&
|
||||
|
|
@ -1761,6 +1791,81 @@ export default class Game extends Vue {
|
|||
this.activateFreePlants();
|
||||
}
|
||||
|
||||
/** The board's Undo button: cancels a bid edit, or takes back buffered moves. */
|
||||
useUndoButton() {
|
||||
// Either can leave nothing to undo locally, and "Undo my move" then takes the
|
||||
// button's place at once: the second click of a double click must not reach it.
|
||||
this.recentLocalUndo = true;
|
||||
if (this.recentLocalUndoTimer) clearTimeout(this.recentLocalUndoTimer);
|
||||
this.recentLocalUndoTimer = setTimeout(() => (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<typeof setTimeout> | undefined;
|
||||
// The board's Undo was just used, see `useUndoButton`.
|
||||
recentLocalUndo = false;
|
||||
private recentLocalUndoTimer: ReturnType<typeof setTimeout> | 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);
|
||||
|
|
|
|||
|
|
@ -30,10 +30,11 @@
|
|||
:powerPlant="chosenPowerPlant.powerPlant"
|
||||
/>
|
||||
<!-- Keyed per plant so every auction gets a fresh calculator: a reused
|
||||
instance would keep displaying the previous auction's bid floor. -->
|
||||
instance would keep displaying the previous auction's bid floor. The
|
||||
draft key also resets a bid dialled before the game was rewound. -->
|
||||
<Calculator
|
||||
v-if="canBid"
|
||||
:key="'calc' + chosenPowerPlant.powerPlant.number + (editingBid ? '-edit' : '')"
|
||||
:key="'calc' + chosenPowerPlant.powerPlant.number + (editingBid ? '-edit' : '') + '-' + draftKey"
|
||||
:transform="`translate(${actualMarketWidth}, 80)`"
|
||||
:minValue="minBid"
|
||||
:maxValue="maxBid"
|
||||
|
|
@ -97,6 +98,7 @@ export default class PowerPlantMarket extends Vue {
|
|||
@Prop() maxBid?: number;
|
||||
@Prop() initialBid?: number;
|
||||
@Prop() editingBid?: boolean;
|
||||
@Prop({ default: 0 }) draftKey!: number;
|
||||
|
||||
@Inject() preferences!: Preferences;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
<template>
|
||||
<g
|
||||
:class="['button', { enabled, highlightButton }]"
|
||||
data-board-control="undo"
|
||||
:data-board-control="control"
|
||||
role="button"
|
||||
:aria-label="text"
|
||||
:tabindex="enabled ? 0 : -1"
|
||||
|
|
@ -12,7 +12,7 @@
|
|||
>
|
||||
<rect width="80" height="26" fill="gainsboro" stroke="black" rx="2" />
|
||||
<image
|
||||
v-if="text === 'Undo last move'"
|
||||
v-if="icon === 'undo'"
|
||||
x="30"
|
||||
y="3"
|
||||
width="20"
|
||||
|
|
@ -39,5 +39,7 @@ export default class UndoButton extends Vue {
|
|||
@Prop({ default: 'Undo last move' }) text!: string;
|
||||
@Prop() enabled!: boolean;
|
||||
@Prop() highlightButton!: boolean;
|
||||
@Prop({ default: 'undo' }) control!: string;
|
||||
@Prop({ default: 'undo' }) icon!: 'undo' | 'cancel';
|
||||
}
|
||||
</script>
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2006,5 +2006,6 @@
|
|||
"Finish building": "Ολοκλήρωση κατασκευής",
|
||||
"Finish powering": "Ολοκλήρωση ηλεκτροδότησης",
|
||||
"Cancel bid edit": "Ακύρωση αλλαγής προσφοράς",
|
||||
"Power capacity: {count} cities": "Δυναμικότητα τροφοδοσίας: {count} πόλεις"
|
||||
"Power capacity: {count} cities": "Δυναμικότητα τροφοδοσίας: {count} πόλεις",
|
||||
"Undo my move": "Αναίρεση κίνησης"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2006,5 +2006,6 @@
|
|||
"Finish building": "پایان ساختوساز",
|
||||
"Finish powering": "پایان تولید برق",
|
||||
"Cancel bid edit": "لغو ویرایش پیشنهاد",
|
||||
"Power capacity: {count} cities": "ظرفیت تأمین برق: {count} شهر"
|
||||
"Power capacity: {count} cities": "ظرفیت تأمین برق: {count} شهر",
|
||||
"Undo my move": "بازگرداندن حرکت"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2006,5 +2006,6 @@
|
|||
"Finish building": "निर्माण पूरा करें",
|
||||
"Finish powering": "बिजली उत्पादन पूरा करें",
|
||||
"Cancel bid edit": "बोली का बदलाव रद्द करें",
|
||||
"Power capacity: {count} cities": "बिजली क्षमता: {count} शहर"
|
||||
"Power capacity: {count} cities": "बिजली क्षमता: {count} शहर",
|
||||
"Undo my move": "अपनी चाल वापस लें"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2006,5 +2006,6 @@
|
|||
"Finish building": "건설 완료",
|
||||
"Finish powering": "발전 완료",
|
||||
"Cancel bid edit": "입찰 수정 취소",
|
||||
"Power capacity: {count} cities": "전력 공급 용량: 도시 {count}개"
|
||||
"Power capacity: {count} cities": "전력 공급 용량: 도시 {count}개",
|
||||
"Undo my move": "내 수 되돌리기"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2006,5 +2006,6 @@
|
|||
"Finish building": "Завершить строительство",
|
||||
"Finish powering": "Завершить выработку",
|
||||
"Cancel bid edit": "Отменить изменение ставки",
|
||||
"Power capacity: {count} cities": "Мощность: {count} городов"
|
||||
"Power capacity: {count} cities": "Мощность: {count} городов",
|
||||
"Undo my move": "Отменить ход"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2006,5 +2006,6 @@
|
|||
"Finish building": "完成建設",
|
||||
"Finish powering": "完成發電",
|
||||
"Cancel bid edit": "取消修改出價",
|
||||
"Power capacity: {count} cities": "供電容量:{count} 座城市"
|
||||
"Power capacity: {count} cities": "供電容量:{count} 座城市",
|
||||
"Undo my move": "撤回我的行動"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 = () => {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
149
viewer/tests/unit/undo-move.spec.ts
Normal file
149
viewer/tests/unit/undo-move.spec.ts
Normal file
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue