powergrid/engine/wrapper.ts

450 lines
20 KiB
TypeScript

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 } from './src/gamestate';
import type { LogMove } from './src/log';
import { Move, MoveName } from './src/move';
import {
automation,
canManagePremoves,
isPremoveCommand,
PremoveCommand,
reconcileManualPlan,
runPremoves,
setPremoves,
} from './src/premoves';
import { asserts } from './src/utils';
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<GameState> {
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<string, unknown>): GameState {
if (G.players[player]) G.players[player].settings = { autoPassBids: settings.autoPassBids === 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<string, unknown> {
return { autoPassBids: G.players[player]?.settings?.autoPassBids === true };
}
function runAutomaticMoves(G: GameState, now: number): GameState {
// Premoves can finish upkeep and enter a new auction round; passing can enter
// Resources. Settle both in order without re-running them inside replay.
G = autoPassAuctions(G, now);
G = runPremoves(G, now);
G = autoPassAuctions(G, now);
return runPremoves(G, now);
}
/**
* 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<GameState> {
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<LogMove>(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 };
}
delete G.pendingMessages;
return G;
}
export function round(G: GameState): number {
return G.round;
}
// Ceiling on the moves auto-played for one dropped player's turn. Real turns resolve in
// a handful — the longest is a Resources phase bought one cube at a time — so this sits
// orders of magnitude above any legitimate turn and only ever trips on a stuck state.
const MAX_AUTO_MOVES = 1000;
export async function dropPlayer(G: GameState, playerNum: number): Promise<GameState> {
automation(G).liveUpdate = false;
const player = G.players[playerNum];
player.isDropped = true;
G.log.push({
type: 'event',
event: `Player ${playerNum} was dropped`,
});
if (player.availableMoves?.[MoveName.Pass]) {
G = engine.move(G, { name: MoveName.Pass, data: true }, playerNum);
} else {
let autoMoves = 0;
while (G.currentPlayers.includes(playerNum)) {
if (++autoMoves > MAX_AUTO_MOVES) {
// A state moveAI cannot advance would otherwise spin this loop forever,
// pinning a game-server worker at 100% CPU with no request ever
// returning. Fail loudly instead: a thrown error is recoverable and
// diagnosable, a hung worker is neither.
throw new Error(
`dropPlayer: player ${playerNum} is still current after ${MAX_AUTO_MOVES} auto-played ` +
`moves (phase ${G.phase}, round ${G.round}) — aborting to avoid an infinite loop`
);
}
G = engine.moveAI(G, playerNum);
}
}
// Dropping a player must always yield a committed state: `G` was committed to
// begin with (tentative states are never persisted), and the auto-play above ends
// either with a Pass or with the dropped player leaving currentPlayers — both
// commit. Force the flag anyway (it costs nothing) so an unexpected auto-play path
// can never leave the persisted state un-saveable.
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 });
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<GameState> {
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);
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);
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;
}