Merge pull request #9 from boardgamers/moon/tentative-turns

Tentative-turn model: per-turn time increments, free undo, append-only log (engine+viewer 2.0.0)
This commit is contained in:
Eliott C. 2026-08-17 12:11:47 +02:00 • committed by GitHub
commit 93983c3fe3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
41 changed files with 19099 additions and 15454 deletions

View file

@ -28,7 +28,7 @@ jobs:
node-version: ${{ env.node_version }}
# registry-url is required so npm publish targets the public npm registry
registry-url: 'https://registry.npmjs.org'
- run: npm install -g pnpm@5.17.1
- run: npm install -g pnpm@11
- run: pnpm install
- run: git config --global user.name github-actions
- run: git config --global user.email bot@github.com

View file

@ -17,13 +17,13 @@ jobs:
lint_and_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '12'
- uses: pnpm/action-setup@v1.2.1
node-version: '24'
- uses: pnpm/action-setup@v4
with:
version: 5.17.1
version: 11
- run: pnpm install
- run: pnpm build
- run: pnpm lint

View file

@ -5,10 +5,12 @@ jobs:
prettier:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
- uses: pnpm/action-setup@v1.2.1
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
version: 5.17.1
node-version: '24'
- uses: pnpm/action-setup@v4
with:
version: 11
- run: pnpm install
- run: pnpm run prettier-check

View file

@ -28,7 +28,7 @@ jobs:
node-version: ${{ env.node_version }}
# registry-url is required so npm publish targets the public npm registry
registry-url: 'https://registry.npmjs.org'
- run: npm install -g pnpm@5.17.1
- run: npm install -g pnpm@11
- run: pnpm install
- run: git config --global user.name github-actions
- run: git config --global user.email bot@github.com

View file

@ -19,13 +19,13 @@ jobs:
test_and_build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '14'
- uses: pnpm/action-setup@v1.2.1
node-version: '24'
- uses: pnpm/action-setup@v4
with:
version: 5.17.1
version: 11
- run: pnpm install
# - run: pnpm lint
# - run: pnpm test

2
.gitignore vendored
View file

@ -1 +1,3 @@
node_modules
.pnpm-store
.playwright-mcp

2
.prettierignore Normal file
View file

@ -0,0 +1,2 @@
dist/
.vscode/

View file

@ -1,5 +1,5 @@
export { availableMoves, AvailableMoves } from './src/available-moves';
export { currentPlayers, ended, move, moveAI, reconstructState, setup, stripSecret } from './src/engine';
export { currentPlayers, ended, move, moveAI, setup, stripSecret } from './src/engine';
export { Phase } from './src/gamestate';
export type { GameState, Player, PointCard } from './src/gamestate';
export { GameEventName, LogItem } from './src/log';

View file

@ -1,6 +1,6 @@
{
"name": "container-engine",
"version": "1.0.11",
"version": "2.0.0",
"description": "An engine for Container",
"main": "dist/index.js",
"types": "index.ts",

2361
engine/pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -24,7 +24,6 @@ export interface AvailableMoves {
[MoveName.Accept]?: number[];
[MoveName.Decline]?: boolean[];
[MoveName.Pass]?: boolean[];
[MoveName.Undo]?: boolean[];
}
export function availableMoves(G: GameState, player: Player): AvailableMoves {
@ -36,10 +35,6 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
if (player.loans.length < 2) moves[MoveName.GetLoan] = [true];
// Undo
const lastLog = G.log[G.log.length - 1];
if (lastLog.type == 'move' && G.currentPlayers.includes(lastLog.player)) moves[MoveName.Undo] = [true];
return moves;
}
@ -53,10 +48,6 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
const highestBidder = G.players[G.highestBidders[0]];
if (player.money >= highestBidder.bid + highestBidder.additionalBid) moves[MoveName.Decline] = [true];
// Undo
const lastLog = G.log[G.log.length - 1];
if (lastLog.type == 'move' && G.currentPlayers.includes(lastLog.player)) moves[MoveName.Undo] = [true];
return moves;
}
@ -301,10 +292,6 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
}
}
// Undo
const lastLog = G.log[G.log.length - 1];
if (lastLog.type == 'move' && G.currentPlayers.includes(lastLog.player)) moves[MoveName.Undo] = [true];
return moves;
}

View file

@ -1,7 +1,10 @@
import { expect } from 'chai';
import { cloneDeep, range } from 'lodash';
import { ended, move, setup } from './engine';
import AbstractJudge from './fixtures/Abstract-judge-7215.json';
import { GameEventName } from './log';
import type { Move } from './move';
import { MoveName } from './move';
describe('Engine', () => {
it('should setup a game correctly', () => {
@ -28,4 +31,29 @@ describe('Engine', () => {
expect(G.currentPlayers).to.deep.equal([0]);
expect(ended(G)).to.be.false;
});
it('should seize upkeep containers deterministically from the game seed', () => {
const base = setup(2, {}, 'upkeep-seed-test');
const A = base.currentPlayers[0];
const B = 1 - A;
// Force B into upkeep debt: two loans, no money, and a pile of island
// containers for the bank to pick from
base.players[B].loans = base.loansLeft.splice(0, 2);
base.players[B].money = 0;
base.players[B].containersOnIsland = base.containersLeft.splice(0, 12);
// A's pass hands the turn to B and runs B's upkeep, seizing two random
// containers. Same seed + same history ⇒ the same containers, every time.
const results = range(5).map(() => move(cloneDeep(base), { name: MoveName.Pass, data: true }, A));
expect(results[0].players[B].containersOnIsland).to.have.length(10);
expect(
results[0].log.filter((item) => item.type === 'event' && item.event.name === GameEventName.Upkeep)
).to.have.length(2);
for (const result of results.slice(1)) {
expect(JSON.parse(JSON.stringify(result))).to.deep.equal(JSON.parse(JSON.stringify(results[0])));
}
});
});

View file

@ -1,5 +1,5 @@
import assert from 'assert';
import { chunk, cloneDeep, groupBy, isEqual, range, zip } from 'lodash';
import { chunk, groupBy, isEqual, range, zip } from 'lodash';
import seedrandom from 'seedrandom';
import { availableMoves } from './available-moves';
import pointCards from './cards';
@ -85,6 +85,7 @@ export function setup(numPlayers: number, { beginner = true }: GameOptions, seed
hiddenLog: [],
seed,
round: 1,
newTurn: true,
} as GameState;
const colors = shuffle(containerColors, rng() + '');
@ -474,10 +475,11 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
.forEach((p) => {
p.showBid = true;
});
const highestBid = Math.max(...G.players.map((p) => p.bid));
const highestBidders = G.players
.filter((p) => p.id != G.auctioningPlayer && !p.isDropped && p.bid === highestBid)
.map((p) => p.id);
// Only players still in the game can win the auction, so a dropped
// player's bid must not enter the maximum either.
const eligible = G.players.filter((p) => p.id != G.auctioningPlayer && !p.isDropped);
const highestBid = Math.max(...eligible.map((p) => p.bid));
const highestBidders = eligible.filter((p) => p.bid === highestBid).map((p) => p.id);
G.highestBidders = highestBidders;
if (highestBidders.length > 1) {
G.currentPlayers = highestBidders;
@ -486,11 +488,10 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
G.phase = Phase.AcceptDecline;
}
} else {
const highestBid = Math.max(...G.players.map((p) => p.bid + p.additionalBid));
const highestBidders = G.players
.filter(
(p) => p.id != G.auctioningPlayer && !p.isDropped && p.bid + p.additionalBid === highestBid
)
const eligible = G.players.filter((p) => p.id != G.auctioningPlayer && !p.isDropped);
const highestBid = Math.max(...eligible.map((p) => p.bid + p.additionalBid));
const highestBidders = eligible
.filter((p) => p.bid + p.additionalBid === highestBid)
.map((p) => p.id);
G.highestBidders = highestBidders;
G.players.forEach((p) => {
@ -608,18 +609,6 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
break;
}
case MoveName.Undo: {
asserts<Moves.MoveUndo>(move);
const lastLog = G.log[G.log.length - 1];
if (lastLog.type == 'move' && G.currentPlayers.includes(lastLog.player) && !fake) {
G.log.pop();
G = reconstructState(getBaseState(G), G.log);
}
return G;
}
}
player.availableMoves = null;
@ -628,6 +617,22 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
G.currentPlayers.forEach((p) => (G.players[p].availableMoves = availableMoves(G, G.players[p])));
// Tentative-turn bookkeeping: the state is committed (`newTurn`) once the mover can
// no longer undo. This mirrors the old undo-availability rule — undo was offered
// whenever the last visible log entry was a move by a player still in
// `currentPlayers` — with turn-boundary moves committing unconditionally:
// - Pass / Accept / Decline end the turn (even in the edge case where the same
// player is up again because everyone else is dropped);
// - Bid (and loans taken during the bid phase) go to the hidden log and were never
// undoable: bids are single-move committed turns.
const lastLog = G.log[G.log.length - 1];
const turnBoundary =
move.name === MoveName.Pass ||
move.name === MoveName.Accept ||
move.name === MoveName.Decline ||
move.name === MoveName.Bid;
G.newTurn = turnBoundary || !(lastLog?.type === 'move' && G.currentPlayers.includes(lastLog.player));
return G;
}
@ -682,7 +687,7 @@ export function moveAI(G: GameState, playerNumber: number): GameState {
data = dataArr[Math.floor(Math.random() * dataArr.length)];
if (moveName == MoveName.Undo || moveName == MoveName.GetLoan || moveName == MoveName.PayLoan) {
if (moveName == MoveName.GetLoan || moveName == MoveName.PayLoan) {
moveName = null;
} else if (moveName == MoveName.Sail) {
if (data == ShipPosition.Island) {
@ -877,29 +882,6 @@ export function scores(G: GameState): number[] {
return ended(G) ? G.players.map((p) => p.money) : G.players.map((_) => 0);
}
export function reconstructState(initialState: GameState, log: LogItem[]): GameState {
const G = cloneDeep(initialState);
for (const item of log) {
switch (item.type) {
case 'event': {
break;
}
case 'phase': {
break;
}
case 'move': {
move(G, item.move, item.player);
break;
}
}
}
return G;
}
function playerBefore(player: Player, G: GameState) {
return player.id === 0 ? G.players[G.players.length - 1] : G.players[player.id - 1];
}
@ -911,6 +893,12 @@ export function nextPlayer(G: GameState) {
}
function doUpkeep(G: GameState) {
// Container seizures must be reproducible: the platform guarantees that the same
// seed yields the same game, and `wrapper.replay` re-runs upkeep from the log. The
// seed comes from the persisted state, and the visible log length uniquely
// identifies this upkeep within the game (each upkeep immediately follows its own
// Pass/Accept/Decline log entry), so together they pin a per-upkeep random stream.
const rng = seedrandom(`${G.seed}:upkeep:${G.log.length}`);
const player = G.players[G.currentPlayers[0]];
const loanCount = player.loans.length;
const interest: string[] = [];
@ -919,7 +907,7 @@ function doUpkeep(G: GameState) {
player.money--;
interest.push('money');
} else if (player.containersOnIsland.length > 0) {
const container = removeRandom(player.containersOnIsland);
const container = removeRandom(player.containersOnIsland, rng);
G.log.push({
type: 'event',
event: {
@ -931,32 +919,32 @@ function doUpkeep(G: GameState) {
});
} else if (player.containersOnWarehouseStore.length + player.containersOnFactoryStore.length > 0) {
if (player.containersOnWarehouseStore.length >= 2) {
const c1 = removeRandom(player.containersOnWarehouseStore);
const c2 = removeRandom(player.containersOnWarehouseStore);
const c1 = removeRandom(player.containersOnWarehouseStore, rng);
const c2 = removeRandom(player.containersOnWarehouseStore, rng);
G.log.push({
type: 'event',
event: {
name: GameEventName.Upkeep,
interest: `The bank seizes a ${containerColorHTML(
c1.color
)} container and a ${containerColorHTML(c2.color)} container from ${playerNameHTML(
c1.piece.color
)} container and a ${containerColorHTML(c2.piece.color)} container from ${playerNameHTML(
player
)}'s warehouses`,
},
});
} else if (player.containersOnWarehouseStore.length == 1) {
const c1 = removeRandom(player.containersOnWarehouseStore);
const c1 = removeRandom(player.containersOnWarehouseStore, rng);
if (player.containersOnFactoryStore.length >= 1) {
const c2 = removeRandom(player.containersOnFactoryStore);
const c2 = removeRandom(player.containersOnFactoryStore, rng);
G.log.push({
type: 'event',
event: {
name: GameEventName.Upkeep,
interest: `The bank seizes a ${containerColorHTML(
c1.color
)} container from ${playerNameHTML(player)}'s warehouses and a ${
c2.color
} container from ${playerNameHTML(player)}'s factory`,
c1.piece.color
)} container from ${playerNameHTML(player)}'s warehouses and a ${containerColorHTML(
c2.piece.color
)} container from ${playerNameHTML(player)}'s factory`,
},
});
} else {
@ -965,22 +953,22 @@ function doUpkeep(G: GameState) {
event: {
name: GameEventName.Upkeep,
interest: `The bank seizes a ${containerColorHTML(
c1.color
c1.piece.color
)} container from ${playerNameHTML(player)}'s warehouses`,
},
});
}
} else {
const c1 = removeRandom(player.containersOnFactoryStore);
const c1 = removeRandom(player.containersOnFactoryStore, rng);
if (player.containersOnFactoryStore.length >= 1) {
const c2 = removeRandom(player.containersOnFactoryStore);
const c2 = removeRandom(player.containersOnFactoryStore, rng);
G.log.push({
type: 'event',
event: {
name: GameEventName.Upkeep,
interest: `The bank seizes a ${containerColorHTML(
c1.color
)} container and a ${containerColorHTML(c2.color)} container from ${playerNameHTML(
c1.piece.color
)} container and a ${containerColorHTML(c2.piece.color)} container from ${playerNameHTML(
player
)}'s factory`,
},
@ -991,7 +979,7 @@ function doUpkeep(G: GameState) {
event: {
name: GameEventName.Upkeep,
interest: `The bank seizes a ${containerColorHTML(
c1.color
c1.piece.color
)} container from ${playerNameHTML(player)}'s factory`,
},
});
@ -1039,18 +1027,8 @@ function remove(array, value) {
return array.splice(array.indexOf(aux), 1);
}
function removeRandom(array) {
return array.splice(Math.floor(Math.random() * array.length), 1)[0];
}
function getBaseState(G: GameState): GameState {
const baseState = setup(G.players.length, G.options, G.seed);
baseState.players.forEach((player, i) => {
player.name = G.players[i].name;
player.isAI = G.players[i].isAI;
});
return baseState;
function removeRandom<T>(array: T[], rng: () => number): T {
return array.splice(Math.floor(rng() * array.length), 1)[0];
}
function prettyShipPosition(G: GameState, data: ShipPosition, simple = false): string {

View file

@ -135,4 +135,11 @@ export interface GameState {
hiddenLog: LogItem[];
seed: string;
round: number;
/**
* Tentative-turn marker. `true` (or `undefined`, for robustness) when the state is
* committed: the last mover can no longer undo and the state can be persisted.
* `false` while a player's turn is still in progress (mid-turn moves can be undone
* by the viewer by replaying a shortened turn buffer from the last committed state).
*/
newTurn?: boolean;
}

View file

@ -88,11 +88,6 @@ export declare namespace Moves {
name: MoveName.Pass;
data: boolean;
}
export interface MoveUndo {
name: MoveName.Undo;
data: boolean;
}
}
export type Move =
@ -110,7 +105,6 @@ export type Move =
| Moves.MoveAccept
| Moves.MoveDecline
| Moves.MovePass
| Moves.MoveUndo
| Moves.MoveDomesticSale;
export enum MoveName {
@ -129,5 +123,4 @@ export enum MoveName {
Accept = 'accept',
Decline = 'decline',
Pass = 'pass',
Undo = 'undo',
}

499
engine/src/wrapper.spec.ts Normal file
View file

@ -0,0 +1,499 @@
import { expect } from 'chai';
import { cloneDeep } from 'lodash';
import * as wrapper from '../wrapper';
import { setup } from './engine';
import { GameState, Phase, ShipPosition } from './gamestate';
import { Move, MoveName } from './move';
const getLoan: Move = { name: MoveName.GetLoan, data: true };
const payLoan: Move = { name: MoveName.PayLoan, data: true };
const pass: Move = { name: MoveName.Pass, data: true };
describe('wrapper (tentative turns)', () => {
/**
* Simulates the platform: `saved` only ever advances when `toSave` returns the
* state (committed); tentative states are discarded, like the game server does.
*/
class Platform {
saved: GameState;
logLengths: number[] = [];
constructor(players = 2, seed = 'wrapper-test') {
this.saved = setup(players, {}, seed);
this.logLengths.push(wrapper.logLength(this.saved));
}
/** Replay a turn buffer from the saved state, persist only if committed. */
async send(moves: Move | Move[], player: number): Promise<{ result: GameState; saved: boolean }> {
const result = await wrapper.move(cloneDeep(this.saved), moves, player);
const toSave = wrapper.toSave(result);
if (toSave) {
this.saved = toSave;
this.logLengths.push(wrapper.logLength(this.saved));
}
return { result, saved: !!toSave };
}
}
it('should keep mid-turn states tentative and commit when the turn completes', async () => {
const platform = new Platform();
const A = platform.saved.currentPlayers[0];
// Mid-turn move: still undoable, must not be saved
const mid = await platform.send([getLoan], A);
expect(mid.saved).to.be.false;
expect(mid.result.newTurn).to.be.false;
expect(wrapper.toSave(mid.result)).to.be.undefined;
// ...but the tentative state did apply the move for the player's preview
expect(mid.result.players[A].loans).to.have.length(1);
// The tentative state was NOT persisted
expect(platform.saved.players[A].loans).to.have.length(0);
// Completed turn: the full buffer replays from the saved state and commits
const full = await platform.send([getLoan, pass], A);
expect(full.saved).to.be.true;
expect(full.result.newTurn).to.be.true;
expect(platform.saved.players[A].loans).to.have.length(1);
expect(platform.saved.currentPlayers).to.not.include(A);
});
it('should accept a bare move object as a one-element buffer', async () => {
const base = setup(2, {}, 'wrapper-test');
const A = base.currentPlayers[0];
const fromObject = await wrapper.move(cloneDeep(base), pass, A);
const fromArray = await wrapper.move(cloneDeep(base), [pass], A);
expect(JSON.parse(JSON.stringify(fromObject))).to.deep.equal(JSON.parse(JSON.stringify(fromArray)));
expect(wrapper.toSave(fromObject)).to.not.be.undefined;
});
it('should not save an empty buffer and not grant it any progress', async () => {
const base = setup(2, {}, 'wrapper-test');
const A = base.currentPlayers[0];
const result = await wrapper.move(cloneDeep(base), [], A);
expect(wrapper.toSave(result)).to.be.undefined;
expect(wrapper.logLength(result)).to.equal(wrapper.logLength(base));
});
it('should make undo-by-truncation equivalent to never having made the popped move', async () => {
const base = setup(2, {}, 'wrapper-test');
const A = base.currentPlayers[0];
// Replaying a shortened buffer from the committed base...
const shortened = await wrapper.move(cloneDeep(base), [getLoan], A);
// ...equals never having made the popped move at all
const straight = await wrapper.move(cloneDeep(base), [getLoan], A);
expect(JSON.parse(JSON.stringify(shortened))).to.deep.equal(JSON.parse(JSON.stringify(straight)));
// Popping the whole buffer needs no server call at all: the saved state is the
// turn start. Taking a loan, undoing it (nothing sent), then passing yields the
// exact same committed state as passing right away.
const passedAfterUndo = await wrapper.move(cloneDeep(base), [pass], A);
const passedDirectly = await wrapper.move(cloneDeep(base), [pass], A);
expect(JSON.parse(JSON.stringify(wrapper.toSave(passedAfterUndo)))).to.deep.equal(
JSON.parse(JSON.stringify(wrapper.toSave(passedDirectly)))
);
// And the tentative detour left no trace to pop: a longer buffer, truncated,
// reproduces the shorter buffer's state exactly.
const detour = await wrapper.move(cloneDeep(base), [getLoan, payLoan], A);
expect(wrapper.toSave(detour)).to.be.undefined;
const truncated = await wrapper.move(cloneDeep(base), [getLoan], A);
expect(JSON.parse(JSON.stringify(truncated))).to.deep.equal(JSON.parse(JSON.stringify(shortened)));
});
/**
* Scripted 3-player opening: plays committed turns until the starting player A has
* sailed to the island with one container, starting an auction where B and C (the
* next players in turn order) are the simultaneous bidders.
*/
async function playToBidPhase(platform: Platform): Promise<{ A: number; B: number; C: number }> {
const A = platform.saved.currentPlayers[0];
const B = (A + 1) % 3;
const C = (A + 2) % 3;
// A buys from B's factory; B buys from A's factory (so B's warehouse store
// holds a container A can later pick up); C just passes.
await platform.send(
[
{
name: MoveName.BuyFromFactory,
data: { player: B, piece: platform.saved.players[B].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
},
pass,
],
A
);
await platform.send(
[
{
name: MoveName.BuyFromFactory,
data: { player: A, piece: platform.saved.players[A].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
},
pass,
],
B
);
await platform.send([pass], C);
// A picks up a container from B's warehouse...
await platform.send(
[
{ name: MoveName.Sail, data: `playerHarbor${B}1` as ShipPosition },
{
name: MoveName.BuyFromWarehouse,
data: { player: B, piece: platform.saved.players[B].containersOnWarehouseStore[0].piece },
},
pass,
],
A
);
await platform.send([pass], B);
await platform.send([pass], C);
// ...and sails to the island, starting the auction
await platform.send(
[
{ name: MoveName.Sail, data: ShipPosition.OpenSea },
{ name: MoveName.Sail, data: ShipPosition.Island },
],
A
);
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.currentPlayers).to.have.members([B, C]);
return { A, B, C };
}
it('should play a 3-player auction with a bid tie and an additional-bid round', async () => {
const platform = new Platform(3, 'wrapper-test-3p');
const { A, B, C } = await playToBidPhase(platform);
// Each bid is a single-move committed turn (bids live in the hidden log)
const bidB = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
expect(bidB.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.currentPlayers).to.deep.equal([C]);
// C matches B's bid: tie → additional-bid round between the tied bidders
const bidC = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], C);
expect(bidC.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.highestBidders).to.have.members([B, C]);
expect(platform.saved.currentPlayers).to.have.members([B, C]);
// The bids are still hidden: nothing was flushed to the visible log yet
expect(platform.saved.hiddenLog).to.have.length(2);
// Additional bids, again one committed turn each; B outbids C
const addB = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 2 } }], B);
expect(addB.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.currentPlayers).to.deep.equal([C]);
const addC = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 0 } }], C);
expect(addC.saved).to.be.true;
// The additional-bid round resolved the tie: the auctioneer decides, and the
// hidden bid moves surfaced in the visible log
expect(platform.saved.phase).to.equal(Phase.AcceptDecline);
expect(platform.saved.currentPlayers).to.deep.equal([A]);
expect(platform.saved.highestBidders).to.deep.equal([B]);
expect(platform.saved.hiddenLog).to.have.length(0);
const moneyA = platform.saved.players[A].money;
const moneyB = platform.saved.players[B].money;
const accept = await platform.send([{ name: MoveName.Accept, data: B }], A);
expect(accept.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Move);
expect(platform.saved.players[B].containersOnIsland).to.have.length(1);
expect(platform.saved.players[B].money).to.equal(moneyB - 5);
expect(platform.saved.players[A].money).to.equal(moneyA + 10);
});
it('should reject a malformed buffer without leaking anything half-applied', async () => {
const platform = new Platform();
const A = platform.saved.currentPlayers[0];
const before = JSON.parse(JSON.stringify(platform.saved));
// A third loan is illegal (two loans per player at most): the buffer must be
// rejected even though its first two moves are legal.
let error: Error | null = null;
try {
await platform.send([getLoan, getLoan, getLoan], A);
} catch (err) {
error = err as Error;
}
expect(error, 'an illegal move mid-buffer must reject the whole buffer').to.not.be.null;
// Nothing half-applied leaked into the platform's saved state...
expect(JSON.parse(JSON.stringify(platform.saved))).to.deep.equal(before);
// ...and a valid buffer from that same state still works
const ok = await platform.send([getLoan, payLoan, pass], A);
expect(ok.saved).to.be.true;
});
it('should reject a buffer that keeps playing past a turn boundary', async () => {
// Degenerate case: the only other player is dropped, so the same player is up
// again right after passing — [Pass, Pass] is a sequence of individually legal
// moves that spans TWO turns. It must not commit both for one time increment.
const platform = new Platform();
const A = platform.saved.currentPlayers[0];
const B = 1 - A;
platform.saved = await wrapper.dropPlayer(platform.saved, B);
const before = JSON.parse(JSON.stringify(platform.saved));
let error: Error | null = null;
try {
await platform.send([pass, pass], A);
} catch (err) {
error = err as Error;
}
expect(error).to.not.be.null;
expect(error!.message).to.match(/turn boundary/);
expect(JSON.parse(JSON.stringify(platform.saved))).to.deep.equal(before);
// A buffer ending exactly on the turn boundary is still fine
const ok = await platform.send([getLoan, pass], A);
expect(ok.saved).to.be.true;
expect(platform.saved.currentPlayers).to.deep.equal([A]);
});
it('should play a full auction with the right commit points and a never-shrinking log', async () => {
const platform = new Platform();
const A = platform.saved.currentPlayers[0];
const B = 1 - A;
const buyFromB: Move = {
name: MoveName.BuyFromFactory,
data: { player: B, piece: platform.saved.players[B].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
};
// A: buy a container from B's factory (tentative), then pass (commits)
expect((await platform.send([buyFromB], A)).saved).to.be.false;
expect((await platform.send([buyFromB, pass], A)).saved).to.be.true;
// B: buy a container from A's factory into B's warehouse, then pass
const buyFromA: Move = {
name: MoveName.BuyFromFactory,
data: { player: A, piece: platform.saved.players[A].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
};
expect((await platform.send([buyFromA, pass], B)).saved).to.be.true;
// A: sail to B's harbor, buy from B's warehouse onto the ship, pass.
// Growing buffer resent on every action, tentative until the pass.
const sailToB: Move = {
name: MoveName.Sail,
data: `playerHarbor${B}1` as ShipPosition,
};
const buyWarehouse: Move = {
name: MoveName.BuyFromWarehouse,
data: { player: B, piece: platform.saved.players[B].containersOnWarehouseStore[0].piece },
};
expect((await platform.send([sailToB], A)).saved).to.be.false;
expect((await platform.send([sailToB, buyWarehouse], A)).saved).to.be.false;
expect((await platform.send([sailToB, buyWarehouse, pass], A)).saved).to.be.true;
expect(platform.saved.players[A].ship.containers).to.have.length(1);
// B: pass
expect((await platform.send([pass], B)).saved).to.be.true;
// A: sail back to the open sea (tentative), then to the island — which starts
// the auction and commits immediately (the mover leaves currentPlayers; there
// is nothing to undo for the bidders)
const sailSea: Move = { name: MoveName.Sail, data: ShipPosition.OpenSea };
expect((await platform.send([sailSea], A)).saved).to.be.false;
const sailIsland = await platform.send([sailSea, { name: MoveName.Sail, data: ShipPosition.Island }], A);
expect(sailIsland.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.currentPlayers).to.deep.equal([B]);
// B: bid — a single-move committed turn (bids live in the hidden log and were
// never undoable)
const bid = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
expect(bid.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.AcceptDecline);
expect(platform.saved.currentPlayers).to.deep.equal([A]);
// A (auctioneer): a loan during accept/decline is still undoable...
const loanFirst = await platform.send([getLoan], A);
expect(loanFirst.saved).to.be.false;
expect(platform.saved.players[A].loans).to.have.length(0);
// ...and accepting commits the whole turn
const moneyBefore = platform.saved.players[A].money;
const accept = await platform.send([getLoan, { name: MoveName.Accept, data: B }], A);
expect(accept.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Move);
expect(platform.saved.players[B].containersOnIsland).to.have.length(1);
// +10 for the loan, + twice the bid of 3 for the accepted auction
expect(platform.saved.players[A].money).to.equal(moneyBefore + 10 + 6);
// Control passed on: the accept itself can no longer be undone
expect(platform.saved.currentPlayers).to.deep.equal([B]);
expect(platform.saved.newTurn).to.be.true;
// The saved log never shrank across committed states
for (let i = 1; i < platform.logLengths.length; i++) {
expect(platform.logLengths[i]).to.be.at.least(platform.logLengths[i - 1]);
}
});
it('should let the auctioneer decline as a committed turn', async () => {
// Same script as above up to the auction, then decline instead of accept
const platform = new Platform();
const A = platform.saved.currentPlayers[0];
const B = 1 - A;
await platform.send(
[
{
name: MoveName.BuyFromFactory,
data: { player: B, piece: platform.saved.players[B].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
},
pass,
],
A
);
await platform.send(
[
{
name: MoveName.BuyFromFactory,
data: { player: A, piece: platform.saved.players[A].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
},
pass,
],
B
);
await platform.send(
[
{ name: MoveName.Sail, data: `playerHarbor${B}1` as ShipPosition },
{
name: MoveName.BuyFromWarehouse,
data: { player: B, piece: platform.saved.players[B].containersOnWarehouseStore[0].piece },
},
pass,
],
A
);
await platform.send([pass], B);
await platform.send(
[
{ name: MoveName.Sail, data: ShipPosition.OpenSea },
{ name: MoveName.Sail, data: ShipPosition.Island },
],
A
);
await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
const moneyBefore = platform.saved.players[A].money;
const decline = await platform.send([{ name: MoveName.Decline, data: true }], A);
expect(decline.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Move);
// Declining: A pays the highest bid and keeps the containers on their island
expect(platform.saved.players[A].money).to.equal(moneyBefore - 3);
expect(platform.saved.players[A].containersOnIsland).to.have.length(1);
expect(platform.saved.currentPlayers).to.deep.equal([B]);
});
it('should replay a state saved mid-bid-phase without dropping hidden log moves', async () => {
const platform = new Platform(3, 'wrapper-test-replay');
const { B, C } = await playToBidPhase(platform);
// One bid placed, plus a bid-phase loan: both live in the hidden log of the
// saved state (they are only flushed once the accept/decline phase starts)
await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
await platform.send([getLoan], C);
expect(platform.saved.hiddenLog).to.have.length(2);
expect(platform.saved.phase).to.equal(Phase.Bid);
// An admin full-replay of that save must reproduce it exactly, hidden bids included
const replayed = wrapper.replay(cloneDeep(platform.saved));
expect(JSON.parse(JSON.stringify(replayed))).to.deep.equal(JSON.parse(JSON.stringify(platform.saved)));
expect(replayed.players[B].bid).to.equal(3);
expect(replayed.players[C].loans).to.have.length(1);
});
it('should always produce committed states from moveAI', async () => {
let G = setup(2, {}, 'wrapper-test-ai');
G.players.forEach((player, i) => {
player.name = `AI ${i}`;
player.isAI = true;
});
for (let turn = 0; turn < 25 && !wrapper.ended(G) && G.currentPlayers.length > 0; turn++) {
const logLengthBefore = wrapper.logLength(G);
G = wrapper.moveAI(G, G.currentPlayers[0]);
expect(wrapper.toSave(G), `moveAI result of turn ${turn} must be saveable`).to.not.be.undefined;
expect(wrapper.logLength(G)).to.be.at.least(logLengthBefore);
}
});
it('should always produce committed states from dropPlayer', async () => {
const G = setup(3, {}, 'wrapper-test-drop');
const dropped = G.currentPlayers[0];
const result = await wrapper.dropPlayer(G, dropped);
expect(wrapper.toSave(result)).to.not.be.undefined;
expect(result.players[dropped].isDropped).to.be.true;
expect(result.currentPlayers).to.not.include(dropped);
// The drop played the pending turn through the regular path: the next player
// got their upkeep (actions, available moves) and can actually play
expect(result.players[result.currentPlayers[0]].availableMoves).to.not.be.null;
expect(result.players[result.currentPlayers[0]].actions).to.equal(2);
});
it('should only auto-play the dropped bidder and keep the other bidders current', async () => {
const platform = new Platform(3, 'wrapper-test-drop-bid');
const { A, B, C } = await playToBidPhase(platform);
// Both B and C are deciding on their bids; dropping C must auto-play only C's
// pending bid and leave B's turn untouched
platform.saved = await wrapper.dropPlayer(platform.saved, C);
expect(wrapper.toSave(platform.saved)).to.not.be.undefined;
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.currentPlayers).to.deep.equal([B]);
expect(platform.saved.players[B].availableMoves).to.not.be.null;
// B's bid then resolves the auction normally, with the dropped bidder excluded
const bid = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
expect(bid.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.AcceptDecline);
expect(platform.saved.currentPlayers).to.deep.equal([A]);
expect(platform.saved.highestBidders).to.deep.equal([B]);
});
it('should not advance the turn when dropping a player who is not up', async () => {
const platform = new Platform(3, 'wrapper-test-drop-idle');
const { A, B, C } = await playToBidPhase(platform);
// B has already bid; C is still deciding
await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
expect(platform.saved.currentPlayers).to.deep.equal([C]);
// Dropping B (not a current player) must not touch C's pending turn
platform.saved = await wrapper.dropPlayer(platform.saved, B);
expect(platform.saved.currentPlayers).to.deep.equal([C]);
expect(platform.saved.players[C].availableMoves).to.not.be.null;
// C's lower bid wins because dropped players are excluded from the auction
await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 2 } }], C);
expect(platform.saved.phase).to.equal(Phase.AcceptDecline);
expect(platform.saved.highestBidders).to.deep.equal([C]);
expect(platform.saved.currentPlayers).to.deep.equal([A]);
});
});

View file

@ -1,8 +1,9 @@
import { cloneDeep } from 'lodash';
import type { GameState } from './index';
import * as engine from './src/engine';
import { Phase } from './src/gamestate';
import type { LogMove } from './src/log';
import { Move } from './src/move';
import { Move, MoveName } from './src/move';
import { asserts } from './src/utils';
export async function init(nbPlayers: number, expansions: string[], options: {}, seed?: string): Promise<GameState> {
@ -15,17 +16,86 @@ export function setPlayerMetaData(G: GameState, player: number, metaData: { name
return G;
}
export async function move(G: GameState, move: Move, player: number) {
G = engine.move(G, move, player);
/**
* Execute the current turn of `player` so far.
*
* The payload is the **whole turn buffer**: an array of atomic moves accumulated by the
* viewer since the last committed state. `G` is always a committed state (tentative
* states are never persisted by the platform), so the buffer is replayed from it in
* order. A bare move object is also accepted and treated as a one-element buffer.
*
* While the resulting state is still tentative (the mover could undo, i.e.
* `G.newTurn === false`), `toSave` returns `undefined`: the platform then sends the
* tentative state back to the acting player without persisting it or granting a time
* increment. Undo is implemented by the viewer replaying a shortened buffer — or, when
* the buffer empties, by doing nothing at all, since the saved state *is* the turn start.
*/
export async function move(G: GameState, move: Move | Move[] | null | undefined, player: number) {
const moves: Move[] = move == null ? [] : Array.isArray(move) ? move : [move];
if (moves.length === 0) {
// Nothing to apply — flag the result as tentative so nothing gets persisted
// and no time increment is granted.
return { ...G, newTurn: false };
}
for (let i = 0; i < moves.length; i++) {
G = engine.move(G, moves[i], player);
// The buffer must describe at most ONE turn: committing is what grants the
// mover their per-turn time increment. Without this guard a buffer like
// `[..., Pass, ...more]` — legal in the degenerate case where the same player
// is up again because everyone else dropped — would replay across the turn
// boundary and commit several turns for a single increment.
if (G.newTurn !== false && i < moves.length - 1) {
throw new Error('The turn buffer continues past a turn boundary: only one turn may be played per call');
}
}
return G;
}
/**
* Only committed states are persisted. Tentative states (mid-turn, still undoable)
* return `undefined` so the platform neither saves them nor grants a time increment.
*/
export function toSave(G: GameState): GameState | undefined {
return G.newTurn === false ? undefined : G;
}
export function factions(G: GameState) {
return G.players.map((pl) => engine.playerColors[pl.id]);
}
export { ended, moveAI, scores, stripSecret } from './src/engine';
export { ended, scores, stripSecret } from './src/engine';
/**
* Play a full turn for `player`. The engine's own `moveAI` plays one atomic move at a
* time, which can leave the state tentative (`toSave` would refuse to persist it); the
* platform's bot driver and `dropPlayer` auto-play both require committed states, so we
* keep playing until the turn commits.
*/
export function moveAI(G: GameState, player: number): GameState {
for (let i = 0; i < 500 && !engine.ended(G) && G.currentPlayers.includes(player); i++) {
G = engine.moveAI(G, player);
if (G.newTurn !== false) {
return G;
}
}
// Safety net — should be unreachable (Pass is always available in the move phase
// and commits the turn). The state is consistent (every atomic move was legal and
// logged), it just did not reach a turn boundary; persisting it keeps the game
// going instead of wedging it. Shout so a would-be livelock is visible in the
// server logs instead of being silently masked.
console.error(
`moveAI: force-committing after 500 moves without reaching a turn boundary (player ${player}, phase ${G.phase}, round ${G.round})`
);
G.newTurn = true;
return G;
}
export function rankings(G: GameState) {
const sortedPlayers = cloneDeep(G.players)
@ -53,7 +123,13 @@ export function replay(G: GameState) {
G.players[i].name = oldPlayers[i].name;
}
for (const move of oldG.log.filter((event) => event.type === 'move')) {
// The visible log freezes during the bid phase: bids and bid-phase loans go to
// `G.hiddenLog` and are only flushed to `G.log` when the accept/decline phase
// starts. A state saved mid-bid therefore keeps its newest moves in `hiddenLog`,
// and whenever `hiddenLog` is non-empty it holds exactly the moves made after the
// last visible entry, in order — so replaying the visible log followed by the
// hidden log reproduces the state faithfully.
for (const move of [...oldG.log, ...(oldG.hiddenLog ?? [])].filter((event) => event.type === 'move')) {
asserts<LogMove>(move);
G = engine.move(G, move.move, move.player);
@ -69,7 +145,35 @@ export function round(G: GameState) {
export async function dropPlayer(G: GameState, player: number) {
G.players[player].isDropped = true;
engine.nextPlayer(G);
// Auto-play only the dropped player's own pending decision, if any. Everything
// else — in particular the other simultaneous bidders' turns during an auction —
// stays untouched: from here on the engine itself skips dropped players
// (`nextPlayer` recursion, the `!isDropped` filters in the auction logic).
if (G.currentPlayers.includes(player)) {
switch (G.phase) {
case Phase.Bid:
// A dropped bidder bids nothing (also covers the additional-bid round)
G = engine.move(G, { name: MoveName.Bid, data: true, extraData: { price: 0 } }, player);
break;
case Phase.AcceptDecline:
// A dropped auctioneer accepts the highest bid (Accept is always
// available; Decline requires enough money to pay the bid)
G = engine.move(G, { name: MoveName.Accept, data: G.highestBidders[0] }, player);
break;
default:
// Move phase: the dropped player simply passes, which advances the
// turn through the regular path (upkeep, next player's actions, ...)
G = engine.move(G, { name: MoveName.Pass, data: true }, player);
break;
}
}
// Dropping a player always yields a committed state: tentative states are never
// persisted, so `G` was committed to begin with, and the auto-played moves above
// (Bid / Accept / Pass) are all turn-boundary moves.
G.newTurn = true;
return G;
}
@ -92,12 +196,19 @@ export function logLength(G: GameState, _player?: number) {
export function logSlice(G: GameState, options?: { player?: number; start?: number; end?: number }) {
const stripped = engine.stripSecret(G, options?.player);
return {
// The full (stripped) state. This is how the acting player's viewer receives
// tentative states: they are never persisted or broadcast, only returned in the
// move response's log slice.
state: stripped,
log: stripped.log.slice(options?.start, options?.end),
availableMoves:
options?.end === undefined
? stripped.players.map((pl) => pl.availableMoves)
: engine
.stripSecret(replay({ ...G, log: G.log.slice(0, options!.end) }), options!.player)
// Replaying a *truncated* log reconstructs a historical state, so
// the hidden log (whose moves all come after the full visible log)
// must not be appended to it.
.stripSecret(replay({ ...G, log: G.log.slice(0, options!.end), hiddenLog: [] }), options!.player)
.players.map((pl) => pl.availableMoves),
};
}

View file

@ -10,7 +10,7 @@
"husky": "^5.0.9",
"lint-staged": "^10.5.4",
"prettier": "^2.2.1",
"prettier-plugin-organize-imports": "^1.1.1",
"prettier-plugin-organize-imports": "^3.2.4",
"typescript": "^4.1.5"
},
"lint-staged": {

18409
pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,27 @@
packages:
- 'viewer'
- 'engine'
# Dependency build scripts are not needed: everything installs and builds with them
# skipped (core-js/ejs postinstalls are ads, @parcel/watcher ships prebuilds, yorkie
# is superseded by husky). Explicit so pnpm doesn't error on unreviewed builds.
allowBuilds:
'@parcel/watcher': false
core-js: false
ejs: false
nodent-runtime: false
yorkie: false
# vue2 project: without this, pnpm auto-installs @vue/cli's optional @vue/compiler-sfc
# (vue 3) peer and the cli-plugin-typescript shim crashes the viewer build (CI-only,
# fresh installs). vue-template-compiler is the correct vue2 path.
autoInstallPeers: false
# 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
# hoist, where EITHER 3.5.41 (works) or vue 2.7's 2.7.16 (legacy shape,
# crashes the build) may win depending on layout. Pin it explicitly.
packageExtensions:
'@vue/cli-plugin-typescript':
dependencies:
'@vue/compiler-sfc': ^3.5.41

View file

@ -1,6 +1,6 @@
{
"name": "container-viewer",
"version": "1.1.6",
"version": "2.0.0",
"repository": {
"type": "git",
"url": "git+https://github.com/boardgamers/container.git",
@ -29,6 +29,7 @@
"@types/events": "^3.0.0",
"@types/lodash": "^4.14.154",
"@types/mocha": "^5.2.4",
"@types/node": "^13.13.52",
"@typescript-eslint/parser": "^4.26.1",
"@vue/cli-plugin-babel": "~4.4.0",
"@vue/cli-plugin-typescript": "~4.4.0",
@ -36,6 +37,7 @@
"@vue/cli-service": "~4.4.0",
"@vue/test-utils": "^1.0.3",
"chai": "^4.1.2",
"csstype": "^3.2.3",
"eslint": "^7.28.0",
"eslint-plugin-vue": "^7.11.0",
"sass": "^1.26.5",

12309
viewer/pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -136,7 +136,7 @@ export default class DropZone extends Vue {
if (!this.availableMoves[MoveName.DomesticSale]?.find((c) => c.id === container.pieceId)) {
return false;
}
} else if (this.data.type != DropZoneType.FactoryStore) {
} else if (this.data.type != DropZoneType.FactoryStore) {
return false;
}
} else {
@ -148,7 +148,7 @@ export default class DropZone extends Vue {
if (!this.availableMoves[MoveName.DomesticSale]?.find((c) => c.id === container.pieceId)) {
return false;
}
} else if (this.data.type != DropZoneType.WarehouseStore) {
} else if (this.data.type != DropZoneType.WarehouseStore) {
return false;
}
} else {

View file

@ -551,9 +551,9 @@
<script lang="ts">
import { Vue, Component, Prop, Watch, Provide, ProvideReactive } from 'vue-property-decorator';
import { MoveName, ended, move as engineMove } from 'container-engine';
import type { GameState } from 'container-engine';
import type { GameState, Move } from 'container-engine';
import { EventEmitter } from 'events';
import { groupBy } from 'lodash';
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';
@ -633,17 +633,80 @@ export default class Game extends Vue {
totalBid: number = 0;
// Tentative-turn buffer: the moves of the current, not-yet-committed turn. The full
// buffer is (re)sent to the platform on every action and replayed server-side from
// the last committed state; undo simply pops the last move from it.
turnMoves: Move[] = [];
// Last committed state received from the platform. Undoing replays the shortened
// turn buffer from this state; when the buffer empties, the preview resets to it
// without any server call (the platform's saved state IS the turn start).
committedState: GameState | null = null;
@Watch('state', { immediate: true })
onStateChanged(state: GameState) {
if (state && state.newTurn !== false) {
// 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.
this.committedState = JSON.parse(JSON.stringify(state));
this.turnMoves = [];
} else if (state && !this.matchesTurnBuffer(state)) {
// Stale tentative echo: server responses can arrive after the buffer has
// changed (a move was undone — possibly down to an empty buffer, which
// re-emits nothing — or another move was made before the echo landed).
// Applying it would transiently show a phantom or regressed move; the echo
// for the current buffer (if any) will follow, so just drop this one.
return;
} else if (state) {
// Matching tentative echo: the server replayed exactly the current turn
// buffer, which the local preview already painted synchronously when the
// move was made (sendMove/undo). Replacing the state again would rebuild
// every piece while the drop animation is still in flight — the piece
// shows at its destination instantly AND tweens there from the drop point.
// Only play the move sound the replace would have played (local previews
// are silent, see replaceState's fake flag).
this.playMoveSound();
return;
}
this.replaceState(state, false);
}
/**
* A tentative state is a valid preview only if it is the server's replay of
* exactly the current turn buffer: the visible log must extend the committed log
* by precisely the buffered moves, in order. (All tentative moves are visible-log
* moves — bids and bid-phase loans go to the hidden log but commit immediately.)
*/
matchesTurnBuffer(state: GameState): boolean {
if (!this.committedState) {
return false;
}
const committedLength = this.committedState.log.length;
if (state.log.length !== committedLength + this.turnMoves.length) {
return false;
}
return state.log
.slice(committedLength)
.every((item, i) => item.type === 'move' && isEqual(item.move, this.turnMoves[i]));
}
replaceState(state: GameState, fake: boolean) {
this.G = JSON.parse(JSON.stringify(state));
this.createPieces();
if (!fake && this.preferences.sound && this.G?.log[this.G?.log.length - 1].type == 'move') {
if (!fake) {
this.playMoveSound();
}
}
playMoveSound() {
if (this.preferences.sound && this.G?.log[this.G?.log.length - 1].type == 'move') {
const move = (this.G?.log[this.G?.log.length - 1] as LogMove).move;
if (move.name == MoveName.Pass && this.G.currentPlayers.includes(this.player!)) {
(document.getElementById('notification')!.cloneNode(true) as HTMLAudioElement).play();
@ -1016,7 +1079,26 @@ export default class Game extends Vue {
}
undo() {
this.sendMove({ name: MoveName.Undo, data: true });
if (this.turnMoves.length === 0 || !this.committedState) {
return;
}
this.turnMoves.pop();
// Rebuild the local preview by replaying the shortened buffer from the last
// committed state (fake mode: no side effects like upkeep or game end).
let state: GameState = JSON.parse(JSON.stringify(this.committedState));
for (const move of this.turnMoves) {
state = engineMove(state, move, this.player!, true);
}
this.replaceState(state, true);
if (this.turnMoves.length > 0) {
// Resend the shortened turn so the server echoes the matching tentative state
this.emitter.emit('move', [...this.turnMoves]);
}
// Empty buffer: nothing to send — nothing was ever persisted for this turn
}
loan(event) {
@ -1061,9 +1143,20 @@ export default class Game extends Vue {
}
sendMove(move) {
this.emitter.emit('move', move);
// Send the WHOLE turn so far: the platform is stateless between calls and
// replays the buffer from the last committed (saved) state.
this.turnMoves.push(move);
this.emitter.emit('move', [...this.turnMoves]);
this.replaceState(engineMove(this.G!, move, this.player!, true), true);
const preview = engineMove(this.G!, move, this.player!, true);
if (preview.newTurn !== false) {
// This move completed the turn — it can no longer be undone. The server
// persists and broadcasts the committed state.
this.turnMoves = [];
}
this.replaceState(preview, true);
}
gameEnded(G: GameState) {
@ -1184,10 +1277,8 @@ export default class Game extends Vue {
canUndo() {
if (!this.canMove) return false;
const currentPlayer = this.G!.players[this.player!];
const availableMoves = currentPlayer.availableMoves!;
return !!availableMoves[MoveName.Undo];
// Undo scope = the current tentative turn: anything still in the buffer
return this.turnMoves.length > 0;
}
canDecline() {
@ -1622,6 +1713,10 @@ text {
.modal-content {
border-radius: 5px;
background-color: #fefefe;
// Explicit text color: the platform's dark mode sets a light text color on the
// page, which would render white-on-light here (the modal keeps its own light
// backgrounds). Like the rest of the viewer, use fixed colors for both themes.
color: #212121;
margin: auto;
padding: 10px 20px 20px 20px;
border: 1px solid #888;

View file

@ -196,7 +196,7 @@ import DropZone from './DropZone.vue';
@Component({
components: {
DropZone,
}
},
})
export default class PlayerBoard extends Vue {
@Prop()
@ -233,7 +233,7 @@ export default class PlayerBoard extends Vue {
name += ' (Bid: $' + this.player.bid + ')';
}
} else if (this.ended) {
name += ' (Score: $' + (this.player.money) + ')';
name += ' (Score: $' + this.player.money + ')';
}
return name;

View file

@ -55,7 +55,7 @@
</template>
<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';
import type { PointCard as PointCardInfo } from 'container-engine'
import type { PointCard as PointCardInfo } from 'container-engine';
@Component
export default class PointCard extends Vue {

View file

@ -10,6 +10,5 @@
import { Vue, Component } from 'vue-property-decorator';
@Component
export default class LogButton extends Vue {
}
export default class LogButton extends Vue {}
</script>

View file

@ -17,7 +17,7 @@ import Piece from './Piece.vue';
@Component({
created(this: Container) {
this.pieceType = PieceType.Container;
}
},
})
export default class Container extends Mixins(Piece) {
@Prop()

View file

@ -7,8 +7,8 @@ import { Vue, Component, Prop } from 'vue-property-decorator';
const endDrag = () => this.endDrag();
const drag = (event: MouseEvent | TouchEvent) => this.drag(event);
this.htmlElement.addEventListener('mousedown', event => this.startDrag(event));
this.htmlElement.addEventListener('touchstart', event => this.startDrag(event));
this.htmlElement.addEventListener('mousedown', (event) => this.startDrag(event));
this.htmlElement.addEventListener('touchstart', (event) => this.startDrag(event));
this.svgElement.addEventListener('touchmove', drag);
this.svgElement.addEventListener('touchend', endDrag);
@ -28,7 +28,7 @@ import { Vue, Component, Prop } from 'vue-property-decorator';
this.$on('hook:beforeDestroy', () => this.svgElement.removeEventListener('mouseup', endDrag));
this.$on('hook:beforeDestroy', () => this.svgElement.removeEventListener('mousemove', drag));
});
}
},
})
export default class Draggable extends Vue {
@Prop()
@ -48,8 +48,7 @@ export default class Draggable extends Vue {
}
startDrag(evt: MouseEvent | TouchEvent) {
if (!this.canDrag)
return;
if (!this.canDrag) return;
this.dragging = true;
@ -87,7 +86,9 @@ export default class Draggable extends Vue {
endDrag() {
this.dragging = false;
if (Date.now() - this._dragStart! < 100) {
this.$nextTick(() => { this.$emit('fastClick', this); });
this.$nextTick(() => {
this.$emit('fastClick', this);
});
}
}
@ -99,7 +100,7 @@ export default class Draggable extends Vue {
const CTM = this.svgElement.getScreenCTM()!;
return {
x: ((evt as any).clientX - CTM.e) / CTM.a,
y: ((evt as any).clientY - CTM.f) / CTM.d
y: ((evt as any).clientY - CTM.f) / CTM.d,
};
}
}

View file

@ -13,7 +13,7 @@ import Piece from './Piece.vue';
@Component({
created(this: Factory) {
this.pieceType = PieceType.Factory;
}
},
})
export default class Factory extends Mixins(Piece) {
@Prop()

View file

@ -16,7 +16,7 @@ import Piece from './Piece.vue';
@Component({
created(this: LoanCard) {
this.pieceType = PieceType.Loan;
}
},
})
export default class LoanCard extends Mixins(Piece) {
@Prop()

View file

@ -6,7 +6,7 @@ import { PieceType, UIData } from '@/types/ui-data';
@Component({
created(this: Piece) {
this.$on('draggedTo', (coords: { x: number, y: number }) => {
this.$on('draggedTo', (coords: { x: number; y: number }) => {
[this.currentX, this.currentY] = [coords.x, coords.y];
this.$nextTick(() => {
@ -19,14 +19,14 @@ import { PieceType, UIData } from '@/types/ui-data';
},
beforeDestroy(this: Piece) {
this.onTransitionEnd();
}
},
})
export default class Piece extends Draggable {
@Prop({ default: () => ({ x: 20, y: 20, rotate: 0 }) })
targetState!: {
x: number,
y: number,
rotate: number
x: number;
y: number;
rotate: number;
};
@Prop()
@ -84,7 +84,7 @@ export default class Piece extends Draggable {
this.startTransitioning();
} else {
this.moving = true;
setTimeout(() => this.moving = false, 800);
setTimeout(() => (this.moving = false), 800);
}
}
@ -121,7 +121,7 @@ export default class Piece extends Draggable {
}
get elId() {
return this.dragging ? 'dragged' : (this.transitioning || this.moving ? 'moving' : undefined);
return this.dragging ? 'dragged' : this.transitioning || this.moving ? 'moving' : undefined;
}
}
</script>

View file

@ -12,8 +12,7 @@ import Piece from './Piece.vue';
@Component({
created(this: Warehouse) {
this.pieceType = PieceType.Warehouse;
}
},
})
export default class Warehouse extends Mixins(Piece) {
}
export default class Warehouse extends Mixins(Piece) {}
</script>

View file

@ -13,10 +13,14 @@ function launch(selector: string) {
} = {
state: null,
emitter: new EventEmitter(),
preferences: {
// 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
// toggles, platform preference pushes) would only paint on the next re-render.
preferences: Vue.observable({
sound: true,
disableHelp: false,
},
}),
};
const app = new Vue({
@ -25,7 +29,9 @@ function launch(selector: string) {
const item: EventEmitter = new EventEmitter();
params.emitter.on('move', (move: Move) => item.emit('move', move));
// The move payload is the whole current turn so far (an array of atomic moves),
// replayed by the engine wrapper from the last committed state.
params.emitter.on('move', (moves: Move[]) => item.emit('move', moves));
params.emitter.on('addLog', (data: string[]) => item.emit('addLog', data));
params.emitter.on('replaceLog', (data: string[]) => item.emit('replaceLog', data));
params.emitter.on('update:preference', (data: { name: string; value: any }) =>
@ -43,10 +49,21 @@ function launch(selector: string) {
app.$forceUpdate();
});
item.addListener('preferences', (data) => {
params.preferences = { ...params.preferences, ...data };
// Mutate (don't replace) the observable object so the update stays reactive
Object.assign(params.preferences, data);
app.$forceUpdate();
});
item.addListener('gamelog', (_) => item.emit('fetchState'));
item.addListener('gamelog', (logData) => {
if (logData?.data?.state) {
// Move responses carry the (possibly tentative) resulting state. Tentative
// states are never persisted or broadcast by the platform — this is the only
// way they reach the acting player's viewer.
params.state = logData.data.state;
app.$forceUpdate();
} else {
item.emit('fetchState');
}
});
return item;
}

View file

@ -26,11 +26,26 @@ function launchSelfContained(selector = '#app') {
playerIndex = AbstractJudge.currentPlayers[0];
}
emitter.on('move', async (move: Move) => {
console.log('move received', move);
gameState = execMove(gameState, move, playerIndex);
console.log('new game state', gameState);
emitter.on('move', async (moves: Move | Move[]) => {
console.log('moves received', moves);
// Mimic the platform: replay the whole turn buffer from the last committed
// state; only keep (persist) the result once the turn is committed.
let newState = cloneDeep(gameState);
for (const move of Array.isArray(moves) ? moves : [moves]) {
newState = execMove(newState, move, playerIndex);
}
console.log('new game state', newState);
if (newState.newTurn === false) {
// 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);
return;
}
gameState = newState;
emitter.emit('state', cloneDeep(strip ? stripSecret(gameState, playerIndex) : gameState));
let delay = 800;

View file

@ -1,13 +0,0 @@
import Vue, { VNode } from 'vue';
declare global {
namespace JSX {
// tslint:disable no-empty-interface
interface Element extends VNode {}
// tslint:disable no-empty-interface
interface ElementClass extends Vue {}
interface IntrinsicElements {
[elem: string]: any;
}
}
}

View file

@ -1,8 +1,9 @@
import { ContainerPiece, ShipPosition } from 'container-engine/src/gamestate';
import PieceComponent from '../components/pieces/Piece.vue';
import Vue from 'vue';
export interface UIData {
dragged?: PieceComponent | null;
/** The Piece component instance (Piece.vue) currently being dragged, if any */
dragged?: (Vue & { pieceType: PieceType; pieceId: string }) | null;
waitingAnimations: number;
}

View file

@ -0,0 +1,21 @@
import Calculator from '@/components/Calculator.vue';
import { shallowMount } from '@vue/test-utils';
import { expect } from 'chai';
describe('Calculator.vue', () => {
it('accumulates digits and emits the bid', () => {
const wrapper = shallowMount(Calculator);
const vm = wrapper.vm as any;
vm.add(1);
vm.add(2);
expect(vm.value).to.equal(12);
vm.del();
expect(vm.value).to.equal(1);
vm.bid();
expect(wrapper.emitted().bid![0]).to.deep.equal([1]);
expect(vm.value).to.equal(0);
});
});

View file

@ -1,13 +0,0 @@
import HelloWorld from '@/components/HelloWorld.vue';
import { shallowMount } from '@vue/test-utils';
import { expect } from 'chai';
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message';
const wrapper = shallowMount(HelloWorld, {
propsData: { msg },
});
expect(wrapper.text()).to.include(msg);
});
});

View file

@ -13,7 +13,7 @@
"sourceMap": true,
"resolveJsonModule": true,
"baseUrl": ".",
"types": ["webpack-env", "mocha", "chai"],
"types": ["webpack-env", "mocha", "chai", "node"],
"paths": {
"@/*": ["src/*"]
},

View file

@ -1,6 +1,29 @@
// The production deploy uploads ONLY dist/container-viewer.umd.min.js and
// dist/container-viewer.css — nothing else from dist/ is served. Any asset emitted
// as a separate file (dist/img/*.svg icons, dist/media/*.mp3 audio) would 404, so
// every static asset must be inlined into the bundles as a data URI.
const INLINE_ASSETS_LIMIT = 10 * 1024 * 1024;
module.exports = {
devServer: {
// For gitpod, it needs to be disabled
disableHostCheck: true,
},
chainWebpack: (config) => {
// vue-cli's svg rule uses plain file-loader (always emits files); replace it
// with url-loader so the icons are inlined. Reuse the url-loader already
// resolved for the images rule (it is not hoisted to our node_modules).
const urlLoader = config.module.rule('images').use('url-loader').get('loader');
config.module.rule('svg').uses.clear();
config.module.rule('svg').use('url-loader').loader(urlLoader).options({ limit: INLINE_ASSETS_LIMIT });
// Raise the inline threshold so audio (and any raster images) inline too
// instead of falling back to file-loader above 4 KiB.
for (const ruleName of ['images', 'media']) {
config.module
.rule(ruleName)
.use('url-loader')
.tap((options) => ({ ...options, limit: INLINE_ASSETS_LIMIT }));
}
},
};