Allow private turn undo without duplicate history or clock increments

This commit is contained in:
coyotte508 2026-10-23 00:04:22 +02:00
commit c69ec8252e
34 changed files with 740 additions and 46 deletions

View file

@ -1,12 +1,19 @@
# Acquire private beta — 22 October 2026
# Acquire private beta — 23 October 2026
Private BGS registration: `acquire`, version `1`. Engine `0.0.1`, viewer `0.0.10`.
Private BGS registration: `acquire`, version `1`. Engine `0.0.2`, viewer `0.0.11`.
Source: <https://github.com/boardgamers/mergers-game>. Keep `public: false`.
## Validation
- `pnpm check`: formatting, lint, TypeScript/Svelte checks, 198 engine tests,
56 viewer/tutorial tests, and the production build. Two pre-existing lint warnings
- Undo keeps unfinished choices in a private server-validated draft. Repeated placement/founding
revisions never persist undo entries or award time. One increment is earned per completed turn;
other players' merger disposal decisions each earn their own increment. Drawing tiles, revealing
merger bonuses, ending the game or handing off a decision commits the draft. Checks cover stale
requests, hidden-information masking, replay, bank mode, four-hands, teams and dropped players.
Desktop/phone checks exercise repeated undo, saved-state refreshes, final history and clock totals.
- `pnpm check`: formatting, lint, TypeScript/Svelte checks, 207 engine tests,
60 viewer/tutorial tests, and the production build. Two pre-existing lint warnings
remain (an unused test import and Svelte's `bind:this` assignment).
- Protocol diagnostics: all eight required engine methods; full core/chat/replay
viewer coverage, preferences, avatars and theme handlers. Protocol `0.10.0` is the

View file

@ -117,7 +117,7 @@ BASE=https://admin.boardgamers.space/api/admin/gameinfo/acquire
# Engine: the raw npm-pack tarball; this sets engine.package on version 1.
curl -X POST "$BASE/1/engine" -H "$AUTH" -H "Content-Type: application/octet-stream" \
--data-binary @packages/engine/acquire-engine-0.0.1.tgz
--data-binary @packages/engine/acquire-engine-0.0.2.tgz
# Viewer files: one POST each with a shared bundle id; each returns the hosted URL.
BUNDLE=acquire-$(git rev-parse --short HEAD)
@ -140,6 +140,18 @@ version integer: ongoing games pick up the new engine within about a minute. A n
integer only affects new games. Upload the engine and viewer together whenever the move or
state format changes, since they are coupled.
From engine 0.0.2 / viewer 0.0.11, live moves use a private turn draft (`type: "turn"`,
`from: <saved log length>`, `moves: [...]`). The engine validates the complete sequence
from the saved position. It returns `toSave: undefined` while choices remain reversible,
and sends the acting player a stripped `preview` inside the log response. The viewer
undoes by dropping one cached action/view; it never rewrites published log entries.
The complete sequence commits when a decision passes to another player, tiles are drawn,
bonuses reveal information or the game ends. Refreshing the page discards unfinished choices.
`timeIncrements` counts completed turns and other players' merger disposal decisions;
revising a private draft earns no time. Publish the engine first: its capability flag
allows the viewer to keep using atomic moves with older engines. Older viewers, tutorials
and analysis retain the original atomic protocol.
## Before making a version public
BGS's release checklist, and where this repo stands:

View file

@ -1,6 +1,6 @@
{
"name": "acquire-engine",
"version": "0.0.1",
"version": "0.0.2",
"description": "Acquire rules engine for boardgamers.space",
"license": "AGPL-3.0-only",
"files": [

View file

@ -124,7 +124,7 @@ test("§13 each viewer's state hides exactly the private fields and passes every
});
const masked = withoutSecrets(view, player) as Record<string, unknown>;
const expected = withoutSecrets(state, player) as Record<string, unknown>;
const expected = withoutSecrets({ ...state, supportsTurnDrafts: true }, player) as Record<string, unknown>;
assert.deepEqual(masked, expected, "§13 the board, chains, bank, merger and log stay public");
}
assert.deepEqual(state, before, "stripSecret never changes the real state");

View file

@ -0,0 +1,218 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import * as engine from "../wrapper.js";
import { legalMoves } from "./legal.js";
import { MAX_TURN_MOVES } from "./turn-draft.js";
import { chainAt, checkInvariants, scenario, t } from "./test/helpers.js";
import type { GameState, Move, TurnRequest } from "./types.js";
const place: Move = { type: "place", tile: "2A" };
const found: Move = { type: "found", chain: "tower" };
const buy: Move = { type: "buy", shares: { tower: 2 } };
const baseGame = () => scenario({ board: { "1A": "loose" }, hands: [["2A", "12I"], ["10G"], ["8E"]] });
const request = (state: GameState, moves: Move[]): TurnRequest => ({ type: "turn", from: state.log.length, moves });
const draft = (state: GameState, moves: Move[], player = engine.currentPlayer(state)!) =>
engine.move(state, request(state, moves), player);
test("undo revisions never save history or award time, and the accepted turn is saved once", () => {
const base = baseGame();
const original = structuredClone(base);
for (let i = 0; i < 30; i++) {
const placed = draft(base, [place]);
assert.equal(placed.phase, "found");
assert.equal(engine.toSave(placed), undefined);
const founded = draft(base, [place, { type: "found", chain: i % 2 ? "tower" : "luxor" }]);
assert.equal(engine.toSave(founded), undefined);
assert.deepEqual(engine.timeIncrements(founded), [0, 0, 0]);
assert.deepEqual(base, original);
}
const saved = draft(base, [place, found, buy]);
assert.equal(engine.toSave(saved), saved);
assert.equal(saved.tentative, undefined);
assert.deepEqual(engine.timeIncrements(saved), [1, 0, 0]);
assert.deepEqual(saved.log.slice(0, base.log.length), base.log);
assert.deepEqual(
saved.log.filter((e) => e.type === "move").map((e) => e.move),
[place, found, buy]
);
const direct = structuredClone(base);
for (const move of [place, found, buy]) {
engine.move(direct, move, 0);
}
assert.deepEqual(saved, direct);
checkInvariants(saved);
});
test("private previews are sent only to their owner and strip all hidden information", () => {
const base = baseGame();
const result = draft(base, [place, found]);
const preview = engine.logSlice(result, { start: base.log.length, player: 0 }).preview!;
assert.equal(preview.phase, "buy");
assert.equal(preview.seed, "");
assert.ok(preview.pool.every((tile) => tile === -1));
assert.equal(preview.seats[1]!.cash, -1);
assert.equal(preview.seats[1]!.shares.luxor, -1);
assert.deepEqual(preview.seats[1]!.hand, [-1]);
assert.equal(engine.logSlice(result, { player: 1 }).preview, undefined);
assert.equal(engine.logSlice(result).preview, undefined);
assert.equal(engine.stripSecret(base, 0).supportsTurnDrafts, true);
});
test("stale, malformed, wrong-player, and overlong requests cannot mutate the saved state", () => {
const base = baseGame();
const original = structuredClone(base);
for (const raw of [
{ ...request(base, [place]), from: base.log.length - 1 },
request(base, []),
request(base, Array(MAX_TURN_MOVES + 1).fill(place)),
{ type: "turn", from: base.log.length, moves: null },
request(base, [place, { type: "buy", shares: {} }]),
request(base, [place, found, buy, { type: "place", tile: "10G" }]),
]) {
assert.throws(() => engine.move(base, raw, 0));
}
assert.throws(() => draft(base, [place], 1), /not your turn/);
const preview = draft(base, [place]);
assert.throws(() => draft(preview, [found]), /game changed/);
assert.deepEqual(base, original);
});
test("drawing tiles closes undo, including placements that automatically skip buying", () => {
const base = scenario({ hands: [["1A"], ["12I"], ["10G"]] });
const result = draft(base, [{ type: "place", tile: "1A" }]);
assert.ok(result.log.some((e) => e.type === "drew"));
assert.equal(engine.toSave(result), result);
assert.deepEqual(engine.timeIncrements(result), [1, 0, 0]);
});
const merger = () =>
scenario({
board: { ...chainAt("tower", ["1A", "2A"]), ...chainAt("luxor", ["4A", "5A"]) },
hands: [["3A"], ["12I"], ["10G"]],
shares: [{ luxor: 1 }, { luxor: 2 }, {}],
});
test("merger placement can be revised until bonuses are revealed, even when the same player still acts", () => {
const base = merger();
const moves: Move[] = [
{ type: "place", tile: "3A" },
{ type: "survivor", chain: "tower" },
];
const placed = draft(base, [moves[0]!]);
assert.equal(engine.toSave(placed), undefined);
assert.equal(placed.phase, "survivor");
const revealed = draft(base, moves);
assert.equal(engine.toSave(revealed), revealed);
assert.equal(engine.currentPlayer(revealed), 0);
assert.ok(revealed.log.some((e) => e.type === "bonuses"));
assert.throws(() => draft(base, [...moves, { type: "dispose", sell: 1, trade: 0 }]), /committed/);
assert.deepEqual(engine.timeIncrements(revealed), [0, 0, 0]);
const handedOff = draft(revealed, [{ type: "dispose", sell: 1, trade: 0 }]);
assert.equal(engine.toSave(handedOff), handedOff);
assert.equal(engine.currentPlayer(handedOff), 1);
assert.deepEqual(engine.timeIncrements(handedOff), [0, 0, 0]);
const returned = draft(handedOff, [{ type: "dispose", sell: 2, trade: 0 }]);
assert.equal(engine.toSave(returned), returned);
assert.equal(engine.currentPlayer(returned), 0);
assert.deepEqual(engine.timeIncrements(returned), [0, 1, 0]);
const ended = draft(returned, [{ type: "buy", shares: {} }]);
assert.deepEqual(engine.timeIncrements(ended), [1, 1, 0]);
});
test("four-hands credits real players, not seats or individual choices", () => {
const base = scenario({
options: { twoPlayerMode: "fourHands" },
activeSeat: 2,
board: { "1A": "loose" },
hands: [["12I"], ["10G"], ["2A"], ["8E"]],
});
const saved = draft(base, [place, found, buy]);
const expected = [0, 0];
expected[base.seatOwner[2]!] = 1;
assert.deepEqual(engine.timeIncrements(saved), expected);
});
test("end announcement can be undone; final scoring credits the completed turn only once", () => {
const base = scenario({
board: chainAt(
"tower",
Array.from({ length: 11 }, (_, i) => `${i + 1}A`)
),
hands: [["12I"], ["10G"], ["8E"]],
});
const moves: Move[] = [{ type: "announce" }, { type: "place", tile: "12I" }, { type: "buy", shares: {} }];
assert.equal(engine.toSave(draft(base, [moves[0]!])), undefined);
const ended = draft(base, moves);
assert.equal(ended.ended, true);
assert.equal(engine.toSave(ended), ended);
assert.deepEqual(engine.timeIncrements(ended), [1, 0, 0]);
});
test("committed drafts remain replayable, with monotonic increments and no transient state across a full game", () => {
let state = engine.init(4, [], { autoEnd: true, endSize: "31" }, "undo-replay");
let preview = state;
let buffer: Move[] = [];
let increments = engine.timeIncrements(state);
let commits = 0;
for (let step = 0; !state.ended && step < 1200; step++) {
const legal = legalMoves(preview).filter((m) => m.type !== "announce");
buffer.push(legal[(step * 7919) % legal.length]!);
preview = draft(state, buffer);
if (engine.toSave(preview)) {
const next = engine.timeIncrements(preview);
assert.ok(next.every((n, i) => n >= increments[i]!));
increments = next;
state = preview;
buffer = [];
commits++;
}
}
assert.equal(state.ended, true);
assert.ok(commits > 10);
assert.equal(state.tentative, undefined);
assert.deepEqual(engine.replay(state), state);
assert.ok(state.board[t("1A")] !== undefined);
});
test("bank, four-hands, teams and dropped players preserve private boundaries and monotonic clock totals", () => {
for (const [players, options] of [
[2, {}],
[2, { twoPlayerMode: "fourHands" }],
[4, { teamPlay: true }],
[6, { publicHoldings: true }],
] as const) {
let state = engine.init(
players,
[],
{ ...options, autoEnd: true, endSize: "31" },
`draft-${players}-${JSON.stringify(options)}`
);
let preview = state;
let buffer: Move[] = [];
let increments = engine.timeIncrements(state);
let dropped = false;
for (let step = 0; !state.ended && step < 1500; step++) {
if (players > 2 && step >= 35 && !buffer.length && !dropped) {
state = engine.dropPlayer(state, players - 1);
preview = state;
dropped = true;
} else {
const legal = legalMoves(preview).filter((move) => move.type !== "announce");
buffer.push(legal[(step * 7919) % legal.length]!);
preview = draft(state, buffer);
if (!engine.toSave(preview)) {
continue;
}
state = preview;
buffer = [];
}
const next = engine.timeIncrements(state);
assert.ok(next.every((n, i) => n >= increments[i]!));
increments = next;
assert.equal(state.tentative, undefined);
checkInvariants(state);
}
assert.equal(state.ended, true);
assert.deepEqual(engine.replay(state), state);
}
});

View file

@ -0,0 +1,85 @@
import { applyMove, currentSeat } from "./moves.js";
import type { GameState, TurnRequest } from "./types.js";
export const MAX_TURN_MOVES = 16;
/** A private draft ends before any new hidden information or another decision is exposed. */
export function draftCanContinue(before: GameState, after: GameState, player: number): boolean {
const next = currentSeat(after);
return (
!after.ended &&
after.turn === before.turn &&
next !== undefined &&
after.seatOwner[next] === player &&
!after.log
.slice(before.log.length)
.some(
(entry) =>
entry.type === "bonuses" ||
entry.type === "bankTile" ||
entry.type === "drew" ||
(entry.type === "move" && after.seatOwner[entry.seat] !== player)
)
);
}
export function applyTurnRequest(data: GameState, raw: TurnRequest, player: number): GameState {
if (raw.from !== data.log.length || data.tentative) {
throw new Error("The game changed. Start again from the current position.");
}
if (!Array.isArray(raw.moves) || raw.moves.length === 0 || raw.moves.length > MAX_TURN_MOVES) {
throw new Error("Invalid turn draft");
}
// Validate the entire request on a copy, including its commit boundary.
const result = structuredClone(data);
let tentative = false;
for (let i = 0; i < raw.moves.length; i++) {
const seat = currentSeat(result);
if (seat === undefined || result.seatOwner[seat] !== player) {
throw new Error("It is not your turn");
}
const before = structuredClone(result);
applyMove(result, raw.moves[i], seat);
tentative = draftCanContinue(before, result, player);
if (!tentative && i < raw.moves.length - 1) {
throw new Error("The turn draft continues past a committed decision");
}
}
if (tentative) {
result.tentative = { player, from: raw.from };
}
return result;
}
/** One time increment per completed turn, plus opponents' merger disposal decisions. */
export function earnedTimeIncrements(state: GameState): number[] {
const counts = Array<number>(state.players).fill(0);
let owner: number | undefined;
let acted = false;
const finish = () => {
if (acted && owner !== undefined) {
counts[owner]!++;
}
acted = false;
};
for (const entry of state.log) {
if (entry.type === "turn") {
finish();
owner = state.seatOwner[entry.seat];
} else if (entry.type === "gameEnd") {
finish();
} else if (entry.type === "move" && !entry.auto) {
const player = state.seatOwner[entry.seat]!;
if (player === owner) {
acted = true;
} else if (entry.move.type === "dispose") {
counts[player]!++;
}
}
}
return counts;
}
export function isTurnRequest(raw: unknown): raw is TurnRequest {
return typeof raw === "object" && raw !== null && "type" in raw && raw.type === "turn";
}

View file

@ -27,6 +27,13 @@ export type Move =
| { type: "dispose"; sell: number; trade: number }
| { type: "buy"; shares: Partial<Shares> };
/** The complete private move sequence since the last saved position. */
export interface TurnRequest {
type: "turn";
from: number;
moves: Move[];
}
export interface MergerState {
/** The merging tile; it sits on the board as a loose tile until the board update (§7.3). */
tile: Tile;
@ -72,6 +79,10 @@ export type LogEntry =
| { type: "result"; cash: number[]; ranks: number[] };
export interface GameState {
/** Transient response only; toSave never persists this private draft. */
tentative?: { player: number; from: number };
/** Viewer capability flag, added only by the BGS wrapper. */
supportsTurnDrafts?: true;
seed: string;
rngCounter: number;
options: GameOptions;

View file

@ -1,3 +1,4 @@
import { applyTurnRequest, earnedTimeIncrements, isTurnRequest } from "./src/turn-draft.js";
import { applyMove, currentSeat, dropPlayerSeats } from "./src/moves.js";
import { replayGame } from "./src/replay.js";
import { playerRankings, playerScores } from "./src/scoring.js";
@ -23,6 +24,10 @@ export function init(
}
export function move(data: GameState, mv: unknown, player: number): GameState {
if (isTurnRequest(mv)) {
return applyTurnRequest(data, mv, player);
}
// Bare moves retain the existing protocol for older viewers and analyses.
const seat = currentSeat(data);
if (seat === undefined || data.seatOwner[seat] !== player) {
throw new Error("It is not your turn");
@ -53,7 +58,7 @@ export function currentPlayer(data: GameState): number | undefined {
}
export function stripSecret(data: GameState, player?: number): GameState {
return viewFor(data, player);
return { ...viewFor(data, player), supportsTurnDrafts: true };
}
export function logLength(data: GameState): number {
@ -68,11 +73,20 @@ export interface LogSliceOptions {
// Both endpoints are inclusive. The log is public (rules.md §13), so every viewer gets the same
// slice. Each entry gets a `simple` line for BGS's last-move display.
export function logSlice(data: GameState, options?: LogSliceOptions): { log: (LogEntry & { simple: string })[] } {
export function logSlice(
data: GameState,
options?: LogSliceOptions
): {
log: (LogEntry & { simple: string })[];
preview?: GameState;
} {
const start = Math.max(0, options?.start ?? 0);
const end = options?.end ?? data.log.length - 1;
return {
log: data.log.slice(start, end + 1).map((entry, i) => ({ ...entry, simple: simpleLineAt(data, start + i) })),
...(data.tentative && data.tentative.player === options?.player
? { preview: stripSecret(data, options.player) }
: {}),
};
}
@ -91,3 +105,10 @@ export function round(data: GameState): number {
export function replay(data: GameState, options?: { to?: number }): GameState {
return replayGame(data, options?.to);
}
/** Private previews do not save history, send notifications or award clock increments. */
export function toSave(data: GameState): GameState | undefined {
return data.tentative ? undefined : data;
}
export const timeIncrements = earnedTimeIncrements;

View file

@ -1,6 +1,6 @@
{
"name": "acquire-viewer",
"version": "0.0.10",
"version": "0.0.11",
"private": true,
"description": "Browser viewer for Acquire on boardgamers.space",
"license": "AGPL-3.0-only",

View file

@ -256,8 +256,22 @@ if (params.has("tutorial")) {
sendPreferences();
emitter.on("move", (move) => {
if (viewAs !== undefined) {
engine.move(state, structuredClone(move), viewAs);
sync();
try {
const result = engine.move(structuredClone(state), structuredClone(move), viewAs);
const saved = engine.toSave(result);
if (saved) {
state = saved;
sync();
} else {
emitter.emit("gamelog", {
start: state.log.length,
data: engine.logSlice(result, { start: state.log.length, player: viewAs }),
});
}
emitter.emit("move:result", { move, ok: true });
} catch (error) {
emitter.emit("move:result", { move, ok: false, error: String(error) });
}
}
});
sync();

View file

@ -64,6 +64,20 @@
{#if moves.length > 0 && !store.sending}
<section class="panel" aria-label={t("panel.label")}>
{#if store.canUndo}
<button type="button" class="actionable undo" onclick={() => store.undo()}>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"><path d="M9 4 3 10l6 6M3 10h11a7 7 0 0 1 0 14" transform="translate(0 -2)" /></svg
>
{t("turn.undo")}
</button>
{/if}
{#if legal("announce")}
<div class="announce">
{#if confirmAnnounce}
@ -268,6 +282,12 @@
{/if}
<style>
.panel .undo {
display: flex;
align-items: center;
gap: 6px;
margin-inline-start: auto;
}
.panel {
background: var(--panel);
padding: 10px 12px 12px;

View file

@ -15,7 +15,8 @@ export const da: Catalog = {
"status.replayNote": "Du ser en tidligere stilling. Brikker på hånden vises ikke.",
"panel.label": "Din beslutning",
"panel.sending": "Sender…",
"announce.ask": "Afslut spillet efter denne tur? Det kan ikke fortrydes.",
"turn.undo": "Fortryd",
"announce.ask": "Afslut spillet efter denne tur?",
"announce.confirm": "Meld afslutning",
"announce.cancel": "Spil videre",
"announce.open": "Meld afslutning…",

View file

@ -15,7 +15,8 @@ export const de: Catalog = {
"status.replayNote": "Du siehst eine frühere Stellung. Plättchen auf der Hand werden nicht gezeigt.",
"panel.label": "Deine Entscheidung",
"panel.sending": "Wird gesendet…",
"announce.ask": "Das Spiel nach diesem Zug beenden? Das kann nicht rückgängig gemacht werden.",
"turn.undo": "Rückgängig",
"announce.ask": "Das Spiel nach diesem Zug beenden?",
"announce.confirm": "Spielende ankündigen",
"announce.cancel": "Weiterspielen",
"announce.open": "Spielende ankündigen…",

View file

@ -15,7 +15,8 @@ export const el: Catalog = {
"status.replayNote": "Βλέπεις μια παλαιότερη θέση. Τα πλακίδια στο χέρι δεν εμφανίζονται.",
"panel.label": "Η απόφασή σου",
"panel.sending": "Αποστολή…",
"announce.ask": "Να τελειώσει το παιχνίδι μετά από αυτόν τον γύρο; Δεν αναιρείται.",
"turn.undo": "Αναίρεση",
"announce.ask": "Να τελειώσει το παιχνίδι μετά από αυτόν τον γύρο;",
"announce.confirm": "Ανακοίνωση τέλους",
"announce.cancel": "Συνέχεια παιχνιδιού",
"announce.open": "Ανακοίνωση τέλους…",

View file

@ -20,7 +20,8 @@ export const en = {
// Decision panel
"panel.label": "Your decision",
"panel.sending": "Sending…",
"announce.ask": "End the game after this turn? This cannot be undone.",
"turn.undo": "Undo",
"announce.ask": "End the game after this turn?",
"announce.confirm": "Announce the end",
"announce.cancel": "Keep playing",
"announce.open": "Announce the end…",

View file

@ -15,7 +15,8 @@ export const fa: Catalog = {
"status.replayNote": "شما وضعیت قبلی بازی را می‌بینید. کاشی‌های دست نشان داده نمی‌شوند.",
"panel.label": "تصمیم شما",
"panel.sending": "در حال ارسال…",
"announce.ask": "بازی بعد از این نوبت تمام شود؟ این کار برگشت‌پذیر نیست.",
"turn.undo": "واگرد",
"announce.ask": "بازی بعد از این نوبت تمام شود؟",
"announce.confirm": "اعلام پایان",
"announce.cancel": "ادامه‌ی بازی",
"announce.open": "اعلام پایان…",

View file

@ -15,7 +15,8 @@ export const fr: Catalog = {
"status.replayNote": "Vous regardez une position antérieure. Les tuiles en main ne sont pas affichées.",
"panel.label": "Votre décision",
"panel.sending": "Envoi…",
"announce.ask": "Terminer la partie après ce tour ? Ce choix est définitif.",
"turn.undo": "Annuler",
"announce.ask": "Terminer la partie après ce tour ?",
"announce.confirm": "Annoncer la fin",
"announce.cancel": "Continuer à jouer",
"announce.open": "Annoncer la fin…",

View file

@ -15,7 +15,8 @@ export const hi: Catalog = {
"status.replayNote": "आप पहले की स्थिति देख रहे हैं। हाथ की टाइलें नहीं दिखाई जातीं।",
"panel.label": "आपका निर्णय",
"panel.sending": "भेजा जा रहा है…",
"announce.ask": "इस बारी के बाद खेल समाप्त करें? इसे वापस नहीं लिया जा सकता।",
"turn.undo": "पूर्ववत करें",
"announce.ask": "इस बारी के बाद खेल समाप्त करें?",
"announce.confirm": "अंत की घोषणा करें",
"announce.cancel": "खेलना जारी रखें",
"announce.open": "अंत की घोषणा करें…",

View file

@ -15,7 +15,8 @@ export const it: Catalog = {
"status.replayNote": "Stai guardando una posizione precedente. Le tessere in mano non sono mostrate.",
"panel.label": "La tua decisione",
"panel.sending": "Invio…",
"announce.ask": "Terminare la partita dopo questo turno? Non si può annullare.",
"turn.undo": "Annulla",
"announce.ask": "Terminare la partita dopo questo turno?",
"announce.confirm": "Annuncia la fine",
"announce.cancel": "Continua a giocare",
"announce.open": "Annuncia la fine…",

View file

@ -15,7 +15,8 @@ export const ko: Catalog = {
"status.replayNote": "이전 상황을 보고 있습니다. 손에 든 타일은 표시되지 않습니다.",
"panel.label": "내 결정",
"panel.sending": "보내는 중…",
"announce.ask": "이번 턴이 끝나면 게임을 끝낼까요? 되돌릴 수 없습니다.",
"turn.undo": "되돌리기",
"announce.ask": "이번 턴이 끝나면 게임을 끝낼까요?",
"announce.confirm": "종료 선언",
"announce.cancel": "계속 플레이",
"announce.open": "종료 선언…",

View file

@ -15,7 +15,8 @@ export const nl: Catalog = {
"status.replayNote": "Je bekijkt een eerdere stand. Tegels in de hand worden niet getoond.",
"panel.label": "Jouw beslissing",
"panel.sending": "Versturen…",
"announce.ask": "Het spel na deze beurt beëindigen? Dit kan niet ongedaan worden gemaakt.",
"turn.undo": "Ongedaan maken",
"announce.ask": "Het spel na deze beurt beëindigen?",
"announce.confirm": "Einde aankondigen",
"announce.cancel": "Verder spelen",
"announce.open": "Einde aankondigen…",

View file

@ -15,7 +15,8 @@ export const pl: Catalog = {
"status.replayNote": "Oglądasz wcześniejszą pozycję. Płytki na ręce nie są pokazywane.",
"panel.label": "Twoja decyzja",
"panel.sending": "Wysyłanie…",
"announce.ask": "Zakończyć grę po tej turze? Tego nie można cofnąć.",
"turn.undo": "Cofnij",
"announce.ask": "Zakończyć grę po tej turze?",
"announce.confirm": "Ogłoś koniec gry",
"announce.cancel": "Graj dalej",
"announce.open": "Ogłoś koniec gry…",

View file

@ -15,7 +15,8 @@ export const ptBR: Catalog = {
"status.replayNote": "Você está vendo uma posição anterior. As peças na mão não são mostradas.",
"panel.label": "Sua decisão",
"panel.sending": "Enviando…",
"announce.ask": "Encerrar o jogo depois deste turno? Não dá para desfazer.",
"turn.undo": "Desfazer",
"announce.ask": "Encerrar o jogo depois deste turno?",
"announce.confirm": "Anunciar o fim",
"announce.cancel": "Continuar jogando",
"announce.open": "Anunciar o fim…",

View file

@ -15,7 +15,8 @@ export const ro: Catalog = {
"status.replayNote": "Vezi o poziție anterioară. Piesele din mână nu sunt afișate.",
"panel.label": "Decizia ta",
"panel.sending": "Se trimite…",
"announce.ask": "Încheiem jocul după această tură? Nu se poate anula.",
"turn.undo": "Anulează",
"announce.ask": "Încheiem jocul după această tură?",
"announce.confirm": "Anunță sfârșitul",
"announce.cancel": "Continuă jocul",
"announce.open": "Anunță sfârșitul…",

View file

@ -15,7 +15,8 @@ export const ru: Catalog = {
"status.replayNote": "Вы смотрите более раннюю позицию. Фишки на руке не показываются.",
"panel.label": "Ваше решение",
"panel.sending": "Отправка…",
"announce.ask": "Закончить игру после этого хода? Это нельзя отменить.",
"turn.undo": "Отменить",
"announce.ask": "Закончить игру после этого хода?",
"announce.confirm": "Объявить конец игры",
"announce.cancel": "Продолжить игру",
"announce.open": "Объявить конец игры…",

View file

@ -15,7 +15,8 @@ export const vi: Catalog = {
"status.replayNote": "Bạn đang xem một thế cờ trước đó. Các ô trên tay không được hiển thị.",
"panel.label": "Quyết định của bạn",
"panel.sending": "Đang gửi…",
"announce.ask": "Kết thúc ván chơi sau lượt này? Không thể hoàn tác.",
"turn.undo": "Hoàn tác",
"announce.ask": "Kết thúc ván chơi sau lượt này?",
"announce.confirm": "Tuyên bố kết thúc",
"announce.cancel": "Tiếp tục chơi",
"announce.open": "Tuyên bố kết thúc…",

View file

@ -15,7 +15,8 @@ export const zhCN: Catalog = {
"status.replayNote": "你正在查看较早的局面。手中的板块不会显示。",
"panel.label": "你的决定",
"panel.sending": "正在发送…",
"announce.ask": "在本回合结束后结束游戏?此操作无法撤销。",
"turn.undo": "撤销",
"announce.ask": "在本回合结束后结束游戏?",
"announce.confirm": "宣布结束",
"announce.cancel": "继续游戏",
"announce.open": "宣布结束…",

View file

@ -15,7 +15,8 @@ export const zhTW: Catalog = {
"status.replayNote": "你正在檢視較早的局面。手中的板塊不會顯示。",
"panel.label": "你的決定",
"panel.sending": "正在傳送…",
"announce.ask": "在本回合結束後結束遊戲?此動作無法復原。",
"turn.undo": "復原",
"announce.ask": "在本回合結束後結束遊戲?",
"announce.confirm": "宣布結束",
"announce.cancel": "繼續遊戲",
"announce.open": "宣布結束…",

View file

@ -1,11 +1,12 @@
import { getContext } from "svelte";
import type { PlayerAppearance } from "@boardgamers/protocol";
import { ChatController } from "@boardgamers/protocol/chat";
import { seatsOf, type GameState, type Move, type Tile } from "acquire-engine";
import { seatsOf, type GameState, type Move, type TurnRequest, type Tile } from "acquire-engine";
import { movesFor } from "./decisions";
import { langFor } from "./format";
import { isRightToLeft, type Locale } from "./i18n";
import { replayStart, replayView } from "./replay";
import { TurnDraft } from "./turn-draft";
/** Context key: the store is given to every component at mount, for viewer-wide settings. */
export const STORE = Symbol("viewer-store");
@ -50,12 +51,60 @@ export class ViewerStore {
/** True between sending a move and receiving the resulting state, so it cannot be sent twice. */
sending = $state(false);
constructor(private readonly sendMove: (move: Move) => boolean) {}
private readonly draft = new TurnDraft();
undoCount = $state(0);
canUndo = $derived(
this.undoCount > 0 && !this.sending && !this.readOnly && !this.analysis && this.replayAt === undefined
);
setState(state: GameState): void {
constructor(
private readonly sendMove: (move: Move | TurnRequest) => boolean,
private readonly options: { turnDrafts?: boolean; onState?: (state: GameState) => void } = {}
) {}
private display(state: GameState): void {
this.state = state;
this.selected = undefined;
this.sending = false;
this.undoCount = this.draft.count;
this.options.onState?.(state);
}
setState(state: GameState): void {
if (this.draft.committed(state)) {
this.display(state);
}
}
setPlayer(player: number | undefined): void {
if (player !== this.player) {
this.draft.reset();
this.undoCount = 0;
}
this.player = player;
}
preview(state: GameState): void {
if (this.draft.accept(state, this.player)) {
this.display(state);
}
}
moveResult(move: unknown, ok: boolean): void {
// A success acknowledgement can precede the queued preview/state callback.
if (!ok && (!this.draft.pending || this.draft.reject(move))) {
this.sending = false;
}
}
undo(): void {
if (!this.canUndo) {
return;
}
const previous = this.draft.undo();
if (previous) {
this.display(previous);
}
}
/** The replay range BGS shows in its controls: setup done, up to the live position. */
@ -64,9 +113,15 @@ export class ViewerStore {
}
send(move: Move): void {
if (this.sending || this.readOnly) {
if (this.sending || this.readOnly || this.replayAt !== undefined) {
return;
}
this.sending = this.sendMove($state.snapshot(move));
const action = $state.snapshot(move);
const request =
this.options.turnDrafts && this.state?.supportsTurnDrafts && !this.analysis ? this.draft.begin(action) : action;
this.sending = true;
if (!this.sendMove(request)) {
this.moveResult(request, false);
}
}
}

View file

@ -0,0 +1,83 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { type Move } from "acquire-engine";
import * as engine from "acquire-engine/wrapper";
import { preparedPosition } from "../tutorial/lessons.ts";
import { TurnDraft } from "./turn-draft.ts";
function setup() {
const full = preparedPosition("founding");
const base = engine.stripSecret(full, 0);
const draft = new TurnDraft();
draft.committed(base);
const accept = (move: Move) => {
const request = draft.begin(move);
const result = engine.move(full, request, 0);
const view = engine.logSlice(result, { player: 0 }).preview!;
assert.equal(draft.accept(view, 0), true);
return view;
};
return { full, base, draft, accept };
}
const place: Move = { type: "place", tile: "2A" };
const found: Move = { type: "found", chain: "tower" };
test("undo uses authoritative snapshots and discards changed choices from the next request", () => {
const { draft, base, accept } = setup();
const placed = accept(place);
accept(found);
assert.deepEqual(draft.undo(), placed);
const replaced = accept({ type: "found", chain: "luxor" });
assert.equal(replaced.board[0], "luxor");
const final = draft.begin({ type: "buy", shares: {} });
assert.deepEqual(final.moves, [place, { type: "found", chain: "luxor" }, { type: "buy", shares: {} }]);
assert.equal(draft.undo(), undefined, "cannot undo an in-flight request");
draft.reject(final);
draft.undo();
assert.deepEqual(draft.undo(), base);
assert.equal(draft.count, 0);
});
test("saved-state refreshes do not erase pending or accepted choices", () => {
const { draft, base, accept } = setup();
accept(place);
assert.equal(draft.committed(structuredClone(base)), false);
const request = draft.begin(found);
assert.equal(draft.committed(structuredClone(base)), false);
assert.deepEqual(draft.pending, request);
draft.reject(request);
assert.equal(draft.count, 1);
});
test("rejected, stale, duplicate and other-player responses do not corrupt a draft", () => {
const { draft, full, accept } = setup();
const placed = accept(place);
assert.equal(draft.accept(placed, 0), false);
const request = draft.begin(found);
const founded = engine.stripSecret(engine.move(full, request, 0), 0);
assert.equal(draft.accept(placed, 0), false);
assert.equal(draft.accept(founded, 1), false);
assert.equal(draft.reject({ ...request, from: -1 }), false);
assert.equal(draft.reject(request), true);
assert.equal(draft.accept(founded, 0), false);
assert.equal(draft.count, 1);
assert.equal(draft.begin({ type: "found", chain: "luxor" }).moves.length, 2);
});
test("new committed states and player changes close undo; repeated revisions stay bounded", () => {
const { draft, full, base, accept } = setup();
for (let i = 0; i < 50; i++) {
accept(place);
assert.deepEqual(draft.undo(), base);
}
accept(place);
accept(found);
const result = engine.move(full, draft.begin({ type: "buy", shares: {} }), 0);
assert.equal(draft.committed(engine.stripSecret(result, 0)), true);
assert.equal(draft.count, 0);
assert.equal(draft.undo(), undefined);
assert.equal(draft.pending, undefined);
draft.reset();
assert.equal(draft.base, undefined);
});

View file

@ -0,0 +1,76 @@
import type { GameState, Move, TurnRequest } from "acquire-engine";
/** Only server-validated private views are cached; hidden holdings are never simulated here. */
export class TurnDraft {
base?: GameState;
private moves: Move[] = [];
private previews: GameState[] = [];
pending?: TurnRequest;
get count(): number {
return this.moves.length;
}
reset(): void {
this.base = undefined;
this.moves = [];
this.previews = [];
this.pending = undefined;
}
committed(state: GameState): boolean {
// BGS can refresh the saved state while a private choice is being previewed.
if ((this.count > 0 || this.pending) && JSON.stringify(state) === JSON.stringify(this.base)) {
return false;
}
this.reset();
this.base = structuredClone(state);
return true;
}
begin(move: Move): TurnRequest {
if (!this.base || this.pending) {
throw new Error("No available turn draft");
}
this.pending = { type: "turn", from: this.base.log.length, moves: [...this.moves, move] };
return structuredClone(this.pending);
}
accept(state: GameState, player: number | undefined): boolean {
if (
!this.pending ||
!this.base ||
state.tentative?.player !== player ||
state.tentative?.from !== this.pending.from
) {
return false;
}
const moves = state.log
.slice(this.pending.from)
.flatMap((entry) => (entry.type === "move" && !entry.auto ? [entry.move] : []));
if (JSON.stringify(moves) !== JSON.stringify(this.pending.moves)) {
return false;
}
this.moves = this.pending.moves;
this.previews.push(structuredClone(state));
this.pending = undefined;
return true;
}
reject(move: unknown): boolean {
if (JSON.stringify(move) !== JSON.stringify(this.pending)) {
return false;
}
this.pending = undefined;
return true;
}
undo(): GameState | undefined {
if (this.pending || !this.count) {
return undefined;
}
this.moves.pop();
this.previews.pop();
return structuredClone(this.previews.at(-1) ?? this.base!);
}
}

View file

@ -38,7 +38,9 @@ export const mountTutorial: TutorialMount = async (target, options) => {
wrapper.append(guideHost, gameHost);
target.append(wrapper);
const store = new ViewerStore((move) => {
void controller.play(move);
if (move.type !== "turn") {
void controller.play(move);
}
return true;
});
store.player = 0;

View file

@ -1,6 +1,6 @@
import { mount, tick, unmount } from "svelte";
import { registerViewer } from "@boardgamers/protocol/viewer";
import type { GameState, Move } from "acquire-engine";
import type { GameState, Move, TurnRequest } from "acquire-engine";
import App from "./App.svelte";
import { resolveLocale } from "./lib/i18n";
import { initialTheme, themeCss } from "./lib/palette";
@ -9,25 +9,33 @@ import { STORE, ViewerStore } from "./lib/store.svelte";
import "./lib/theme.css";
import { mountTutorial } from "./tutorial/mount.svelte";
export const viewer = registerViewer<GameState, Move>(
export const viewer = registerViewer<GameState, Move | TurnRequest>(
"acquire",
({ target, move, setReplayInfo }) => {
({ target, move, setReplayInfo, fetchState }) => {
const style = document.createElement("style");
style.textContent = themeCss();
document.head.append(style);
const store = new ViewerStore(move);
const sounds = createActionSounds(target);
const store = new ViewerStore(move, { turnDrafts: true, onState: (state) => sounds.onState(state) });
store.theme = initialTheme();
const app = mount(App, { target, props: { store }, context: new Map([[STORE, store]]) });
return {
chat: store.chat,
async onState(state) {
sounds.onState(state);
store.setState(state);
await tick();
},
async onLog({ data }) {
const preview = (data as { preview?: GameState } | undefined)?.preview;
if (preview) {
store.preview(preview);
} else {
fetchState();
}
await tick();
},
onPlayer({ index }) {
store.player = index;
store.setPlayer(index);
},
onPreferences(preferences) {
sounds.onPreferences(preferences);
@ -56,10 +64,8 @@ export const viewer = registerViewer<GameState, Move>(
sounds.onReplayEnd();
store.replayAt = undefined;
},
onMoveResult({ ok }) {
if (!ok) {
store.sending = false;
}
onMoveResult({ move, ok }) {
store.moveResult(move, ok);
},
destroy() {
sounds.destroy();

View file

@ -407,6 +407,67 @@ try {
assert.equal(await page.locator("main .board").first().innerText(), after);
report.scenarios.push("real tile move through the built viewer and state refresh");
// Private drafts run through the real BGS-shaped engine response, never through a local rules shortcut.
for (const width of [1280, 390]) {
await page.setViewportSize({ width, height: 900 });
await open("players=3&hotseat=0&view=0&theme=dark");
const original = await page.evaluate(async () => {
const { preparedPosition } = await import("/src/tutorial/lessons.ts");
window.acquireDev.load(preparedPosition("founding"));
window.undoRequests = [];
window.acquireDev.emitter.on("move", (request) => window.undoRequests.push(request));
return JSON.stringify(window.acquireDev.state);
});
await settle();
const boardBefore = await page.locator("main .board").first().innerText();
const undo = page.getByRole("button", { name: "Undo", exact: true });
for (let repeat = 0; repeat < 3; repeat++) {
await page.locator(".board").getByRole("button", { name: "Place 2A", exact: true }).click();
await undo.waitFor();
assert.ok((await undo.boundingBox()).height >= 44, "undo is a full touch target");
await page.locator(".choices button").filter({ hasText: "Tower" }).click();
await page.waitForSelector("table.buy");
assert.equal(await page.evaluate(() => JSON.stringify(window.acquireDev.state)), original);
await page.evaluate(() => window.acquireDev.emitter.emit("state:updated"));
await settle();
assert.equal(await page.locator("table.buy").count(), 1, "saved-state refresh preserves private choices");
const count = await page.evaluate(() => window.undoRequests.length);
await undo.click();
await page.waitForSelector(".choices");
await undo.click();
await page.waitForSelector(".square.playable");
assert.equal(await page.locator("main .board").first().innerText(), boardBefore);
assert.equal(
await page.evaluate(() => window.undoRequests.length),
count,
"undo sends no history-writing action"
);
assert.equal(await undo.count(), 0);
}
await page.locator(".board").getByRole("button", { name: "Place 2A", exact: true }).click();
await page.locator(".choices button").filter({ hasText: "Luxor" }).click();
await page.waitForSelector("table.buy");
await page.screenshot({ path: new URL(`undo-${width}.png`, output).pathname, fullPage: true });
await page.locator(".panel .primary").click();
await page.waitForFunction(() => window.acquireDev.state.turn === 2);
await settle();
assert.equal(await undo.count(), 0, "no undo after drawing and handing over");
const committed = await page.evaluate(() => ({
moves: window.acquireDev.state.log.filter((e) => e.type === "move").map((e) => e.move),
increments: window.acquireDev.engine.timeIncrements(window.acquireDev.state),
}));
assert.deepEqual(committed.moves, [
{ type: "place", tile: "2A" },
{ type: "found", chain: "luxor" },
{ type: "buy", shares: {} },
]);
assert.deepEqual(committed.increments, [1, 0, 0]);
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));
}
report.scenarios.push(
"desktop/phone undo, repeated private revisions, refresh, no undo network calls, one saved turn and one clock increment"
);
// The desktop used to stack every supporting panel in one tall sidebar. Check the rendered
// arrangement and height, not only horizontal overflow, before creating gallery images.
await page.setViewportSize({ width: 1280, height: 900 });
@ -576,7 +637,13 @@ try {
.getByRole("button", { name: chapter === "founding" ? "2A" : "4A", exact: true })
.click();
await page.locator("main .panel .primary").click();
await page.waitForSelector('.acquire-tutorial[data-step="1"]');
await page.waitForSelector('.acquire-tutorial[data-step="1"]').catch(async (error) => {
await page.screenshot({ path: new URL("tutorial-failure.png", output).pathname, fullPage: true });
throw new Error(
`${chapter} ${locale} ${width}px: ${await page.locator("#app").innerText()}\n${errors.join("\n")}`,
{ cause: error }
);
});
if (chapter === "founding") {
await page.locator(".choices button").filter({ hasText: "Tower" }).click();
await page.waitForSelector('.acquire-tutorial[data-step="2"]');