Prefer hand-capacity cards and preserve Research in auto-selection

This commit is contained in:
coyotte508 2026-10-01 16:05:35 +02:00
commit 79cc186c9b
10 changed files with 378 additions and 121 deletions

View file

@ -15,6 +15,7 @@
"lint": "oxlint",
"check": "pnpm test:locales && pnpm fmt:check && pnpm lint && pnpm tsc && pnpm test && pnpm build",
"test:browser": "node tests/protocol-smoke.mjs",
"test:selection": "node tests/card-selection-browser.mjs",
"test:tutorial": "pnpm --filter outpost-engine build && node --test tests/tutorial.spec.mjs",
"test:tutorial:browser": "node tests/tutorial-browser.mjs",
"preview:tutorial": "node tests/tutorial-preview.mjs",

View file

@ -1,6 +1,6 @@
{
"name": "outpost-engine",
"version": "0.10.19",
"version": "0.10.20",
"description": "Unofficial Outpost rules engine for boardgamers.space",
"license": "AGPL-3.0",
"files": [

View file

@ -2,6 +2,7 @@ import { FACTORIES, KICKER_SPECS, MEGA_CARDS, PRODUCTION_DECKS, UPGRADE_SPECS }
import { applyMove } from "./moves.js";
import {
auctionCard,
bestDiscard,
bestPayment,
canBuyFactory,
countingHandSize,
@ -126,23 +127,7 @@ function chooseExchange(state: GameState, seat: number, player: PlayerState): Mo
}
function chooseDiscard(player: PlayerState): Move {
const cap = handCapacity(player);
// Discard the cheapest counting cards until under the cap. A mega card
// counts as 4, so it is only discarded when nothing smaller suffices.
const counting = player.hand
.map((card, index) => ({ card, index, weight: card.m ? 4 : 1 }))
.filter(({ card }) => card.t !== "research" && card.t !== "microbiotics")
.sort((a, b) => a.card.v - b.card.v);
let size = counting.reduce((sum, e) => sum + e.weight, 0);
const picked: number[] = [];
for (const e of counting) {
if (size <= cap) {
break;
}
picked.push(e.index);
size -= e.weight;
}
return { action: "discard", cards: picked };
return { action: "discard", cards: bestDiscard(player) };
}
function chooseAction(state: GameState, player: PlayerState): Move {

View file

@ -0,0 +1,162 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { applyMove, initGame } from "./moves.js";
import { bestDiscard, bestPayment, countingHandSize, handCardSize } from "./state.js";
import type { ProductionCard } from "./types.js";
function playerWith(hand: ProductionCard[]) {
const player = initGame(3, {}, "card-selection").players[0]!;
player.hand = hand;
return player;
}
test("payment: spend a Mega before the same value in singles", () => {
const player = playerWith([
{ t: "water", v: 7 },
{ t: "water", v: 7 },
{ t: "water", v: 8 },
{ t: "water", v: 8 },
{ t: "water", v: 30, m: true },
]);
assert.deepEqual(bestPayment(player, 30), [4]);
assert.deepEqual(bestPayment(player, 7), [0]);
});
test("payment: prefer freeing hand capacity over spending exempt cards", () => {
const player = playerWith([
{ t: "research", v: 4 },
{ t: "microbiotics", v: 6 },
{ t: "water", v: 10 },
]);
assert.deepEqual(bestPayment(player, 10), [2]);
player.hand = [
{ t: "water", v: 30, m: true },
{ t: "titanium", v: 10 },
{ t: "titanium", v: 10 },
{ t: "titanium", v: 10 },
];
assert.deepEqual(bestPayment(player, 30), [0]);
});
test("payment: preserve Research for New Chemicals, including when research is required", () => {
const player = playerWith([
{ t: "research", v: 10 },
{ t: "microbiotics", v: 10 },
{ t: "research", v: 10 },
]);
assert.deepEqual(bestPayment(player, 10), [1]);
assert.deepEqual(bestPayment(player, 20, true), [0, 1]);
player.hand = [{ t: "microbiotics", v: 20 }];
assert.equal(bestPayment(player, 10, true), null);
});
test("payment: minimum overpayment takes precedence over card preferences", () => {
const player = playerWith([
{ t: "water", v: 30, m: true },
{ t: "research", v: 9 },
{ t: "microbiotics", v: 10 },
]);
assert.deepEqual(bestPayment(player, 9), [1]);
assert.deepEqual(bestPayment(player, 8), [1]);
assert.deepEqual(bestPayment(player, 0), []);
assert.equal(bestPayment(player, 50), null);
});
test("hand capacity: Megas count as four; Research and Microbiotics count as zero", () => {
const player = playerWith([
{ t: "water", v: 30, m: true },
{ t: "ore", v: 3 },
{ t: "research", v: 8 },
{ t: "microbiotics", v: 15 },
]);
assert.equal(countingHandSize(player), 5);
assert.deepEqual(player.hand.map(handCardSize), [4, 1, 0, 0]);
});
test("discard: free four slots with one Mega when that loses fewer credits", () => {
const player = playerWith([
{ t: "water", v: 30, m: true },
...Array.from({ length: 10 }, (): ProductionCard => ({ t: "titanium", v: 10 })),
{ t: "research", v: 1 },
{ t: "microbiotics", v: 1 },
]);
assert.equal(countingHandSize(player), 14);
assert.deepEqual(bestDiscard(player), [0]);
const retained = player.hand.filter((_, index) => !bestDiscard(player).includes(index));
assert.equal(countingHandSize({ ...player, hand: retained }), 10);
});
test("discard: keep a valuable Mega when a cheap single is enough", () => {
const player = playerWith([
{ t: "water", v: 30, m: true },
...Array.from({ length: 7 }, (_, index): ProductionCard => ({ t: "ore", v: index + 1 })),
{ t: "research", v: 1 },
]);
assert.deepEqual(bestDiscard(player), [1]);
player.hand = [{ t: "water", v: 30, m: true }];
assert.deepEqual(bestDiscard(player), []);
});
test("discard: the engine rejects a selection that leaves Megas over the limit", () => {
const state = initGame(3, {}, "mega-discard-limit");
const player = state.players[0]!;
player.hand = [
{ t: "water", v: 30, m: true },
{ t: "titanium", v: 44, m: true },
{ t: "newChemicals", v: 88, m: true },
{ t: "ore", v: 1 },
];
player.mustDiscard = true;
state.phase = "discard";
const before = structuredClone(state);
assert.throws(() => applyMove(state, { action: "discard", cards: [3] }, 0), /hand capacity/);
assert.deepEqual(state, before);
applyMove(state, { action: "discard", cards: bestDiscard(player) }, 0);
assert.ok(countingHandSize(player) <= 10);
});
test("payment: dynamic selection matches exhaustive subsets across amounts and research requirements", () => {
const player = playerWith([
{ t: "research", v: 7 },
{ t: "microbiotics", v: 7 },
{ t: "water", v: 30, m: true },
{ t: "water", v: 8 },
{ t: "titanium", v: 10 },
{ t: "research", v: 5 },
{ t: "ore", v: 2 },
{ t: "water", v: 0 },
]);
const subsets = Array.from({ length: 1 << player.hand.length }, (_, mask) =>
player.hand.flatMap((_, index) => (mask & (1 << index) ? [index] : []))
);
const score = (pick: number[]) => {
const cards = pick.map((index) => player.hand[index]!);
return [
cards.reduce((sum, card) => sum + card.v, 0),
-cards.reduce((sum, card) => sum + (card.t === "research" || card.t === "microbiotics" ? 0 : card.m ? 4 : 1), 0),
-cards.filter((c) => c.m).length,
cards.filter((c) => c.t === "research").length,
-cards.length,
];
};
const compare = (a: number[], b: number[]) => {
const left = score(a),
right = score(b);
return left.map((value, index) => value - right[index]!).find((value) => value !== 0) ?? 0;
};
for (const forced of [false, true]) {
for (let due = 1; due <= 71; due++) {
const expected = subsets
.filter(
(pick) => score(pick)[0]! >= due && (!forced || pick.some((index) => player.hand[index]!.t === "research"))
)
.sort(compare)[0];
const actual = bestPayment(player, due, forced);
assert.deepEqual(
actual === null ? null : score(actual),
expected ? score(expected) : null,
`due=${due}, research=${forced}`
);
}
}
});

View file

@ -471,10 +471,7 @@ function moveDiscard(
}
const indices = sanitizeIndices(move.cards, player.hand.length, "discard");
const remaining = player.hand.filter((_, i) => !indices.includes(i));
const counting = remaining.reduce(
(sum, c) => sum + (c.t === "research" || c.t === "microbiotics" ? 0 : c.m ? 4 : 1),
0
);
const counting = countingHandSize({ ...player, hand: remaining });
if (counting > handCapacity(player)) {
err(`still ${counting} cards over the hand capacity of ${handCapacity(player)}`);
}

View file

@ -22,7 +22,7 @@ import {
} from "./data.js";
import { nextInt, shuffle } from "./prng.js";
import { KICKERS, RESOURCES, UPGRADES } from "./types.js";
import type { FactoryType, GameState, Kicker, PlayerState, Resource, Upgrade } from "./types.js";
import type { FactoryType, GameState, Kicker, PlayerState, ProductionCard, Resource, Upgrade } from "./types.js";
export function setup(players: number, options: Record<string, unknown>, seed: string): GameState {
if (!Number.isInteger(players) || players < MIN_PLAYERS || players > MAX_PLAYERS) {
@ -199,15 +199,12 @@ export function operators(player: PlayerState): number {
return player.population + Math.min(player.robots, robotMax(player));
}
/** Number of hand cards that count against hand capacity (a mega card counts as 4). */
export function handCardSize(card: ProductionCard): number {
return CAP_EXEMPT.includes(card.t) ? 0 : card.m ? 4 : 1;
}
export function countingHandSize(player: PlayerState): number {
let size = 0;
for (const card of player.hand) {
if (!CAP_EXEMPT.includes(card.t)) {
size += card.m ? 4 : 1;
}
}
return size;
return player.hand.reduce((size, card) => size + handCardSize(card), 0);
}
export function handValue(player: PlayerState): number {
@ -258,86 +255,87 @@ export function megaGroupsFor(player: PlayerState): Partial<Record<Resource, num
return result;
}
/**
* Pick hand-card indices paying at least `due`, minimizing the total paid
* (overpaid credits are lost) and, among equal totals, spending as MANY cards
* as possible (several small cards are worth less kept than one big card).
* Exact 0/1 subset-sum DP — hands are tiny, so this is a few thousand ops.
* Returns null when the hand cannot cover `due`.
*/
export function bestPayment(player: PlayerState, due: number, mustIncludeResearch = false): number[] | null {
const cards = player.hand.map((card, index) => ({ v: card.v, index })).filter((c) => c.v >= 0);
if (!mustIncludeResearch) {
const solved = solvePayment(cards, due);
return solved ? solved.picked.sort((a, b) => a - b) : null;
}
// Try each research card as the forced one and keep the best overall pick.
let best: { total: number; picked: number[] } | null = null;
for (const forced of cards) {
if (player.hand[forced.index]?.t !== "research") {
continue;
}
const rest = cards.filter((c) => c.index !== forced.index);
const sub = solvePayment(rest, Math.max(0, due - forced.v));
if (!sub) {
continue;
}
const total = forced.v + sub.total;
const count = 1 + sub.picked.length;
if (!best || total < best.total || (total === best.total && count > best.picked.length)) {
best = { total, picked: [forced.index, ...sub.picked] };
}
}
return best ? best.picked.sort((a, b) => a - b) : null;
interface CardSelection {
total: number;
space: number;
megas: number;
research: number;
picked: number[];
}
/** 0/1 knapsack over exact sums: dp[i][s] = max cards among the first i reaching exactly s. */
function solvePayment(cards: { v: number; index: number }[], due: number): { total: number; picked: number[] } | null {
if (due <= 0) {
return { total: 0, picked: [] };
function preferSelection(candidate: CardSelection, current: CardSelection | undefined): boolean {
if (!current) {
return true;
}
const totalAll = cards.reduce((sum, c) => sum + c.v, 0);
if (totalAll < due) {
return null;
if (candidate.total !== current.total) {
return candidate.total < current.total;
}
const n = cards.length;
const width = totalAll + 1;
// Flat (n+1) x width table of best counts; -1 = sum unreachable.
const dp = new Int32Array((n + 1) * width).fill(-1);
dp[0] = 0;
for (let i = 0; i < n; i++) {
const v = (cards[i] as { v: number }).v;
const prev = i * width;
const cur = prev + width;
for (let s = 0; s < width; s++) {
let count = dp[prev + s] as number;
if (s >= v && dp[prev + s - v] !== -1 && (dp[prev + s - v] as number) + 1 > count) {
count = (dp[prev + s - v] as number) + 1;
if (candidate.space !== current.space) {
return candidate.space > current.space;
}
if (candidate.megas !== current.megas) {
return candidate.megas > current.megas;
}
if (candidate.research !== current.research) {
return candidate.research < current.research;
}
return candidate.picked.length > current.picked.length;
}
function addToSelection(selection: CardSelection, card: ProductionCard, index: number): CardSelection {
return {
total: selection.total + card.v,
space: selection.space + handCardSize(card),
megas: selection.megas + Number(card.m === true),
research: selection.research + Number(card.t === "research"),
picked: [...selection.picked, index],
};
}
function selectCards(
player: PlayerState,
target: number,
discard: boolean,
mustIncludeResearch = false
): number[] | null {
if (target <= 0 && !mustIncludeResearch) {
return [];
}
const empty: CardSelection = { total: 0, space: 0, megas: 0, research: 0, picked: [] };
const choices = new Map<number, CardSelection>([[0, empty]]);
for (const [index, card] of player.hand.entries()) {
if (card.v < 0 || (discard && handCardSize(card) === 0)) {
continue;
}
for (const selection of [...choices.values()]) {
const candidate = addToSelection(selection, card, index);
const amount = discard ? candidate.space : candidate.total;
// Keep research-bearing payments separate so a better unrestricted
// payment cannot erase the only valid New Chemicals payment.
const nextKey = amount * 2 + Number(mustIncludeResearch && candidate.research > 0);
if (preferSelection(candidate, choices.get(nextKey))) {
choices.set(nextKey, candidate);
}
dp[cur + s] = count;
}
}
let sum = -1;
for (let s = due; s < width; s++) {
if (dp[n * width + s] !== -1) {
sum = s;
break;
let best: CardSelection | undefined;
for (const candidate of choices.values()) {
if ((discard ? candidate.space : candidate.total) < target || (mustIncludeResearch && candidate.research === 0)) {
continue;
}
if (preferSelection(candidate, best)) {
best = candidate;
}
}
if (sum === -1) {
return null;
}
const total = sum;
const picked: number[] = [];
for (let i = n; i > 0; i--) {
const card = cards[i - 1] as { v: number; index: number };
const withoutIt = dp[(i - 1) * width + sum] as number;
if (dp[i * width + sum] !== withoutIt) {
picked.push(card.index);
sum -= card.v;
}
}
return { total, picked };
return best?.picked ?? null;
}
export function bestPayment(player: PlayerState, due: number, mustIncludeResearch = false): number[] | null {
return selectCards(player, due, false, mustIncludeResearch);
}
export function bestDiscard(player: PlayerState): number[] {
return selectCards(player, Math.max(0, countingHandSize(player) - handCapacity(player)), true) ?? [];
}
/**

View file

@ -1,6 +1,6 @@
{
"name": "outpost-viewer",
"version": "0.1.13",
"version": "0.1.14",
"description": "Browser viewer for the Outpost game on boardgamers.space",
"license": "AGPL-3.0",
"files": [

View file

@ -141,9 +141,13 @@
{:else if store.iMustDiscard && me}
<div class="flow">
<span class="hint warn">
{`Hand limit exceeded. Cards still to discard: ${store.discardExcess} (selected: ${pickCount}; Research and Microbiotics do not count).`}
{`Hand limit exceeded. Cards still to discard: ${store.discardRemaining} (selected: ${store.discardSelectedSize}; Research and Microbiotics do not count).`}
</span>
<button class="confirm" disabled={pickCount === 0} onclick={() => store.confirmDiscard()}>
<button
class="confirm"
disabled={pickCount === 0 || store.discardRemaining > 0}
onclick={() => store.confirmDiscard()}
>
Discard selected
</button>
</div>

View file

@ -8,6 +8,7 @@ import {
applyMove,
applyTurnBuy,
auctionCard,
bestDiscard,
bestPayment,
canBuyFactory,
countingHandSize,
@ -15,6 +16,7 @@ import {
describeLogEntry,
exchangeResources,
handCapacity,
handCardSize,
handValue,
megaEligible as megaEligibleEngine,
needsMegaChoice,
@ -660,7 +662,7 @@ export class ViewerStore {
return null;
}
/** Preselect the optimal payment: least overpay, then as many (small) cards as possible. */
/** Minimize overpayment, then free hand space and preserve research. */
suggestPayment(due: number, mustIncludeResearch = false): void {
const me = this.me;
if (!me) {
@ -669,18 +671,13 @@ export class ViewerStore {
this.cardPick = bestPayment(me, due, mustIncludeResearch) ?? [];
}
/** Preselect the cheapest counting cards to get back under the hand cap. */
/** Minimize discarded credits while freeing enough hand space. */
suggestDiscard(): void {
const me = this.me;
if (!me) {
return;
}
this.cardPick = me.hand
.map((card, index) => ({ card, index }))
.filter(({ card }) => card.t !== "research" && card.t !== "microbiotics")
.sort((a, b) => a.card.v - b.card.v)
.slice(0, this.discardExcess)
.map((e) => e.index);
this.cardPick = bestDiscard(me);
}
canBuy(type: FactoryType): boolean {
@ -938,14 +935,19 @@ export class ViewerStore {
this.rebuildDraft();
}
get discardSelectedSize(): number {
return this.cardPick.reduce((sum, index) => {
const card = this.me?.hand[index];
return sum + (card ? handCardSize(card) : 0);
}, 0);
}
get discardRemaining(): number {
return Math.max(0, this.discardExcess - this.discardSelectedSize);
}
confirmDiscard(): void {
const me = this.me;
if (!this.iMustDiscard || !me || this.cardPick.length === 0) {
return;
}
const remaining = me.hand.filter((_, i) => !this.cardPick.includes(i));
const counting = remaining.filter((c) => c.t !== "research" && c.t !== "microbiotics").length;
if (counting > handCapacity(me)) {
if (!this.me || !this.iMustDiscard || this.cardPick.length === 0 || this.discardRemaining > 0) {
return;
}
this.send({ action: "discard", cards: this.cardPick });

View file

@ -0,0 +1,108 @@
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { previewServer } from "./tutorial-preview.mjs";
import { initGame } from "../packages/engine/dist/index.js";
import { stripSecret } from "../packages/engine/dist/wrapper.js";
async function checkCardSelection(page) {
const show = async (state) => {
await page.evaluate(
(state) => {
window.emitter = outpost.launch("#app");
window.selectionMoves = [];
emitter.on("move", (move) => selectionMoves.push(move));
emitter.emit("preferences", { sound: false });
emitter.emit("player", { index: 0 });
emitter.emit("state", state);
},
stripSecret(state, 0)
);
await page.locator(".pcard.selected").first().waitFor();
};
for (const [hand, due, expected] of [
[
[{ t: "water", v: 30, m: true }, ...[7, 7, 8, 8].map((v) => ({ t: "water", v }))],
30,
"Mega Water: 30 credits (counts as 4 cards toward hand capacity)",
],
[
[
{ t: "research", v: 10 },
{ t: "microbiotics", v: 10 },
{ t: "water", v: 10 },
],
10,
"Water: 10 credits",
],
[
[
{ t: "research", v: 10 },
{ t: "microbiotics", v: 10 },
],
10,
"Microbiotics: 10 credits",
],
]) {
const state = initGame(3, {}, "payment-suggestion");
state.players[0].hand = hand;
state.phase = "auctionPayment";
state.auction = {
marketIndex: 0,
upgrade: "dataLibrary",
auctioneer: 0,
highBid: due,
highBidder: 0,
passed: [1, 2],
activeBidder: 0,
};
await show(state);
assert.deepEqual(await page.locator(".pcard.selected").evaluateAll((cards) => cards.map((c) => c.title)), [
expected,
]);
}
const state = initGame(3, {}, "discard-suggestion");
state.phase = "discard";
state.players[0].mustDiscard = true;
state.players[0].hand = [
{ t: "water", v: 30, m: true },
{ t: "titanium", v: 44, m: true },
{ t: "newChemicals", v: 88, m: true },
{ t: "ore", v: 1 },
];
await show(state);
const confirm = page.getByRole("button", { name: "Discard selected", exact: true });
assert.equal(await confirm.isEnabled(), true);
assert.equal(await page.locator(".pcard.selected").count(), 1);
await page.getByText(/Cards still to discard: 0 \(selected: 4;/).waitFor();
const mega = page.getByTitle("Mega Water: 30 credits (counts as 4 cards toward hand capacity)", { exact: true });
const ore = page.getByTitle("Ore: 1 credits", { exact: true });
await mega.click();
await ore.click();
assert.equal(await confirm.isDisabled(), true, "three remaining Megas still exceed capacity");
await page.getByText(/Cards still to discard: 2 \(selected: 1;/).waitFor();
await ore.click();
await mega.click();
await confirm.click();
assert.deepEqual(await page.evaluate(() => selectionMoves), [{ action: "discard", cards: [0] }]);
}
const server = previewServer();
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const browser = await chromium.launch({ executablePath: process.env.OUTPOST_CHROMIUM_EXECUTABLE });
try {
for (const width of [390, 1400]) {
const page = await browser.newPage({ viewport: { width, height: 950 } });
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.setContent('<div id="app"></div>');
await page.addStyleTag({ path: "packages/viewer/dist/outpost-viewer.css" });
await page.addScriptTag({ url: `http://127.0.0.1:${server.address().port}/bundle.js` });
await checkCardSelection(page);
assert.deepEqual(errors, []);
await page.close();
}
console.log("Card selection: payment preferences and weighted Mega discards passed on mobile and desktop.");
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}