495 lines
17 KiB
TypeScript
495 lines
17 KiB
TypeScript
import crypto from "crypto";
|
|
import { set } from "lodash";
|
|
import Engine, { EngineOptions } from "./src/engine";
|
|
import { Command, Phase, Round } from "./src/enums";
|
|
import { chargeDecisionSeats, chargeFor, hasConcurrentCharges, waitingForCharges } from "./src/pending-charges";
|
|
import {
|
|
defaultAutoCharge,
|
|
defaultAutoChargeMaxPassedRoundLeech,
|
|
defaultAutoChargeTargetSpendablePower,
|
|
Settings,
|
|
} from "./src/player";
|
|
import type { PremoveCommand } from "./src/premove-types";
|
|
import {
|
|
assertOwnMove,
|
|
automation,
|
|
canQueue,
|
|
clearExpiredPremoves,
|
|
creditDecision,
|
|
playNextPremove,
|
|
premoveHistoryAfterReplay,
|
|
reconcileManualPremoves,
|
|
setPremoves,
|
|
} from "./src/premoves";
|
|
import assert from "./src/utils/assert";
|
|
|
|
export async function init(
|
|
nbPlayers: number,
|
|
expansions: string[],
|
|
options: EngineOptions,
|
|
seed?: string,
|
|
creator?: number
|
|
): Promise<Engine> {
|
|
if (!seed) {
|
|
seed = crypto.randomBytes(8).toString("base64");
|
|
}
|
|
if (creator && creator >= 0) {
|
|
options.creator = creator;
|
|
}
|
|
|
|
if (expansions.includes("lost-fleet")) {
|
|
options.lostFleet = true;
|
|
}
|
|
|
|
if (nbPlayers === 1) options = { ...options, automaSeed: crypto.randomBytes(24).toString("hex") };
|
|
const engine = new Engine([`init ${nbPlayers} ${seed}`], options);
|
|
engine.generateAvailableCommandsIfNeeded();
|
|
|
|
automove(engine);
|
|
|
|
return engine;
|
|
}
|
|
|
|
export function setPlayerMetaData(engine: Engine, player: number, metaData: { name: string }) {
|
|
engine.players[player].name = metaData.name;
|
|
|
|
return engine;
|
|
}
|
|
|
|
export function setPlayerSettings(
|
|
engine: Engine,
|
|
player: number,
|
|
settings: {
|
|
autoCharge?: string;
|
|
autoChargeTargetSpendablePower?: string;
|
|
autoChargeMaxPassedRoundLeech?: string;
|
|
autoIncome?: boolean;
|
|
autoBrainstone?: boolean;
|
|
itarsAutoChargeToArea3?: boolean;
|
|
}
|
|
) {
|
|
if ("autoCharge" in settings) {
|
|
set(
|
|
engine.players[player],
|
|
"settings.autoChargePower",
|
|
isNaN(settings.autoCharge as any) ? settings.autoCharge : Number(settings.autoCharge)
|
|
);
|
|
}
|
|
if ("autoChargeTargetSpendablePower" in settings) {
|
|
set(
|
|
engine.players[player],
|
|
"settings.autoChargeTargetSpendablePower",
|
|
Number(settings.autoChargeTargetSpendablePower)
|
|
);
|
|
}
|
|
if ("autoChargeMaxPassedRoundLeech" in settings) {
|
|
set(
|
|
engine.players[player],
|
|
"settings.autoChargeMaxPassedRoundLeech",
|
|
Number(settings.autoChargeMaxPassedRoundLeech)
|
|
);
|
|
}
|
|
if ("autoIncome" in settings) {
|
|
set(engine.players[player], "settings.autoIncome", settings.autoIncome);
|
|
}
|
|
if ("autoBrainstone" in settings) {
|
|
set(engine.players[player], "settings.autoBrainstone", settings.autoBrainstone);
|
|
}
|
|
if ("itarsAutoChargeToArea3" in settings) {
|
|
set(engine.players[player], "settings.itarsAutoChargeToArea3", settings.itarsAutoChargeToArea3);
|
|
}
|
|
|
|
return engine;
|
|
}
|
|
|
|
export function playerSettings(engine: Engine, player: number) {
|
|
return {
|
|
autoCharge: String(engine.players[player].settings?.autoChargePower ?? defaultAutoCharge),
|
|
autoChargeTargetSpendablePower: String(
|
|
engine.players[player].settings?.autoChargeTargetSpendablePower ?? defaultAutoChargeTargetSpendablePower
|
|
),
|
|
autoChargeMaxPassedRoundLeech: String(
|
|
engine.players[player].settings?.autoChargeMaxPassedRoundLeech ?? defaultAutoChargeMaxPassedRoundLeech
|
|
),
|
|
autoIncome: !!engine.players[player].settings?.autoIncome,
|
|
autoBrainstone: !!engine.players[player].settings?.autoBrainstone,
|
|
itarsAutoChargeToArea3: !!engine.players[player].settings?.itarsAutoChargeToArea3,
|
|
};
|
|
}
|
|
|
|
export function move(engine: Engine, move: string | PremoveCommand, player: number) {
|
|
if (!move) {
|
|
// Don't save
|
|
(engine as any).noSave = true;
|
|
return engine;
|
|
}
|
|
|
|
if (!(engine instanceof Engine)) {
|
|
engine = Engine.fromData(engine);
|
|
}
|
|
|
|
if (typeof move === "string") {
|
|
const command = move.trim().split(/\s+/)[1];
|
|
// Engine.move also reconstructs historical games containing resumeCharges.
|
|
// Reject new cancellations here, before touching history, resources or automation.
|
|
assert(command !== Command.ResumeCharges, "Wait for the pending charge decisions");
|
|
if (command === Command.WaitForCharges) {
|
|
assert(!waitingForCharges(engine, player), "Already waiting for charge decisions");
|
|
}
|
|
}
|
|
|
|
automation(engine).liveUpdate = false;
|
|
if (typeof move !== "string") {
|
|
assert(move?.type === "premoves", "Unknown move");
|
|
setPremoves(engine, move, player);
|
|
automove(engine);
|
|
return engine;
|
|
}
|
|
assertOwnMove(engine, move, player);
|
|
const revision = canReviseSealedBid(engine, move, player);
|
|
|
|
const round = engine.round;
|
|
const command = move.trim().split(/\s+/)[1];
|
|
const charge = hasConcurrentCharges(engine) && [Command.ChargePower, Command.Decline].includes(command as Command);
|
|
const waiting = hasConcurrentCharges(engine) && command === Command.WaitForCharges;
|
|
const phase = charge ? Phase.RoundLeech : engine.phase;
|
|
const backup = JSON.stringify(engine);
|
|
|
|
engine.move(move);
|
|
|
|
if (!engine.newTurn) {
|
|
// Try to complete the move for the player, e.g. if the player does not have auto brainstone
|
|
// but does have auto charge
|
|
|
|
const copy = Engine.fromData(JSON.parse(backup));
|
|
|
|
if (copy.autoMove(move, charge ? { player } : undefined)) {
|
|
engine = copy;
|
|
}
|
|
}
|
|
|
|
engine.generateAvailableCommandsIfNeeded();
|
|
|
|
if (engine.newTurn) {
|
|
if (revision || waiting) automation(engine).liveUpdate = true;
|
|
else creditDecision(engine, player, phase);
|
|
if (!waiting) reconcileManualPremoves(engine, player, round, phase);
|
|
afterMove(engine, round);
|
|
|
|
automove(engine);
|
|
}
|
|
|
|
return engine;
|
|
}
|
|
|
|
function afterMove(engine: Engine, oldRound: number) {
|
|
if (engine.round > oldRound && engine.round > 0) {
|
|
(engine as any).messages = [...((engine as any).messages || []), `Round ${engine.round}`];
|
|
}
|
|
}
|
|
|
|
export function automove(engine: Engine) {
|
|
let modified: boolean;
|
|
do {
|
|
modified = false;
|
|
let oldRound = engine.round;
|
|
|
|
const dropped = () =>
|
|
(hasConcurrentCharges(engine) ? chargeDecisionSeats(engine) : [engine.playerToMove]).find(
|
|
(seat) => engine.player(seat)?.dropped
|
|
);
|
|
while (!cancelled(engine) && !ended(engine) && dropped() !== undefined) {
|
|
assert(engine.autoMove(undefined, { autoPass: true, player: dropped() }), "Autopass not working");
|
|
|
|
afterMove(engine, oldRound);
|
|
modified = true;
|
|
oldRound = engine.round;
|
|
}
|
|
|
|
oldRound = engine.round;
|
|
|
|
while (engine.autoMove()) {
|
|
afterMove(engine, oldRound);
|
|
modified = true;
|
|
oldRound = engine.round;
|
|
}
|
|
clearExpiredPremoves(engine);
|
|
if (playNextPremove(engine)) {
|
|
afterMove(engine, oldRound);
|
|
modified = true;
|
|
}
|
|
} while (modified);
|
|
}
|
|
|
|
function canReviseSealedBid(data: Engine, move: unknown, player: number): boolean {
|
|
if (typeof move !== "string" || !data.players[player] || data.players[player].dropped || data.ended) return false;
|
|
const engine = data instanceof Engine ? data : Engine.fromData(data);
|
|
const pending = engine.sealedBidPendingSeats();
|
|
if (!pending?.length || pending.includes(player)) return false;
|
|
const command = engine.phase === Phase.SetupSilentBid ? "silentBid" : "preferenceBid";
|
|
return new RegExp(`^p${player + 1}\\s+${command}\\s+`).test(move.trim());
|
|
}
|
|
|
|
export function canMoveOutOfTurn(engine: Engine, move: string | PremoveCommand, player: number): boolean {
|
|
return (
|
|
canReviseSealedBid(engine, move, player) ||
|
|
(typeof move === "object" && move?.type === "premoves" && canQueue(engine, player))
|
|
);
|
|
}
|
|
|
|
export function isLiveUpdate(engine: Engine): boolean {
|
|
return engine.automation?.liveUpdate === true;
|
|
}
|
|
|
|
export function timeIncrements(engine: Engine): number[] {
|
|
return (engine.automation?.increments ?? engine.players.map(() => 0)).slice(
|
|
0,
|
|
engine.automa ? 1 : engine.players.length
|
|
);
|
|
}
|
|
|
|
export function ended(engine: Engine) {
|
|
return engine.ended;
|
|
}
|
|
|
|
export function cancelled(engine: Engine) {
|
|
return engine.ended && engine.round < Round.LastRound;
|
|
}
|
|
|
|
export function scores(engine: Engine) {
|
|
return engine.players.filter((pl) => !pl.isAutoma).map((pl) => pl.data.victoryPoints);
|
|
}
|
|
|
|
export function rankings(engine: Engine): number[] | undefined {
|
|
if (engine.automa) return [engine.players[0].data.victoryPoints >= engine.players[1].data.victoryPoints ? 1 : 2];
|
|
}
|
|
|
|
export function factions(engine: Engine) {
|
|
return engine.players.filter((pl) => !pl.isAutoma).map((pl) => pl.faction);
|
|
}
|
|
|
|
export async function replay(engine: Engine, { to = Infinity } = { to: Infinity }): Promise<Engine> {
|
|
if (!(engine instanceof Engine)) {
|
|
engine = Engine.fromData(engine);
|
|
}
|
|
|
|
const previous = automation(engine);
|
|
engine = engine.replayedTo(to, false);
|
|
engine.automation = {
|
|
...previous,
|
|
plans: premoveHistoryAfterReplay(previous.plans, engine.moveHistory.length),
|
|
liveUpdate: false,
|
|
};
|
|
|
|
automove(engine);
|
|
|
|
delete (engine as any).messages;
|
|
|
|
return engine;
|
|
}
|
|
|
|
export function moveAI(engine: Engine, player: number) {
|
|
if (!(engine instanceof Engine)) {
|
|
engine = Engine.fromData(engine);
|
|
}
|
|
|
|
if (
|
|
engine.ended ||
|
|
(hasConcurrentCharges(engine) ? !chargeDecisionSeats(engine).includes(player) : engine.playerToMove !== player)
|
|
) {
|
|
return engine;
|
|
}
|
|
|
|
const round = engine.round;
|
|
const phase = hasConcurrentCharges(engine) && chargeFor(engine, player) ? Phase.RoundLeech : engine.phase;
|
|
automation(engine).liveUpdate = false;
|
|
|
|
if (engine.moveAI(player)) {
|
|
creditDecision(engine, player, phase);
|
|
afterMove(engine, round);
|
|
engine.generateAvailableCommandsIfNeeded();
|
|
// resolve forced / trivial decisions (free leech, income, ...) so the game
|
|
// can advance to the next bot move
|
|
automove(engine);
|
|
}
|
|
|
|
return engine;
|
|
}
|
|
|
|
export async function dropPlayer(engine: Engine, player: number) {
|
|
engine = engine instanceof Engine ? engine : Engine.fromData(engine);
|
|
automation(engine).liveUpdate = false;
|
|
|
|
engine.players[player].dropped = true;
|
|
|
|
if (engine.round <= 0) {
|
|
engine.ended = true;
|
|
} else {
|
|
automove(engine);
|
|
}
|
|
|
|
return engine;
|
|
}
|
|
|
|
/**
|
|
* Whose move the platform should accept right now. Returns a single seat in sequential play, an
|
|
* ARRAY of seats during a simultaneous sealed-bid phase (Silent / Preference Split Auction - every
|
|
* seat still owing a bid may submit in any order), and `undefined` when the game is over or between
|
|
* phases. The platform normalizes both shapes (`Array.isArray(current) ? current : [current]`) and
|
|
* persists all of them to `game.currentPlayers`, which is the check its `/move` route authorizes
|
|
* against - returning the array is what lifts the "not your turn to play" rejection off-turn
|
|
* bidders used to hit. Same array convention as the other BGS games (Outpost / Power Grid).
|
|
*/
|
|
export function currentPlayer(engine: Engine): number | number[] | undefined {
|
|
// The game-server holds the game state as PLAIN JSON (Mongo stores plain objects, and every
|
|
// result crosses the worker boundary via JSON.parse(JSON.stringify(...))), so `engine` here is
|
|
// usually NOT an `Engine` instance. `sealedBidPendingSeats`/`playerToMove` are instance members -
|
|
// rehydrate first or they are undefined and this throws "sealedBidPendingSeats is not a function".
|
|
const e = engine instanceof Engine ? engine : Engine.fromData(engine);
|
|
if (hasConcurrentCharges(e) && e.newTurn) {
|
|
const seats = chargeDecisionSeats(e);
|
|
return seats.length === 1 ? seats[0] : seats.length ? seats : undefined;
|
|
}
|
|
const pending = e.sealedBidPendingSeats();
|
|
if (pending !== undefined) {
|
|
if (pending.length === 0) {
|
|
return undefined;
|
|
}
|
|
return pending.length === 1 ? pending[0] : pending;
|
|
}
|
|
return e.playerToMove;
|
|
}
|
|
|
|
export function toSave(engine: Engine) {
|
|
if (!engine.newTurn || (engine as any).noSave) {
|
|
return undefined;
|
|
}
|
|
return engine;
|
|
}
|
|
|
|
export function messages(engine: Engine) {
|
|
const messages = (engine as any).messages || [];
|
|
delete (engine as any).messages;
|
|
|
|
return {
|
|
messages,
|
|
data: engine,
|
|
};
|
|
}
|
|
|
|
/** `p3 silentBid ...` / `p3 preferenceBid ...` → seat index 2, or null for any other move. */
|
|
function sealedBidMovePlayer(move: string): number | null {
|
|
const match = /^p(\d+)\s+(?:silentBid|preferenceBid)\b/.exec(move.trim());
|
|
return match ? Number(match[1]) - 1 : null;
|
|
}
|
|
|
|
/**
|
|
* Hide other seats' sealed bids while a silent / preference-split auction round is being
|
|
* collected. The bid phases are sequential in-engine (one seat at a time), but nothing is
|
|
* derived from a bid until the last one lands, so sequential-but-hidden is equivalent to a
|
|
* simultaneous sealed round: the only thing other clients may learn is WHO has already bid
|
|
* (the UI shows that roster anyway), never the values or preference order.
|
|
*
|
|
* Masking is phase-scoped (same pattern as take6's face-down cards): once the engine leaves
|
|
* the bid phase the reveal has happened and the true moves/bids are public again - clients
|
|
* simply re-fetch the log. While the phase is in progress, a masked bid move is served as
|
|
* `pN silentBid` (well-formed command, no arguments), and the engine-level bid arrays keep
|
|
* only the `player` field for foreign seats so the "already submitted" roster keeps working.
|
|
*/
|
|
// BGS game-server: `hashSeed ?? !!stripSecret` decides whether the game seed gets sha256-hashed
|
|
// before init (hashed seeds show as base64 in the log instead of the game name). Gaia's only hidden
|
|
// information is the sealed-bid auction, which is player CHOICE, not seed-derived - no secret depends
|
|
// on the seed - so force the raw seed.
|
|
export const hashSeed = false;
|
|
|
|
export function stripSecret(engine: Engine, player?: number): Engine {
|
|
// Plain-JSON copy: this runs on both live Engine instances and the saved plain data, and the
|
|
// platform JSON-serializes whatever we return anyway.
|
|
const data = JSON.parse(JSON.stringify(engine)) as Engine;
|
|
delete data.options.automaSeed;
|
|
if (data.automa) delete data.automa.deck;
|
|
const state = automation(data);
|
|
state.plans = player === undefined || !state.plans[player] ? {} : { [player]: state.plans[player] };
|
|
|
|
if (data.phase !== Phase.SetupSilentBid && data.phase !== Phase.SetupPreferenceBid) {
|
|
return data;
|
|
}
|
|
|
|
data.silentAuctionBids = (data.silentAuctionBids ?? []).map((bid) =>
|
|
bid.player === player ? bid : ({ player: bid.player } as typeof bid)
|
|
);
|
|
data.preferenceSplitBids = (data.preferenceSplitBids ?? []).map((bid) =>
|
|
bid.player === player ? bid : ({ player: bid.player } as typeof bid)
|
|
);
|
|
data.moveHistory = data.moveHistory.map((move) => {
|
|
const bidder = sealedBidMovePlayer(move);
|
|
if (bidder === null || bidder === player) {
|
|
return move;
|
|
}
|
|
// Keep the seat + command so log rendering can still label the row, drop the arguments.
|
|
return move.trim().split(/\s+/).slice(0, 2).join(" ");
|
|
});
|
|
|
|
return data;
|
|
}
|
|
|
|
export function logLength(engine: Engine) {
|
|
return engine.moveHistory.length;
|
|
}
|
|
|
|
export function logSlice(engine: Engine, options?: { player?: number; start?: number; end?: number }) {
|
|
const stripped = stripSecret(engine, options?.player);
|
|
return {
|
|
state: stripped, // to remove later
|
|
log: stripped.moveHistory.slice(options?.start, options?.end),
|
|
availableMoves: engine.availableCommands, // todo: if end !== undefined, get the available moves from back then?
|
|
};
|
|
}
|
|
|
|
export function round(engine: Engine) {
|
|
return engine.round;
|
|
}
|
|
|
|
export function canLaunchAnalysisMode(data: Engine): boolean {
|
|
return (
|
|
data.round > 0 || [Phase.SetupBuilding, Phase.SetupBooster, Phase.BeginGame, Phase.EndGame].includes(data.phase)
|
|
);
|
|
}
|
|
|
|
export function createAnalysis(data: Engine, options: { to: number; sourceEnded: boolean }): Engine {
|
|
const source = Engine.fromData(JSON.parse(JSON.stringify(data)));
|
|
assert(options.to >= 1 && options.to <= source.moveHistory.length, "Choose a position after game setup");
|
|
const copy = source.replayedTo(options.to, false);
|
|
delete copy.automation;
|
|
delete copy.options.automaSeed;
|
|
if (copy.automa) delete copy.automa.deck;
|
|
delete (copy as any).messages;
|
|
for (const player of copy.players) {
|
|
player.dropped = false;
|
|
player.settings = new Settings();
|
|
}
|
|
copy.generateAvailableCommandsIfNeeded();
|
|
return copy;
|
|
}
|
|
|
|
export function analysisMove(data: Engine, command: string, player: number): Engine {
|
|
assert(typeof command === "string", "Premoves are not available in an analysis");
|
|
const copy = Engine.fromData(JSON.parse(JSON.stringify(data)));
|
|
assertOwnMove(copy, command, player);
|
|
copy.move(command);
|
|
copy.generateAvailableCommandsIfNeeded();
|
|
return copy;
|
|
}
|
|
|
|
export function analysisView(data: Engine, options: { player: number; start?: number; end?: number }) {
|
|
const copy = Engine.fromData(stripSecret(data, options.player));
|
|
copy.generateAvailableCommandsIfNeeded();
|
|
return {
|
|
state: copy,
|
|
log: {
|
|
state: copy,
|
|
log: copy.moveHistory.slice(options.start, options.end),
|
|
availableMoves: copy.availableCommands,
|
|
},
|
|
};
|
|
}
|