import { cloneDeep, isEqual } from 'lodash'; import seedrandom from 'seedrandom'; import type { GameState } from './index'; import { availableMoves } from './src/available-moves'; import pointCards from './src/cards'; import { canReviseBid } from './src/choice-revisions'; import * as engine from './src/engine'; import { Phase } from './src/gamestate'; import type { LogMove } from './src/log'; import { isLoanReversal, Move, MoveName } from './src/move'; import { asserts } from './src/utils'; export async function init(nbPlayers: number, expansions: string[], options: {}, seed?: string): Promise { return engine.setup( nbPlayers, expansions.includes('offshore-island') ? { ...options, offshoreIsland: true } : options, seed ); } export function setPlayerMetaData(G: GameState, player: number, metaData: { name: string }) { G.players[player].name = metaData.name; return G; } /** * 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, payload: Move | Move[] | null | undefined, player: number ): Promise { const moves: Move[] = payload == null ? [] : Array.isArray(payload) ? payload : [payload]; 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 }; } const compacted: Move[] = []; for (const action of moves) { if (isLoanReversal(compacted[compacted.length - 1], action)) compacted.pop(); else compacted.push(action); } const before = compacted.length < moves.length ? cloneDeep(G) : undefined; // Validate every requested move and the turn boundary before cancelling any pair. // Historical replay deliberately keeps the original atomic engine semantics. 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 before ? move(before, compacted, player) : 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 const canMoveOutOfTurn = canReviseBid; export const isLiveUpdate = (G: GameState): boolean => G.liveUpdate === true; export function factions(G: GameState) { return G.players.map((pl) => engine.playerColors[pl.id]); } export { achievementDefinitions, achievements } from './src/achievements'; 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) .sort((p1, p2) => { if (p1.money == p2.money) { return p1.containersOnIsland.length - p2.containersOnIsland.length; } else { return p1.money - p2.money; } }) .map((pl) => pl.id) .reverse(); return G.players.map((pl) => sortedPlayers.indexOf(pl.id) + 1); } /** * Rebuild the state from its seed and logged moves. * * With `to`, rebuild the earlier position after the first `to` visible log entries instead, * as BGS does to take back moves (undo against bots, admin replays); its undo checks that * `logLength` is then `to`. Hidden-log moves (sealed bids, bid-phase loans) all come after * the whole visible log, so they are left out: replaying to the visible length of a * running auction reopens it with no bids. `to` 0 gives the initial position, whose log * already holds the game start. */ export function replay(G: GameState, options?: { to?: number }): GameState { if (options?.to !== undefined) { const { to } = options; if (!Number.isInteger(to) || to < 0 || to > G.log.length) throw new Error('Invalid history position'); const copy = cloneDeep(G); const log = copy.log.slice(0, to); return replay({ ...copy, log, hiddenLog: [], // As saved back then: reached by a regular move (sealed-bid replacements, the only // live updates, never reach the visible log), its announcements already made. liveUpdate: log.some((entry) => entry.type === 'move') ? false : undefined, pendingMessages: undefined, }); } const oldPlayers = G.players; const oldG = G; G = engine.setup(G.players.length, G.options, G.seed); for (let i = 0; i < oldPlayers.length && i < G.players.length; i++) { G.players[i].name = oldPlayers[i].name; } // 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(move); G = engine.move(G, move.move, move.player); } G.liveUpdate = oldG.liveUpdate; // Reconstructing history must not announce old auctions again. if (oldG.pendingMessages) G.pendingMessages = [...oldG.pendingMessages]; else delete G.pendingMessages; return G; } export function round(G: GameState) { return G.round; } export async function dropPlayer(G: GameState, player: number) { G.liveUpdate = false; G.players[player].isDropped = true; // 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.BankDecision: while (G.phase === Phase.BankDecision && G.currentPlayers.includes(player)) G = engine.moveAI(G, player); break; 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; } export function currentPlayer(G: GameState) { return G.currentPlayers; } export function messages(G: GameState) { if (G.newTurn === false || !G.pendingMessages?.length) return { messages: [], data: G }; const data = { ...G }; delete data.pendingMessages; return { messages: [...G.pendingMessages], data }; } export function logLength(G: GameState, _player?: number) { return G.log.length; } 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 // 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), }; } export function createAnalysis(G: GameState, options: { to: number; sourceEnded: boolean }): GameState { if (options.to < 0 || options.to > G.log.length) throw new Error('Invalid history position'); const copy = replay({ ...cloneDeep(G), log: G.log.slice(0, options.to), hiddenLog: [] }); for (const player of copy.players) { player.isAI = false; player.isDropped = false; } copy.newTurn = true; return copy; } export function analysisView(G: GameState, options: { player: number; start?: number; end?: number }) { const state = cloneDeep(G); return { state, log: { state, log: state.log.slice(options.start, options.end), availableMoves: state.players.map((p) => p.availableMoves), }, }; } function observedCash(G: GameState, seed: string): number[] | undefined { if (G.analysisCash) return G.analysisCash; try { let replayed = engine.setup(G.players.length, G.options, seed); const factories = [ ...replayed.factoriesLeft, ...replayed.players.reduce((all, p) => all.concat(p.factories), [] as typeof replayed.factoriesLeft), ]; const containers = [ ...replayed.containersLeft, ...(replayed.offshoreBank?.containerLots.reduce( (all, lot) => all.concat(lot), [] as typeof replayed.containersLeft ) || []), ...replayed.players.reduce( (all, p) => all.concat(p.containersOnFactoryStore.map((c) => c.piece)), [] as typeof replayed.containersLeft ), ]; for (const p of replayed.players) { const color = G.players[p.id].factories[0].color; const factory = factories.find((f) => f.color === color && f.id === G.players[p.id].factories[0].id)!; factories.splice(factories.indexOf(factory), 1); const container = containers .filter((c) => c.color === color) .sort((a, b) => Number(a.id.slice(1)) - Number(b.id.slice(1)))[0]; containers.splice(containers.indexOf(container), 1); p.factories = [factory]; p.containersOnFactoryStore = [{ piece: container, price: 2, moved: false }]; p.actions = p.id === G.startingPlayer ? 2 : 0; } if (replayed.offshoreBank) { replayed.offshoreBank.initialContainerLots = cloneDeep(G.offshoreBank!.initialContainerLots); replayed.offshoreBank.containerLots = cloneDeep(G.offshoreBank!.initialContainerLots); for (const piece of replayed.offshoreBank.containerLots.reduce( (all, lot) => all.concat(lot), [] as typeof replayed.containersLeft )) { const i = containers.findIndex((c) => c.id === piece.id); if (i < 0) return undefined; containers.splice(i, 1); } } replayed.factoriesLeft = factories; replayed.containersLeft = containers; replayed.startingPlayer = G.startingPlayer; replayed.currentPlayers = [G.startingPlayer]; for (const p of replayed.players) p.availableMoves = replayed.currentPlayers.includes(p.id) ? availableMoves(replayed, p) : null; for (const entry of G.log) { if (entry.type === 'move') replayed = engine.move(replayed, entry.move, entry.player); } for (const p of replayed.players) { const actual = G.players[p.id]; for (const key of [ 'factories', 'warehouses', 'ship', 'containersOnFactoryStore', 'containersOnWarehouseStore', 'containersOnIsland', 'bankHolding', 'offshoreStats', ] as const) { if (!isEqual(p[key], actual[key])) return undefined; } } if (G.offshoreBank && !isEqual(G.offshoreBank, replayed.offshoreBank)) return undefined; return replayed.players.map((p, i) => p.money + (G.players[i].loans.length - p.loans.length) * 10); } catch { return undefined; } } export function createAnalysisScenario(G: GameState, { player, seed }: { player?: number; seed: string }): GameState { if (G.newTurn === false) throw new Error('Analysis requires a committed turn'); const copy = cloneDeep(engine.stripSecret(G, player)); const rng = seedrandom(seed); const cash = observedCash(G, seed); if (!cash || cash.some((amount) => !Number.isFinite(amount) || amount < 0)) throw new Error('Cannot reconstruct public cash balances safely'); copy.analysisCash = cash; const cards = cloneDeep(pointCards).filter((card) => !isEqual(card, copy.players[player!]?.pointCard)); copy.seed = seed; copy.hiddenLog = []; copy.log = []; copy.newTurn = true; for (const p of copy.players) { p.isAI = false; p.isDropped = false; delete p.finalScoreBreakdown; if (p.id !== player) { p.pointCard = cards.splice(Math.floor(rng() * cards.length), 1)[0]; if (cash[p.id] < p.bid + p.additionalBid) throw new Error('Public bids contradict reconstructed cash'); p.money = cash[p.id]; p.lastMove = null; if (!p.showBid) p.bid = G.phase === Phase.Bid && !copy.currentPlayers.includes(p.id) && p.id !== copy.auctioningPlayer ? Math.floor(rng() * (p.money + 1)) : 0; if (!p.showAdditionalBid) p.additionalBid = G.phase === Phase.Bid && copy.highestBidders.includes(p.id) && !copy.currentPlayers.includes(p.id) ? Math.floor(rng() * (p.money - p.bid + 1)) : 0; } } for (const p of copy.players) p.availableMoves = copy.currentPlayers.includes(p.id) ? availableMoves(copy, p) : null; return copy; } export function canLaunchAnalysisMode(G: GameState): boolean { return G.newTurn !== false && observedCash(G, 'analysis-eligibility') !== undefined; }