diff --git a/packages/engine/package.json b/packages/engine/package.json index f2a4156..ee16e10 100644 --- a/packages/engine/package.json +++ b/packages/engine/package.json @@ -1,6 +1,6 @@ { "name": "outpost-engine", - "version": "0.3.0", + "version": "0.4.0", "description": "Unofficial Outpost rules engine for boardgamers.space", "license": "AGPL-3.0", "files": [ diff --git a/packages/engine/src/ai.ts b/packages/engine/src/ai.ts index 0aae616..7983da9 100644 --- a/packages/engine/src/ai.ts +++ b/packages/engine/src/ai.ts @@ -1,7 +1,7 @@ import { FACTORIES, PRODUCTION_DECKS, UPGRADE_SPECS } from "./data.js"; import { applyMove } from "./moves.js"; import { canBuyFactory, handCapacity, handValue, populationCost, populationMax, upgradeDiscount } from "./state.js"; -import type { GameState, Move, PlayerState, Upgrade } from "./types.js"; +import type { GameState, Move, PlayerState, TurnBuy, Upgrade } from "./types.js"; /** Pick a legal (and mildly sensible) move for the player, then apply it. */ export function moveAI(state: GameState, seat: number): GameState { @@ -90,32 +90,60 @@ function chooseAction(state: GameState, player: PlayerState): Move { return { action: "auction", marketIndex: bestIndex, bid: UPGRADE_SPECS[upgrade].price }; } - // 2. Recruit population while there are factories to man. - const unmanned = player.factories.length - (player.population + player.robots); - if (unmanned > 0 && player.population < populationMax(player) && cash >= populationCost(player)) { - return { action: "buyPopulation", count: 1, cards: choosePayment(player, populationCost(player)) }; - } + return chooseTurn(player); +} - // 3. Expand production while there are operators (or room) for it. - for (const type of ["titanium", "water", "ore"] as const) { - const cost = FACTORIES[type].cost; - if ( - canBuyFactory(player, type) && - cash >= cost && - player.factories.length < populationMax(player) + player.robots - ) { - if (type === "titanium" || cash >= cost + populationCost(player)) { - return { action: "buyFactory", factory: type, cards: choosePayment(player, cost) }; - } +/** Greedily assemble a whole turn (purchases + manning) as one composite endTurn move. */ +function chooseTurn(player: PlayerState): Move { + // Simulate the buys on a private copy so each step's card indices are + // relative to the hand as the engine will see it at that step. + const sim = JSON.parse(JSON.stringify(player)) as PlayerState; + const buys: TurnBuy[] = []; + const spend = (due: number): number[] => { + const cards = choosePayment(sim, due); + for (const i of [...cards].sort((a, b) => b - a)) { + sim.hand.splice(i, 1); } + return cards; + }; + + for (let guard = 0; guard < 100; guard++) { + const cash = handValue(sim); + + // 2. Recruit population while there are factories to man. + const unmanned = sim.factories.length - (sim.population + sim.robots); + if (unmanned > 0 && sim.population < populationMax(sim) && cash >= populationCost(sim)) { + const cards = spend(populationCost(sim)); + buys.push({ buy: "population", count: 1, cards }); + sim.population += 1; + continue; + } + + // 3. Expand production while there are operators (or room) for it. + const type = (["titanium", "water", "ore"] as const).find((t) => { + const cost = FACTORIES[t].cost; + return ( + canBuyFactory(sim, t) && + cash >= cost && + sim.factories.length < populationMax(sim) + sim.robots && + (t === "titanium" || cash >= cost + populationCost(sim)) + ); + }); + if (type) { + const cards = spend(FACTORIES[type].cost); + buys.push({ buy: "factory", factory: type, cards }); + sim.factories.push({ type, manned: false }); + continue; + } + break; } // 4. Man the most valuable factories and end the turn. - const operators = player.population + player.robots; - const manned = player.factories + const operators = sim.population + sim.robots; + const manned = sim.factories .map((factory, index) => ({ index, value: PRODUCTION_DECKS[factory.type].average })) .sort((a, b) => b.value - a.value) .slice(0, operators) .map((e) => e.index); - return { action: "endTurn", manned }; + return { action: "endTurn", buys, manned }; } diff --git a/packages/engine/src/auction.spec.ts b/packages/engine/src/auction.spec.ts index b0343d0..51a100d 100644 --- a/packages/engine/src/auction.spec.ts +++ b/packages/engine/src/auction.spec.ts @@ -1,8 +1,11 @@ import assert from "node:assert/strict"; import { test } from "node:test"; +import { UPGRADE_SPECS } from "./data.js"; import { applyMove, initGame } from "./moves.js"; -import { handValue, upgradeDiscount, victoryPoints } from "./state.js"; -import type { GameState, PlayerState, ProductionCard } from "./types.js"; +import { replay } from "./replay.js"; +import { handValue, publicMaxBid, upgradeDiscount, victoryPoints } from "./state.js"; +import { stripSecret } from "../wrapper.js"; +import type { GameState, PlayerState, ProductionCard, Upgrade } from "./types.js"; function fixedGame(): GameState { const state = initGame(3, {}, "auction-spec"); @@ -177,3 +180,50 @@ test("upgrade effects: outpost grants capacity, population max, free titanium fa assert.equal(player.factories.at(-1)?.manned, false); assert.equal(victoryPoints(player), before + 5); }); + +test("auction: true-value auto-passes are logged and replay identically (stripped too)", () => { + const state = initGame(3, {}, "autopass-replay-spec"); + const opener = state.activeSeat; + const order = state.purchaseOrder; + const weak = order[(order.indexOf(opener) + 1) % order.length] as number; + // Stay within hand capacity (10): the replayed round entry must not trigger a discard phase. + const richHand = (): ProductionCard[] => Array.from({ length: 10 }, () => ({ t: "water", v: 10 })); + const weakHand = (): ProductionCard[] => Array.from({ length: 8 }, () => ({ t: "water", v: 1 })); + // Hands must come from the round entry too, so the replayed game sees them. + const roundEntry = state.log.find((e) => e.type === "round"); + assert.ok(roundEntry && roundEntry.type === "round"); + for (const rec of roundEntry.produced) { + rec.cards = rec.player === weak ? weakHand() : richHand(); + } + for (const p of state.players) { + p.hand = richHand(); + } + (state.players[weak] as PlayerState).hand = weakHand(); + (state.players[weak] as PlayerState).settings.autoPassBids = true; + + const upgrade = state.market[0] as Upgrade; + const bid = UPGRADE_SPECS[upgrade].price; + // The regression needs the TRUE-VALUE branch: the public bound could still + // beat the bid, only the real hand value (8) cannot. + assert.ok(publicMaxBid(state, weak, upgrade) > bid); + assert.ok(handValue(state.players[weak] as PlayerState) < bid); + + applyMove(state, { action: "auction", marketIndex: 0, bid }, opener); + assert.ok(state.auction?.passed.includes(weak)); + const entry = state.log.at(-1); + assert.ok(entry?.type === "move" && entry.info?.autoPassed?.includes(weak)); + + applyMove(state, { action: "bidPass" }, state.auction?.activeBidder as number); + assert.equal(state.phase, "auctionPayment"); + assert.equal(state.auction?.highBidder, opener); + + const replayed = replay(state); + assert.equal(replayed.phase, "auctionPayment"); + assert.deepEqual(replayed.auction?.passed, state.auction?.passed); + + // A stripped log (weak player's values hidden from this viewer) must replay too. + const viewer = order[(order.indexOf(opener) + 2) % order.length] as number; + const replayedStripped = replay(stripSecret(state, viewer)); + assert.equal(replayedStripped.phase, "auctionPayment"); + assert.deepEqual(replayedStripped.auction?.passed, state.auction?.passed); +}); diff --git a/packages/engine/src/describe.ts b/packages/engine/src/describe.ts index 01c21a2..1b408f0 100644 --- a/packages/engine/src/describe.ts +++ b/packages/engine/src/describe.ts @@ -32,14 +32,20 @@ export function describeLogEntry(state: GameState, entry: LogEntry): string { return `${name} passes on the auction`; case "pay": return `${name} buys ${info?.upgrade ? UPGRADE_SPECS[info.upgrade].name : "the upgrade"} (paid ${info?.paid ?? 0})`; - case "buyFactory": - return `${name} builds a ${FACTORIES[move.factory] ? move.factory : "?"} factory (paid ${info?.paid ?? 0})`; - case "buyPopulation": - return `${name} recruits ${move.count} colonist(s) (paid ${info?.paid ?? 0})`; - case "buyRobots": - return `${name} buys ${move.count} robot(s) (paid ${info?.paid ?? 0})`; - case "endTurn": - return `${name} ends their turn (${move.manned.length} factories manned)`; + case "endTurn": { + const buys = (move.buys ?? []).map((buy) => { + switch (buy.buy) { + case "factory": + return `builds a ${FACTORIES[buy.factory] ? buy.factory : "?"} factory`; + case "population": + return `recruits ${buy.count} colonist(s)`; + case "robots": + return `buys ${buy.count} robot(s)`; + } + }); + const spent = buys.length > 0 ? `${buys.join(", ")} (paid ${info?.paid ?? 0}), then ` : ""; + return `${name} ${spent}ends their turn (${move.manned.length} factories manned)`; + } default: return `${name} moves`; } diff --git a/packages/engine/src/moves.spec.ts b/packages/engine/src/moves.spec.ts index f8f1fdb..eb0bf03 100644 --- a/packages/engine/src/moves.spec.ts +++ b/packages/engine/src/moves.spec.ts @@ -15,7 +15,11 @@ test("buy factory: water factory costs 20, joins unmanned", () => { { t: "water", v: 10 }, { t: "water", v: 10 }, ]; - applyMove(state, { action: "buyFactory", factory: "water", cards: [0, 1] }, state.activeSeat); + applyMove( + state, + { action: "endTurn", buys: [{ buy: "factory", factory: "water", cards: [0, 1] }], manned: [] }, + state.activeSeat + ); assert.equal(player.factories.length, 4); assert.equal(player.factories.at(-1)?.type, "water"); assert.equal(player.factories.at(-1)?.manned, false); @@ -28,10 +32,12 @@ test("buy factory: titanium requires heavy equipment, research requires laborato const state = initGame(3, {}, "buy-spec2"); const player = activePlayer(state); player.hand = [{ t: "water", v: 40 }]; - assert.throws(() => applyMove(state, { action: "buyFactory", factory: "titanium", cards: [0] }, state.activeSeat)); - assert.throws(() => applyMove(state, { action: "buyFactory", factory: "research", cards: [0] }, state.activeSeat)); + const buyIn = (factory: "titanium" | "research") => + ({ action: "endTurn", buys: [{ buy: "factory", factory, cards: [0] }], manned: [] }) as const; + assert.throws(() => applyMove(state, buyIn("titanium"), state.activeSeat)); + assert.throws(() => applyMove(state, buyIn("research"), state.activeSeat)); player.upgrades.heavyEquipment = 1; - applyMove(state, { action: "buyFactory", factory: "titanium", cards: [0] }, state.activeSeat); + applyMove(state, buyIn("titanium"), state.activeSeat); assert.equal(player.factories.at(-1)?.type, "titanium"); }); @@ -40,13 +46,21 @@ test("buy factory: new chemicals requires a research card in the payment", () => const player = activePlayer(state); player.hand = [{ t: "water", v: 60 }]; assert.throws(() => - applyMove(state, { action: "buyFactory", factory: "newChemicals", cards: [0] }, state.activeSeat) + applyMove( + state, + { action: "endTurn", buys: [{ buy: "factory", factory: "newChemicals", cards: [0] }], manned: [] }, + state.activeSeat + ) ); player.hand = [ { t: "water", v: 50 }, { t: "research", v: 12 }, ]; - applyMove(state, { action: "buyFactory", factory: "newChemicals", cards: [0, 1] }, state.activeSeat); + applyMove( + state, + { action: "endTurn", buys: [{ buy: "factory", factory: "newChemicals", cards: [0, 1] }], manned: [] }, + state.activeSeat + ); assert.equal(player.factories.at(-1)?.type, "newChemicals"); }); @@ -58,15 +72,35 @@ test("population: costs 10 (5 with ecoplants), capped by population max", () => { t: "water", v: 10 }, { t: "water", v: 10 }, ]; - applyMove(state, { action: "buyPopulation", count: 2, cards: [0, 1] }, state.activeSeat); - assert.equal(player.population, 5); - assert.throws(() => applyMove(state, { action: "buyPopulation", count: 1, cards: [0] }, state.activeSeat)); assert.equal(populationMax(player), 5); + // Over the cap (3 + 3 > 5) rejected atomically: nothing spent. + assert.throws(() => + applyMove( + state, + { action: "endTurn", buys: [{ buy: "population", count: 3, cards: [0, 1, 2] }], manned: [] }, + state.activeSeat + ) + ); + assert.equal(player.population, 3); + assert.equal(player.hand.length, 3); player.upgrades.ecoplants = 1; player.upgrades.nodule = 1; assert.equal(populationMax(player), 8); - applyMove(state, { action: "buyPopulation", count: 1, cards: [0] }, state.activeSeat); // 5 with ecoplants, 10 paid + // With ecoplants a colonist costs 5: two for one card, one more for another. + applyMove( + state, + { + action: "endTurn", + buys: [ + { buy: "population", count: 2, cards: [0] }, + { buy: "population", count: 1, cards: [0] }, + ], + manned: [], + }, + state.activeSeat + ); assert.equal(player.population, 6); + assert.equal(player.hand.length, 1); }); test("robots: require the upgrade and respect the robot limit", () => { @@ -76,23 +110,80 @@ test("robots: require the upgrade and respect the robot limit", () => { { t: "water", v: 10 }, { t: "water", v: 10 }, ]; - assert.throws(() => applyMove(state, { action: "buyRobots", count: 1, cards: [0] }, state.activeSeat)); + const buyRobot = { action: "endTurn", buys: [{ buy: "robots", count: 1, cards: [0] }], manned: [] } as const; + assert.throws(() => applyMove(state, buyRobot, state.activeSeat)); player.upgrades.robots = 1; assert.equal(robotMax(player), player.population); - applyMove(state, { action: "buyRobots", count: 1, cards: [0] }, state.activeSeat); + applyMove(state, buyRobot, state.activeSeat); assert.equal(player.robots, 1); }); +test("end turn: buys apply in order and manning covers factories bought this turn", () => { + const state = initGame(3, {}, "turn-buys-spec"); + const player = activePlayer(state); + player.hand = [ + { t: "water", v: 10 }, + { t: "water", v: 10 }, + { t: "water", v: 10 }, + ]; + // Buy a water factory (20, two cards) then a colonist (10, the remaining + // card, now at index 0), and man the new factory (index 3). + applyMove( + state, + { + action: "endTurn", + buys: [ + { buy: "factory", factory: "water", cards: [0, 1] }, + { buy: "population", count: 1, cards: [0] }, + ], + manned: [0, 1, 2, 3], + }, + state.activeSeat + ); + assert.equal(player.factories.length, 4); + assert.equal(player.population, 4); + assert.equal(player.hand.length, 0); + assert.equal(player.factories[3]?.manned, true); + const logged = state.log.at(-1); + assert.ok(logged?.type === "move" && logged.info?.paid === 30); +}); + +test("end turn: an illegal later step rejects the whole move without mutating", () => { + const state = initGame(3, {}, "turn-atomic-spec"); + const player = activePlayer(state); + player.hand = [ + { t: "water", v: 10 }, + { t: "water", v: 10 }, + ]; + const snapshot = JSON.stringify(state); + // First buy is legal on its own; the second (robots without the upgrade) is not. + assert.throws(() => + applyMove( + state, + { + action: "endTurn", + buys: [ + { buy: "factory", factory: "water", cards: [0, 1] }, + { buy: "robots", count: 1, cards: [0] }, + ], + manned: [], + }, + state.activeSeat + ) + ); + assert.equal(JSON.stringify(state), snapshot); +}); + test("end turn: mans the selected factories and passes the action turn on", () => { const state = initGame(3, {}, "turn-spec"); const first = state.activeSeat; const player = activePlayer(state); - applyMove(state, { action: "endTurn", manned: [0, 2] }, first); + applyMove(state, { action: "endTurn", buys: [], manned: [0, 2] }, first); assert.equal(player.factories[0]?.manned, true); assert.equal(player.factories[1]?.manned, false); assert.equal(player.factories[2]?.manned, true); assert.ok(state.activeSeat !== first); - assert.throws(() => applyMove(state, { action: "endTurn", manned: [] }, first)); + assert.throws(() => applyMove(state, { action: "endTurn", buys: [], manned: [] }, first)); }); test("end turn: cannot man more factories than operators", () => { @@ -100,7 +191,7 @@ test("end turn: cannot man more factories than operators", () => { const player = activePlayer(state); player.factories.push({ type: "ore", manned: false }); player.factories.push({ type: "ore", manned: false }); - assert.throws(() => applyMove(state, { action: "endTurn", manned: [0, 1, 2, 3, 4] }, state.activeSeat)); + assert.throws(() => applyMove(state, { action: "endTurn", buys: [], manned: [0, 1, 2, 3, 4] }, state.activeSeat)); }); test("discard phase: over-capacity players must discard down to the cap", () => { @@ -110,7 +201,7 @@ test("discard phase: over-capacity players must discard down to the cap", () => hoarder.hand = Array.from({ length: 13 }, () => ({ t: "ore" as const, v: 1 })); hoarder.hand.push({ t: "research", v: 9 }); // exempt from the cap for (let guard = 0; guard < 10 && state.round === 1; guard++) { - applyMove(state, { action: "endTurn", manned: [0, 1, 2] }, state.activeSeat); + applyMove(state, { action: "endTurn", buys: [], manned: [0, 1, 2] }, state.activeSeat); } assert.equal(state.round, 2); assert.equal(state.phase, "discard"); @@ -132,16 +223,22 @@ test("hardening: malformed moves are rejected without mutating state", () => { assert.throws(() => applyMove(state, "endTurn" as never, seat)); assert.throws(() => applyMove(state, [] as never, seat)); assert.throws(() => applyMove(state, { action: "unknown" } as never, seat)); - assert.throws(() => applyMove(state, { action: "buyFactory", factory: "moon", cards: [] } as never, seat)); - assert.throws(() => applyMove(state, { action: "buyPopulation", count: 1, cards: [99] } as never, seat)); - assert.throws(() => applyMove(state, { action: "buyPopulation", count: 1, cards: [0, 0] } as never, seat)); - assert.throws(() => applyMove(state, { action: "buyPopulation", count: 1.5, cards: [0] } as never, seat)); - assert.throws(() => applyMove(state, { action: "buyPopulation", count: 1, cards: [0.5] } as never, seat)); + const turn = (buys: unknown) => ({ action: "endTurn", buys, manned: [] }) as never; + assert.throws(() => applyMove(state, turn("everything"), seat)); + assert.throws(() => applyMove(state, turn([{ buy: "spaceElevator", cards: [] }]), seat)); + assert.throws(() => applyMove(state, turn([{ buy: "factory", factory: "moon", cards: [] }]), seat)); + assert.throws(() => applyMove(state, turn([{ buy: "population", count: 1, cards: [99] }]), seat)); + assert.throws(() => applyMove(state, turn([{ buy: "population", count: 1, cards: [0, 0] }]), seat)); + assert.throws(() => applyMove(state, turn([{ buy: "population", count: 1.5, cards: [0] }]), seat)); + assert.throws(() => applyMove(state, turn([{ buy: "population", count: 1, cards: [0.5] }]), seat)); + assert.throws(() => + applyMove(state, turn(Array.from({ length: 51 }, () => ({ buy: "population", count: 1, cards: [0] }))), seat) + ); assert.throws(() => applyMove(state, { action: "bid", amount: Infinity } as never, seat)); assert.throws(() => applyMove(state, { action: "bid", amount: "9" } as never, seat)); - assert.throws(() => applyMove(state, { action: "endTurn", manned: "all" } as never, seat)); - assert.throws(() => applyMove(state, { action: "endTurn", manned: [0] } as never, seat + 1)); - assert.throws(() => applyMove(state, { action: "endTurn", manned: [0] } as never, "0" as never)); + assert.throws(() => applyMove(state, { action: "endTurn", buys: [], manned: "all" } as never, seat)); + assert.throws(() => applyMove(state, { action: "endTurn", buys: [], manned: [0] } as never, seat + 1)); + assert.throws(() => applyMove(state, { action: "endTurn", buys: [], manned: [0] } as never, "0" as never)); assert.throws(() => applyMove(state, { action: "discard", cards: Array.from({ length: 10_000 }, (_, i) => i) } as never, seat) ); @@ -152,12 +249,12 @@ test("hardening: extra keys and __proto__ payloads are stripped before logging", const state = initGame(3, {}, "hardening-spec2"); const seat = state.activeSeat; const malicious = JSON.parse( - '{"action":"endTurn","manned":[0,1,2],"__proto__":{"polluted":true},"junk":"x","nested":{"a":1}}' + '{"action":"endTurn","buys":[],"manned":[0,1,2],"__proto__":{"polluted":true},"junk":"x","nested":{"a":1}}' ) as never; applyMove(state, malicious, seat); const logged = state.log.at(-1); assert.ok(logged?.type === "move"); - assert.deepEqual(logged.move, { action: "endTurn", manned: [0, 1, 2] }); + assert.deepEqual(logged.move, { action: "endTurn", buys: [], manned: [0, 1, 2] }); assert.equal(({} as { polluted?: boolean }).polluted, undefined); // The logged move is a fresh literal, not the network object. assert.notEqual(logged.move, malicious); diff --git a/packages/engine/src/moves.ts b/packages/engine/src/moves.ts index 324487b..f0c3eec 100644 --- a/packages/engine/src/moves.ts +++ b/packages/engine/src/moves.ts @@ -10,14 +10,13 @@ import { mustAutoPassBid, populationCost, populationMax, - publicMaxBid, robotMax, scores, setup, upgradeDiscount, } from "./state.js"; import { sanitizeMove } from "./sanitize.js"; -import type { GameState, Move, MoveInfo, PlayerState, ProductionCard, Upgrade } from "./types.js"; +import type { GameState, Move, MoveInfo, PlayerState, ProductionCard, TurnBuy, Upgrade } from "./types.js"; /** Safety valve: no sane game lasts anywhere near this long. */ export const MAX_ROUNDS = 200; @@ -31,6 +30,16 @@ export function setReplayMode(value: boolean): void { replayMode = value; } +// Seats the currently replayed move auto-passed out of the auction (from the +// logged MoveInfo). The live auto-pass check can use true hand values (the +// autoPassBids setting), which a stripped log cannot recompute, so replay +// applies the recorded seats verbatim instead. +let replayAutoPassed: number[] = []; + +export function setReplayAutoPassed(seats: number[]): void { + replayAutoPassed = seats; +} + export function initGame(players: number, options: Record, seed: string): GameState { const state = setup(players, options, seed); beginRound(state); @@ -203,15 +212,6 @@ export function applyMove(state: GameState, rawMove: Move | unknown, seat: numbe case "pay": info = movePay(state, move, seat, player); break; - case "buyFactory": - info = moveBuyFactory(state, move, seat, player); - break; - case "buyPopulation": - info = moveBuyPopulation(state, move, seat, player); - break; - case "buyRobots": - info = moveBuyRobots(state, move, seat, player); - break; case "endTurn": info = moveEndTurn(state, move, seat, player); break; @@ -220,7 +220,6 @@ export function applyMove(state: GameState, rawMove: Move | unknown, seat: numbe } state.moveCount += 1; - state.lastAction = move.action; state.log.push(info ? { type: "move", player: seat, move, info } : { type: "move", player: seat, move }); postMove(state, move); return state; @@ -295,8 +294,9 @@ function moveAuction( passed: [], activeBidder: seat, }; - advanceBidder(state); - return { upgrade }; + const autoPassed: number[] = []; + advanceBidder(state, autoPassed); + return autoPassed.length > 0 ? { upgrade, autoPassed } : { upgrade }; } function assertCanPayBid(player: PlayerState, upgrade: Upgrade, bid: number): void { @@ -319,7 +319,7 @@ function biddingOrder(state: GameState): number[] { return order.map((_, i) => order[(start + i) % order.length] as number); } -function advanceBidder(state: GameState): void { +function advanceBidder(state: GameState, autoPassed?: number[]): void { const auction = state.auction; if (!auction) { err("no auction in progress"); @@ -337,16 +337,14 @@ function advanceBidder(state: GameState): void { } const p = state.players[seat]; if (p && !p.dropped && !auction.passed.includes(seat)) { - // Auto-pass a bidder who can't beat the high bid. During replay the - // public bound is recomputed identically from the stripped log, but a - // true-value auto-pass (the autoPassBids setting) can't be — so in - // replay only the public bound is used, and the logged bidPass entries - // that true-value passes produced are skipped as already-applied. - const autoPass = replayMode - ? publicMaxBid(state, seat, auction.upgrade) <= auction.highBid - : mustAutoPassBid(state, seat); + // Auto-pass a bidder who can't beat the high bid (public bound, or true + // hand value when they opted into autoPassBids). The seats are recorded + // in the move's info so replay reproduces them verbatim — the true-value + // check cannot be recomputed from a stripped log. + const autoPass = replayMode ? replayAutoPassed.includes(seat) : mustAutoPassBid(state, seat); if (autoPass) { auction.passed.push(seat); + autoPassed?.push(seat); continue; } auction.activeBidder = seat; @@ -370,8 +368,9 @@ function moveBid(state: GameState, move: Move & { action: "bid" }, seat: number, assertCanPayBid(player, auction.upgrade, move.amount); auction.highBid = move.amount; auction.highBidder = seat; - advanceBidder(state); - return { upgrade: auction.upgrade }; + const autoPassed: number[] = []; + advanceBidder(state, autoPassed); + return autoPassed.length > 0 ? { upgrade: auction.upgrade, autoPassed } : { upgrade: auction.upgrade }; } function moveBidPass(state: GameState, _move: Move & { action: "bidPass" }, seat: number): MoveInfo { @@ -380,8 +379,9 @@ function moveBidPass(state: GameState, _move: Move & { action: "bidPass" }, seat err("not this player's turn to bid"); } auction.passed.push(seat); - advanceBidder(state); - return { upgrade: auction.upgrade }; + const autoPassed: number[] = []; + advanceBidder(state, autoPassed); + return autoPassed.length > 0 ? { upgrade: auction.upgrade, autoPassed } : { upgrade: auction.upgrade }; } function movePay(state: GameState, move: Move & { action: "pay" }, seat: number, player: PlayerState): MoveInfo { @@ -413,68 +413,50 @@ function movePay(state: GameState, move: Move & { action: "pay" }, seat: number, return { upgrade, paid }; } -function moveBuyFactory( - state: GameState, - move: Move & { action: "buyFactory" }, - seat: number, - player: PlayerState -): MoveInfo { - requireActionTurn(state, seat, player); - const type = move.factory; - const spec = FACTORIES[type]; - if (!canBuyFactory(player, type)) { - err(`cannot build ${type} factories`); +/** Apply one purchase step of a turn. Validates against the current state and mutates it; returns the amount paid. */ +export function applyTurnBuy(state: GameState, player: PlayerState, buy: TurnBuy): number { + switch (buy.buy) { + case "factory": { + const spec = FACTORIES[buy.factory]; + if (!canBuyFactory(player, buy.factory)) { + err(`cannot build ${buy.factory} factories`); + } + const indices = sanitizeIndices(buy.cards, player.hand.length, "buy factory"); + if (spec.needsResearchCard && !indices.some((i) => player.hand[i]?.t === "research")) { + err("buying a New Chemicals factory requires spending a research card"); + } + const paid = spendCards(state, player, indices, spec.cost); + player.factories.push({ type: buy.factory, manned: false }); + return paid; + } + case "population": { + if (!Number.isInteger(buy.count) || buy.count < 1) { + err("invalid population count"); + } + if (player.population + buy.count > populationMax(player)) { + err(`population limit is ${populationMax(player)}`); + } + const indices = sanitizeIndices(buy.cards, player.hand.length, "buy population"); + const paid = spendCards(state, player, indices, populationCost(player) * buy.count); + player.population += buy.count; + return paid; + } + case "robots": { + if (player.upgrades.robots === 0) { + err("requires the Robots upgrade"); + } + if (!Number.isInteger(buy.count) || buy.count < 1) { + err("invalid robot count"); + } + if (player.robots + buy.count > robotMax(player)) { + err(`robot limit is ${robotMax(player)}`); + } + const indices = sanitizeIndices(buy.cards, player.hand.length, "buy robots"); + const paid = spendCards(state, player, indices, ROBOT_COST * buy.count); + player.robots += buy.count; + return paid; + } } - const indices = sanitizeIndices(move.cards, player.hand.length, "buyFactory"); - if (spec.needsResearchCard && !indices.some((i) => player.hand[i]?.t === "research")) { - err("buying a New Chemicals factory requires spending a research card"); - } - const paid = spendCards(state, player, indices, spec.cost); - player.factories.push({ type, manned: false }); - return { paid }; -} - -function moveBuyPopulation( - state: GameState, - move: Move & { action: "buyPopulation" }, - seat: number, - player: PlayerState -): MoveInfo { - requireActionTurn(state, seat, player); - const count = move.count; - if (!Number.isInteger(count) || count < 1) { - err("invalid population count"); - } - if (player.population + count > populationMax(player)) { - err(`population limit is ${populationMax(player)}`); - } - const indices = sanitizeIndices(move.cards, player.hand.length, "buyPopulation"); - const paid = spendCards(state, player, indices, populationCost(player) * count); - player.population += count; - return { paid }; -} - -function moveBuyRobots( - state: GameState, - move: Move & { action: "buyRobots" }, - seat: number, - player: PlayerState -): MoveInfo { - requireActionTurn(state, seat, player); - if (player.upgrades.robots === 0) { - err("requires the Robots upgrade"); - } - const count = move.count; - if (!Number.isInteger(count) || count < 1) { - err("invalid robot count"); - } - if (player.robots + count > robotMax(player)) { - err(`robot limit is ${robotMax(player)}`); - } - const indices = sanitizeIndices(move.cards, player.hand.length, "buyRobots"); - const paid = spendCards(state, player, indices, ROBOT_COST * count); - player.robots += count; - return { paid }; } function moveEndTurn( @@ -484,6 +466,19 @@ function moveEndTurn( player: PlayerState ): MoveInfo { requireActionTurn(state, seat, player); + // A multi-step move must reject without mutating anything: dry-run the whole + // turn on a clone first (the state is JSON-serializable by invariant, and no + // step draws randomness, so the second run is identical). + runTurn(JSON.parse(JSON.stringify(state)) as GameState, seat, move); + return runTurn(state, seat, move); +} + +function runTurn(state: GameState, seat: number, move: Move & { action: "endTurn" }): MoveInfo { + const player = state.players[seat] as PlayerState; + let paid = 0; + for (const buy of move.buys) { + paid += applyTurnBuy(state, player, buy); + } const manned = sanitizeIndices(move.manned, player.factories.length, "endTurn"); if (manned.length > player.population + player.robots) { err(`only ${player.population + player.robots} operators available`); @@ -492,7 +487,7 @@ function moveEndTurn( factory.manned = manned.includes(i); }); player.done = true; - return {}; + return move.buys.length > 0 ? { paid } : {}; } export function dropPlayer(state: GameState, seat: number): GameState { diff --git a/packages/engine/src/replay.ts b/packages/engine/src/replay.ts index bb0e2e4..88590bb 100644 --- a/packages/engine/src/replay.ts +++ b/packages/engine/src/replay.ts @@ -1,4 +1,4 @@ -import { applyMove, enterDiscardPhase, setReplayMode } from "./moves.js"; +import { applyMove, enterDiscardPhase, setReplayAutoPassed, setReplayMode } from "./moves.js"; import { setup } from "./state.js"; import type { GameState, LogEntry } from "./types.js"; @@ -26,20 +26,16 @@ export function replay(state: GameState, options?: { to?: number }): GameState { if (entry.type === "round") { applyRoundEntry(replayed, entry); } else if (entry.type === "move") { - // The live game auto-passes bidders who provably can't beat the - // high bid without logging a move; replay reproduces those passes - // via advanceBidder, so it must NOT also apply the next real move - // out of turn. Skip a logged bidPass whose seat was already - // auto-passed (it's the same pass, just recorded differently). - const alreadyPassed = - entry.move.action === "bidPass" && replayed.auction?.passed.includes(entry.player) === true; - if (!alreadyPassed) { - applyMove(replayed, entry.move, entry.player); - } + // Seats the live game auto-passed during this move are recorded in + // its info; advanceBidder replays them verbatim (the true-value + // auto-pass cannot be recomputed from a stripped log). + setReplayAutoPassed(entry.info?.autoPassed ?? []); + applyMove(replayed, entry.move, entry.player); } } } finally { setReplayMode(false); + setReplayAutoPassed([]); } return replayed; } diff --git a/packages/engine/src/sanitize.ts b/packages/engine/src/sanitize.ts index 27259e8..321c3ab 100644 --- a/packages/engine/src/sanitize.ts +++ b/packages/engine/src/sanitize.ts @@ -1,5 +1,5 @@ import { FACTORY_TYPES } from "./types.js"; -import type { FactoryType, Move } from "./types.js"; +import type { FactoryType, Move, TurnBuy } from "./types.js"; // Moves arrive as untrusted JSON from the network and are stored verbatim in // the game log. Rebuild every move as a fresh literal with exactly the @@ -36,6 +36,38 @@ function intArray(value: unknown, label: string): number[] { return value.map((v) => int(v, `${label} entry`, 0, 10_000)); } +const MAX_BUYS = 50; + +function buyArray(value: unknown): TurnBuy[] { + if (value === undefined) { + return []; + } + if (!Array.isArray(value)) { + fail("buys must be an array"); + } + if (value.length > MAX_BUYS) { + fail("buys is too large"); + } + return value.map((raw): TurnBuy => { + const entry = record(raw); + switch (entry.buy) { + case "factory": { + const factory = entry.factory; + if (typeof factory !== "string" || !FACTORY_TYPES.includes(factory as FactoryType)) { + fail("unknown factory type"); + } + return { buy: "factory", factory: factory as FactoryType, cards: intArray(entry.cards, "cards") }; + } + case "population": + return { buy: "population", count: int(entry.count, "count", 1, 100), cards: intArray(entry.cards, "cards") }; + case "robots": + return { buy: "robots", count: int(entry.count, "count", 1, 100), cards: intArray(entry.cards, "cards") }; + default: + fail("unknown buy kind"); + } + }); +} + export function sanitizeMove(raw: unknown): Move { const move = record(raw); const action = move.action; @@ -57,19 +89,8 @@ export function sanitizeMove(raw: unknown): Move { return { action }; case "pay": return { action, cards: intArray(move.cards, "cards") }; - case "buyFactory": { - const factory = move.factory; - if (typeof factory !== "string" || !FACTORY_TYPES.includes(factory as FactoryType)) { - fail("unknown factory type"); - } - return { action, factory: factory as FactoryType, cards: intArray(move.cards, "cards") }; - } - case "buyPopulation": - return { action, count: int(move.count, "count", 1, 100), cards: intArray(move.cards, "cards") }; - case "buyRobots": - return { action, count: int(move.count, "count", 1, 100), cards: intArray(move.cards, "cards") }; case "endTurn": - return { action, manned: intArray(move.manned, "manned") }; + return { action, buys: buyArray(move.buys), manned: intArray(move.manned, "manned") }; default: fail(`unknown action ${action}`); } diff --git a/packages/engine/src/state.ts b/packages/engine/src/state.ts index dfb355c..a6b1c44 100644 --- a/packages/engine/src/state.ts +++ b/packages/engine/src/state.ts @@ -312,10 +312,6 @@ export function availableMoves(state: GameState, player?: number): string[] { if (state.market.length > 0) { moves.push("auction"); } - moves.push("buyFactory", "buyPopulation"); - if (p.upgrades.robots > 0) { - moves.push("buyRobots"); - } return moves; } default: diff --git a/packages/engine/src/types.ts b/packages/engine/src/types.ts index f4503c3..7dcf406 100644 --- a/packages/engine/src/types.ts +++ b/packages/engine/src/types.ts @@ -85,16 +85,25 @@ export interface AuctionState { activeBidder: number; } +/** + * A purchase step inside an endTurn move. Card indices are relative to the hand + * as it stands when the step applies (earlier steps have removed their cards). + */ +export type TurnBuy = + | { buy: "factory"; factory: FactoryType; cards: number[] } + | { buy: "population"; count: number; cards: number[] } + | { buy: "robots"; count: number; cards: number[] }; + +// A player's whole action turn (purchases + manning) is one endTurn move: the +// platform grants time per persisted move, so splitting a turn into many moves +// would farm extra time. Auctions stay separate moves (they interleave seats). export type Move = | { action: "discard"; cards: number[] } | { action: "auction"; marketIndex: number; bid: number } | { action: "bid"; amount: number } | { action: "bidPass" } | { action: "pay"; cards: number[] } - | { action: "buyFactory"; factory: FactoryType; cards: number[] } - | { action: "buyPopulation"; count: number; cards: number[] } - | { action: "buyRobots"; count: number; cards: number[] } - | { action: "endTurn"; manned: number[] }; + | { action: "endTurn"; buys: TurnBuy[]; manned: number[] }; export type LogEntry = | { type: "init"; players: number; seed: string; options: Record } @@ -114,6 +123,12 @@ export interface MoveInfo { paid?: number; upgrade?: Upgrade; discarded?: number; + /** + * Seats auto-passed out of the auction by this move (public bound or the + * autoPassBids setting). Replay applies these verbatim: the true-value check + * cannot be recomputed from a stripped log. + */ + autoPassed?: number[]; } export interface GameState { @@ -141,6 +156,4 @@ export interface GameState { moveCount: number; ended: boolean; messages: string[]; - /** Action of the most recently applied move (drives toSave checkpointing). */ - lastAction?: Move["action"]; } diff --git a/packages/engine/src/wrapper.spec.ts b/packages/engine/src/wrapper.spec.ts index f096f6d..76a1d22 100644 --- a/packages/engine/src/wrapper.spec.ts +++ b/packages/engine/src/wrapper.spec.ts @@ -98,9 +98,8 @@ test("dropPlayer removes the player from play and can end the game", async () => assert.equal(ranks.length, 3); }); -test("toSave persists only at checkpoints, not intermediate moves", () => { +test("toSave persists every state (the platform has no memory between moves)", () => { const state = initGame(3, {}, "tosave-spec"); - // Give everyone a comfortable hand so auctions/bids/buys are legal. for (const p of state.players) { p.hand = [ { t: "water", v: 10 }, @@ -111,42 +110,26 @@ test("toSave persists only at checkpoints, not intermediate moves", () => { { t: "water", v: 10 }, ]; } - // Opening an auction / bidding are intermediate: no save. + // Every move must be saved: bids come from different seats, and drops or + // settings changes also persist through toSave. const opener = state.activeSeat; applyMove(state, { action: "auction", marketIndex: 0, bid: 25 }, opener); - assert.equal(wrapper.toSave(state), undefined); + assert.equal(wrapper.toSave(state), state); const bidder = state.auction?.activeBidder as number; applyMove(state, { action: "bid", amount: 30 }, bidder); - assert.equal(wrapper.toSave(state), undefined); - // Everyone else passes until the auction resolves to a payment. + assert.equal(wrapper.toSave(state), state); let guard = 0; while (state.phase === "auction" && guard++ < 20) { applyMove(state, { action: "bidPass" }, state.auction?.activeBidder as number); } assert.equal(state.phase, "auctionPayment"); - // Resolve the auction: the winner pays -> checkpoint. - const winner = state.auction?.highBidder as number; - const hand = state.players[winner]?.hand ?? []; - applyMove(state, { action: "pay", cards: hand.map((_, i) => i) }, winner); - assert.ok(wrapper.toSave(state)); - // Buying a factory is intermediate: no save. - const me = state.players[state.activeSeat]; - if (me && me.hand.length > 0) { - const before = state.moveCount; - applyMove(state, { action: "buyFactory", factory: "ore", cards: me.hand.map((_, i) => i) }, state.activeSeat); - if (state.moveCount > before) { - assert.equal(wrapper.toSave(state), undefined); - } - } - // Ending the turn is a checkpoint. - applyMove(state, { action: "endTurn", manned: [] }, state.activeSeat); - assert.ok(wrapper.toSave(state)); + assert.equal(wrapper.toSave(state), state); }); -test("toSave always persists a finished game", () => { +test("toSave persists a finished game", () => { const state = play(initGame(4, {}, "tosave-end"), 100000); assert.ok(state.ended); - assert.ok(wrapper.toSave(state)); + assert.equal(wrapper.toSave(state), state); }); test("messages drain once", () => { diff --git a/packages/engine/wrapper.ts b/packages/engine/wrapper.ts index bc5433c..9be2fd9 100644 --- a/packages/engine/wrapper.ts +++ b/packages/engine/wrapper.ts @@ -148,20 +148,14 @@ export function playerSettings(data: GameState, player: number): Record + buy.buy === "factory" + ? `${RESOURCE_LABELS[buy.factory]} factory` + : buy.buy === "population" + ? `${buy.count} colonist${buy.count === 1 ? "" : "s"}` + : `${buy.count} robot${buy.count === 1 ? "" : "s"}` + ) + ); const total = $derived(store.pickTotal()); const pickCount = $derived(store.cardPick.length); const needsResearch = $derived(pending?.kind === "factory" && FACTORIES[pending.factory].needsResearchCard === true); @@ -78,6 +87,9 @@ Assign operators: {store.manningPick.length} / {me.population + me.robots} factories manned. Click the factory chips in your panel to toggle them. + {#if staged.length > 0} + Ending the turn also confirms: {staged.join(", ")}. + {/if} @@ -146,6 +158,14 @@ {/if} + {#if staged.length > 0} +
+ + Staged this turn: {staged.join(", ")} — sent when you end the turn (undo to open an auction). + + +
+ {/if}
Click a market upgrade to auction it, or a buy button and then the hand cards to pay with. diff --git a/packages/viewer/src/lib/store.svelte.ts b/packages/viewer/src/lib/store.svelte.ts index 53193dc..2a10bce 100644 --- a/packages/viewer/src/lib/store.svelte.ts +++ b/packages/viewer/src/lib/store.svelte.ts @@ -2,6 +2,7 @@ import { FACTORIES, UPGRADE_SPECS, applyMove, + applyTurnBuy, canBuyFactory, countingHandSize, describeLog, @@ -20,6 +21,7 @@ import { type GameState, type Move, type PlayerState, + type TurnBuy, type Upgrade, } from "outpost-engine"; import type { ViewerBridge } from "./bgs.svelte"; @@ -98,6 +100,12 @@ export class ViewerStore { manning = $state(false); manningPick = $state([]); + // Purchases staged this turn. They are only sent to the server as part of + // the endTurn move (the whole turn is one move); until then `draft` holds + // the live state with the staged buys applied, and it is what the UI shows. + turnBuys = $state([]); + private draft = $state(null); + constructor(private bridge: ViewerBridge) { bridge.on("state", (state) => this.setState(state)); bridge.on("player", ({ index }) => { @@ -113,7 +121,10 @@ export class ViewerStore { } get state(): GameState | null { - return this.replay.active ? this.replay.state : this.liveState; + if (this.replay.active) { + return this.replay.state; + } + return this.draft ?? this.liveState; } private setState(state: GameState): void { @@ -124,9 +135,36 @@ export class ViewerStore { this.cancel(); this.lastMoveAt = Date.now(); } + this.rebuildDraft(); this.bridge.replaceLog(this.logLines); } + // Re-apply the staged buys on top of the (new) live state; drop them when + // they no longer apply (turn is over, or the server state moved on). + private rebuildDraft(): void { + if (this.turnBuys.length === 0) { + this.draft = null; + return; + } + const s = this.liveState; + if (!s || s.ended || this.playerIndex === undefined || s.phase !== "actions" || s.activeSeat !== this.playerIndex) { + this.turnBuys = []; + this.draft = null; + return; + } + try { + const clone = JSON.parse(JSON.stringify(s)) as GameState; + const player = clone.players[this.playerIndex] as PlayerState; + for (const buy of this.turnBuys) { + applyTurnBuy(clone, player, buy); + } + this.draft = clone; + } catch { + this.turnBuys = []; + this.draft = null; + } + } + private onGamelog(payload: { start: number; end?: number; data: unknown }): void { const data = payload?.data as { log?: unknown[] } | undefined; const entries = Array.isArray(data?.log) ? (data.log as GameState["log"]) : []; @@ -173,7 +211,7 @@ export class ViewerStore { } get me(): PlayerState | null { - const s = this.liveState; + const s = this.draft ?? this.liveState; return s && this.playerIndex !== undefined ? (s.players[this.playerIndex] ?? null) : null; } @@ -328,7 +366,9 @@ export class ViewerStore { openAuction(marketIndex: number): void { const s = this.liveState; const upgrade = s?.market[marketIndex]; - if (!this.myActionTurn || upgrade === undefined) { + // Staged buys reference the current hand; an auction payment would shift + // those indices. Auction first, then stage purchases (undo re-enables it). + if (!this.myActionTurn || upgrade === undefined || this.turnBuys.length > 0) { return; } this.cancel(); @@ -462,23 +502,45 @@ export class ViewerStore { this.send({ action: "pay", cards: this.cardPick }); } + // Stage the purchase locally: it is only sent with the endTurn move. Card + // indices are relative to the draft hand, which is exactly how the engine + // applies the steps in order. confirmPending(): void { const pending = this.pending; - if (!pending || !this.pendingValid()) { + if (!pending || !this.pendingValid() || this.playerIndex === undefined) { return; } const cards = this.cardPick; - switch (pending.kind) { - case "factory": - this.send({ action: "buyFactory", factory: pending.factory, cards }); - break; - case "population": - this.send({ action: "buyPopulation", count: pending.count, cards }); - break; - case "robots": - this.send({ action: "buyRobots", count: pending.count, cards }); - break; + const buy: TurnBuy = + pending.kind === "factory" + ? { buy: "factory", factory: pending.factory, cards } + : pending.kind === "population" + ? { buy: "population", count: pending.count, cards } + : { buy: "robots", count: pending.count, cards }; + const base = this.draft ?? this.liveState; + if (!base) { + return; } + try { + const clone = JSON.parse(JSON.stringify(base)) as GameState; + applyTurnBuy(clone, clone.players[this.playerIndex] as PlayerState, buy); + this.draft = clone; + this.turnBuys = [...this.turnBuys, buy]; + } catch { + return; + } + this.cardPick = []; + this.pending = null; + } + + undoBuy(): void { + if (this.turnBuys.length === 0) { + return; + } + this.turnBuys = this.turnBuys.slice(0, -1); + this.cardPick = []; + this.pending = null; + this.rebuildDraft(); } confirmDiscard(): void { @@ -521,7 +583,10 @@ export class ViewerStore { if (!this.manning) { return; } - this.send({ action: "endTurn", manned: this.manningPick }); + const move: Move = { action: "endTurn", buys: this.turnBuys, manned: this.manningPick }; + this.turnBuys = []; + this.draft = null; + this.send(move); } cancel(): void {