import { cloneDeep } from 'lodash'; import type { GameState } from './index'; import { createAnalysisScenario as sampleAnalysisScenario } from './src/analysis'; import { applyAnalysisMoney, isAnalysisMoneyCommand, SetAnalysisMoney } from './src/analysis-money'; import { autoPassAuctions } from './src/auction-auto-pass'; import { alreadyCreditedPowering, canReviseChoice } from './src/choice-revisions'; import * as engine from './src/engine'; import { playersSortedByScore } from './src/engine'; import { GameOptions, Phase } from './src/gamestate'; import type { LogMove } from './src/log'; import { Move, MoveName } from './src/move'; import { autoPassResourcesAndBuilding } from './src/phase-auto-pass'; import { automation, canManagePremoves, isPremoveCommand, PremoveCommand, reconcileManualPlan, runPremoves, setPremoves, } from './src/premoves'; import { asserts } from './src/utils'; export { achievementDefinitions, achievements } from './src/achievements'; export { MAX_ANALYSIS_MONEY } from './src/analysis-money'; export type { SetAnalysisMoney } from './src/analysis-money'; export { ended, scores, stripSecret } from './src/engine'; export async function init( nbPlayers: number, expansions: string[], options: GameOptions, seed?: string, creator?: number, context?: { preferredPlayerColors?: (string | null)[] } ): Promise { return engine.setup(nbPlayers, options, seed, undefined, undefined, context?.preferredPlayerColors); } export function setPlayerMetaData(G: GameState, player: number, metaData: { name: string }): GameState { G.players[player].name = metaData.name; return G; } export function setPlayerSettings(G: GameState, player: number, settings: Record): GameState { if (G.players[player]) G.players[player].settings = { autoPassBids: settings.autoPassBids === true, autoPassResources: settings.autoPassResources === true, autoPassBuilding: settings.autoPassBuilding === true, }; // The host settings endpoint only persists preferences: it does not advance // turns or clocks. Apply automation after the next committed game move. return G; } export function playerSettings(G: GameState, player: number): Record { return { autoPassBids: G.players[player]?.settings?.autoPassBids === true, autoPassResources: G.players[player]?.settings?.autoPassResources === true, autoPassBuilding: G.players[player]?.settings?.autoPassBuilding === true, }; } function runAutomaticMoves(G: GameState, now: number): GameState { if (G.newTurn === false || G.achievementAnalysis) return G; // Settle to a fixed point: queued powering can enter auctions, whose passes // can enter resources, whose passes can unlock another queued building turn. // Run submitted plans first so an automatic Pass cannot supersede them. for (let guard = 0; guard < MAX_AUTO_MOVES; guard++) { const before = G.log.length + (G.hiddenLog?.length ?? 0); G = advanceDroppedPlayers(G); G = runPremoves(G, now); G = autoPassAuctions(G, now); G = autoPassResourcesAndBuilding(G, now); const after = G.log.length + (G.hiddenLog?.length ?? 0); if (after === before) return G; } throw new Error('Automatic moves did not settle'); } /** * 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. Each move carries the wall-clock stamp given to it when it FIRST entered the * buffer, so successive replays of the same buffer tick the in-game clocks identically. */ export async function move( G: GameState, move: Move | Move[] | PremoveCommand | null | undefined, player: number ): Promise { if ((Array.isArray(move) ? move : [move]).some(isAnalysisMoneyCommand)) throw new Error('SetAnalysisMoney is only available in an analysis'); automation(G).liveUpdate = false; if (isPremoveCommand(move)) { setPremoves(G, move, player); return runAutomaticMoves(G, Date.now()); } const initialPhase = G.phase; const initialRound = G.round; const revision = canReviseChoice(G, move, player); const moves: Move[] = move == null ? [] : Array.isArray(move) ? move : [move]; // Saved choices from before history compaction have no block boundary. A // deterministic replay derives it without guessing from unrelated earlier Passes. if (revision && moves[0]?.name === MoveName.ReopenPowering && G.poweringChoices?.[player]?.logStart === undefined) G = replay(G); 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 }; } // Drive the per-player clocks from a single clock. Each move's `time` is the acting // client's own Date.now(), and browser clocks disagree — a player whose clock runs // fast would charge that skew to itself on every turn, inflating its timer toward the // whole game's elapsed time. This is the authoritative move processor and never runs // during a deterministic replay (`replay` calls `engine.move` directly), so stamping // the server clock here is safe: the stamp is written into the log and reused on // replay. The client `time` is preserved untouched so it can still reconcile the // turn buffer against this state's echo. One `now` for the whole buffer is enough — // a turn's atomic moves are one player's, so their internal gaps don't matter; the // stretch charged is from the previous turn's stamp to this one. const now = Date.now(); for (let i = 0; i < moves.length; i++) { const input = { ...moves[i] }; delete input.poweringClock; G = engine.move(G, { ...input, serverTime: now }, 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 right away (e.g. the only other players are dropped, or a // Building-phase move commits early because a market event followed it) — // would replay across the turn boundary and commit several turns for a single // increment. Any illegal move in the buffer throws wholesale; the platform // discards the state either way. 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'); } } if (G.newTurn !== false) { if (revision) automation(G).liveUpdate = true; else if (!alreadyCreditedPowering(G, player, initialPhase, initialRound)) automation(G).increments[player]++; reconcileManualPlan(G, player, initialPhase); G = revision ? autoPassAuctions(G, now) : runAutomaticMoves(G, now); } return G; } export function canMoveOutOfTurn(G: GameState, move: unknown, player: number): boolean { return canReviseChoice(G, move, player) || (isPremoveCommand(move) && canManagePremoves(G, player)); } export function isLiveUpdate(G: GameState): boolean { return G.automation?.liveUpdate === true; } export function timeIncrements(G: GameState): number[] { return G.automation?.increments || G.players.map(() => 0); } /** * 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; } /** Host-facing interactive policy; AI callers import the sampler from src/analysis. */ export function createAnalysisScenario(data: GameState, options: { player?: number; seed: string }): GameState { return sampleAnalysisScenario(data, { ...options, interactive: true }); } /** * 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 { automation(G).liveUpdate = false; const initialPhase = G.phase; const initialRound = G.round; for (let i = 0; i < 500 && !engine.ended(G) && G.currentPlayers.includes(player); i++) { G = engine.moveAI(G, player); if (G.newTurn !== false) { if (!alreadyCreditedPowering(G, player, initialPhase, initialRound)) automation(G).increments[player]++; return runAutomaticMoves(G, Date.now()); } } // Safety net — should be unreachable (every phase offers the AI a committing move: // Pass wherever it exists, and the choose/bid/discard prompts all commit by handing // control on or pushing a resolution event). 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): number[] { const sortedPlayers = playersSortedByScore(G); sortedPlayers.forEach((player, index) => { player.ranking = index + 1; if (index > 0) { const prev = sortedPlayers[index - 1]; if ( player.citiesPowered === prev.citiesPowered && player.money === prev.money && player.cities.length === prev.cities.length ) { player.ranking = prev.ranking; } } }); return G.players.map((pl) => sortedPlayers.find((spl) => pl.id === spl.id)!.ranking!); } export function factions(G: GameState): string[] { return G.players.map((pl) => pl.color ?? engine.playerColors[pl.id]); } export function replay(G: GameState, { to = Infinity }: { to?: number } = {}): GameState { const oldPlayers = G.players; const oldG = G; G = engine.setup( G.players.length, engine.reconstructionOptions(G.options, G.log), G.seed, undefined, undefined, G.setupPlayerColors ); for (let i = 0; i < oldPlayers.length && i < G.players.length; i++) { G.players[i].name = oldPlayers[i].name; G.players[i].settings = oldPlayers[i].settings ? { ...oldPlayers[i].settings } : undefined; } // The visible log freezes during a fastBid auction: the simultaneous bids (and // bid-phase passes) go to `G.hiddenLog` and are only flushed to `G.log` when the // last bid resolves the auction. A state saved mid-auction 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 a full // replay must run the visible log followed by the hidden log to reproduce the // state faithfully. Truncated replays (`to` inside the visible log) reconstruct // a historical state and must NOT append the hidden log. const items = to >= oldG.log.length ? [...oldG.log, ...(oldG.hiddenLog ?? [])] : oldG.log.slice(0, to); for (const move of items) { if (move.type === 'event') { if (move.analysisMoney) { applyAnalysisMoney(G, move.analysisMoney); G.log.push(cloneDeep(move)); } continue; } asserts(move); G = engine.move(G, move.move, move.player); } // Queue edits are private operational state, not game moves. Preserve them only // for a full reconstruction; historical replay positions have no future queue. if (to >= oldG.log.length && oldG.automation) G.automation = JSON.parse(JSON.stringify(oldG.automation)); if (to >= oldG.log.length) { // Reopening is operational state, like a premove queue: the superseded // powering actions are gone, so a full replay needs only this bounded state. // Completed choices carry their exact clock accounting on the final Pass. for (const [seat, choice] of Object.entries(oldG.poweringChoices ?? {})) { if (choice.logStart === undefined) continue; (G.poweringChoices ??= {})[Number(seat)] = JSON.parse(JSON.stringify(choice)); if (choice.round === G.round && choice.reopened) { const player = G.players[Number(seat)]; const saved = oldPlayers[Number(seat)]; player.totalTimeUsed = saved.totalTimeUsed; player.clockStartedAt = saved.clockStartedAt; player.lastMove = saved.lastMove; } } if (oldG.revisedPowering) G.revisedPowering = { ...oldG.revisedPowering }; } if (oldG.achievementAnalysis) G.achievementAnalysis = true; delete G.pendingMessages; return G; } export function round(G: GameState): number { return G.round; } // Bound the entire dropped-seat chain, not just one seat: setup may hand control // to several dropped players, or return to the first seat when auctions begin. const MAX_AUTO_MOVES = 1000; function advanceDroppedPlayers(G: GameState): GameState { if (engine.ended(G)) return G; if (G.players.every((player) => player.isDropped)) { // There is nobody left to receive control. Do not try to play an entire // game with dropped seats (some turn selectors intentionally retain one). G.phase = Phase.GameEnd; G.currentPlayers = []; G.players.forEach((player) => (player.availableMoves = null)); G.newTurn = true; return G; } for (let count = 0; ; count++) { const seat = G.currentPlayers.find((id) => G.players[id].isDropped); if (engine.ended(G) || seat === undefined) return G; if (count >= MAX_AUTO_MOVES) throw new Error(`Dropped players are still current after ${MAX_AUTO_MOVES} auto-played moves`); // Use the engine directly: wrapper.moveAI would recursively run this // automation and credit time increments to an abandoned seat. G = G.players[seat].availableMoves?.[MoveName.Pass] ? engine.move(G, { name: MoveName.Pass, data: true }, seat) : engine.moveAI(G, seat); } } export async function dropPlayer(G: GameState, playerNum: number): Promise { automation(G).liveUpdate = false; const player = G.players[playerNum]; player.isDropped = true; G.log.push({ type: 'event', event: `Player ${playerNum} was dropped`, }); // Off-turn drops only mark the seat. Automatic play starts when a dropped // seat becomes current, including after another player's later setup pick. G.newTurn = true; return runAutomaticMoves(G, Date.now()); } export function currentPlayer(G: GameState): number[] { return G.currentPlayers; } export function messages(G: GameState) { const messages = G.pendingMessages ?? []; delete G.pendingMessages; return { messages, data: G, }; } export function logLength(G: GameState, _player?: number): number { return G.log.length; } export function logSlice(G: GameState, options?: { player?: number; start?: number; end?: number }) { const stripped = engine.stripSecret(G, options?.player); // `stripSecret` only leaves a player's own `availableMoves` intact for the index it // is given; everyone else is blanked to `{}`. The platform's move route is // logged-in and always passes the mover's index, but `GET /gameplay/:id/log` is not // — it derives the index with `findIndex`, which yields **-1** whenever the user // cannot be resolved. Handing back a `state` built that way tells the acting // player's viewer they have no moves: the board renders and nothing is clickable // until they re-enter the game (which takes the `fetchState` path instead). // // That blanking predates the tentative-turn model and was harmless while the viewer // ignored this payload. Now that the viewer adopts `state` from it, only offer the // state when we actually know whose it is; without it `launch.ts` falls back to // `fetchState`, which is exactly the old behaviour. const playerKnown = options?.player != undefined && options.player >= 0; 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: playerKnown ? stripped : undefined, log: stripped.log.slice(options?.start, options?.end), availableMoves: options?.end === undefined ? stripped.players.map((pl) => pl.availableMoves) : engine .stripSecret(replay(G, { to: options.end }), options!.player) .players.map((pl) => pl.availableMoves), }; } export function createAnalysis(data: GameState, { to }: { to: number; sourceEnded: boolean }): GameState { if (!Number.isInteger(to) || to < 0 || to > data.log.length) throw new Error('Invalid history position'); const copy = replay(JSON.parse(JSON.stringify(data)), { to }); copy.achievementAnalysis = true; delete copy.automation; for (const player of copy.players) { player.isDropped = false; player.isAI = false; } copy.newTurn = true; return copy; } export async function analysisMove( data: GameState, input: Move | SetAnalysisMoney | (Move | SetAnalysisMoney)[], player: number ): Promise { const buffer = Array.isArray(input) ? input : [input]; if (buffer.some(isAnalysisMoneyCommand)) { if (buffer.length !== 1) throw new Error('Analysis money edits must be sent alone'); if (data.newTurn === false) throw new Error('Analysis money edits require a committed state'); if (engine.ended(data)) throw new Error('Cannot edit money in an ended analysis'); if ( !Number.isSafeInteger(player) || !data.players[player] || !data.currentPlayers.includes(player) || data.players[player].isDropped ) throw new Error('Only an active player can edit analysis money'); const command = buffer[0] as SetAnalysisMoney; const copy = cloneDeep(data); copy.achievementAnalysis = true; const previous = copy.players[command.data?.player]?.money; applyAnalysisMoney(copy, command.data); copy.log.push({ type: 'event', event: `Analysis: player ${command.data.player} money changed from ${previous} to ${command.data.money}`, analysisMoney: { ...command.data }, }); return copy; } data = cloneDeep(data); data.achievementAnalysis = true; if (isPremoveCommand(input)) throw new Error('Premoves are not available in an analysis'); delete data.automation; // Deliberately bypass the live wrapper: clearing premoves alone does not // suppress preference/public-money auto-passes. engine.move still performs // mandatory auction resolution, upkeep and phase transitions. data.players.forEach((seat) => { seat.isAI = false; seat.isDropped = false; }); const moves = buffer as Move[]; if (!moves.length) return { ...data, newTurn: false }; const now = Date.now(); for (let i = 0; i < moves.length; i++) { const atomic = { ...moves[i] }; delete atomic.poweringClock; data = engine.move(data, { ...atomic, serverTime: now }, player); if (data.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 data; }