files-tcg/sim/test/table.ts
2026-10-01 17:20:33 -04:00

244 lines
8.8 KiB
TypeScript

/**
* A test table: builds a game from small hand-picked decks, then lets a test arrange the board
* directly and drive decisions one at a time.
*/
import assert from 'node:assert/strict';
import { loadCards } from '../src/load.ts';
import { actionKey, applyAction, createGame, decider, legalActions, openWindow } from '../src/engine.ts';
import { checkInvariants } from '../src/invariants.ts';
import type { LocId } from '../src/map.ts';
import { coresOf, fighterOf, sideCores } from '../src/query.ts';
import { DEFAULT_RULES, type RulesConfig } from '../src/rules.ts';
import { anomaly, logFor, removeFrom } from '../src/state.ts';
import type { Action, Args, AnomalyRef, GameState, PlayerId } from '../src/types.ts';
export const pool = loadCards();
/** Cards that do nothing in hand and can't be played in response, used to pad decks. */
const FILLER = 'Network Interface Upgrade';
const PLAIN_SERVER = 'Network Throttle';
/** Anomalies whose Abilities only work in combat, so they don't open response windows. */
const DEFAULT_ANOMALIES = ['Broken Bits', 'Pixelated Picture', 'Corrupt Driver', 'Code Zero'];
export interface Side {
anomalies?: string[];
servers?: string[];
main?: string[];
}
export class Table {
s: GameState;
constructor(o: { south?: Side; north?: Side; first?: PlayerId; seed?: number; health?: boolean } = {}) {
const side = (x: Side = {}) => ({
anomalies: x.anomalies ?? DEFAULT_ANOMALIES,
servers: [...(x.servers ?? []), ...Array(12).fill(PLAIN_SERVER)],
main: [...(x.main ?? []), ...Array(12).fill(FILLER)],
});
const decks = [side(o.south), side(o.north)] as const;
// Classic turns (one turn each, every Anomaly acts), no turn-1 draw for the first player, and
// one-roll combats, which the card tests are written for. The command rule has its own tests in
// engine.test.ts, the health rule in health.test.ts (`health: true`).
const rules: RulesConfig = {
...DEFAULT_RULES,
commands: { ...DEFAULT_RULES.commands, on: false },
firstTurn: { ...DEFAULT_RULES.firstTurn, draw: false },
health: { ...DEFAULT_RULES.health, on: o.health ?? false },
openingHand: 0,
deck: { anomalies: 4, servers: decks[0].servers.length, main: decks[0].main.length, maxCopies: 99 },
};
// Both decks must be the same size under one rules object; pad the shorter one.
const n = Math.max(decks[0].main.length, decks[1].main.length);
const m = Math.max(decks[0].servers.length, decks[1].servers.length);
for (const d of decks) {
while (d.main.length < n) d.main.push(FILLER);
while (d.servers.length < m) d.servers.push(PLAIN_SERVER);
}
rules.deck = { ...rules.deck, main: n, servers: m };
this.s = createGame({ pool, decks: [decks[0], decks[1]], seed: o.seed ?? 1, rules, log: true });
const first = o.first ?? 0;
this.s.firstPlayer = first;
this.s.active = first;
for (const p of [0, 1] as const) {
// Put the starting Server back and use a plain one, so tests start from a known board.
const start = p === 0 ? 'S1' : 'S2';
const L = this.s.locations[start];
this.s.players[p].serverPile.push(L.server!);
L.server = this.take(p, PLAIN_SERVER);
this.s.players[p].bandwidth = 0;
// Anomalies in the order given, slot 1 face up.
const want = (p === 0 ? o.south : o.north)?.anomalies ?? DEFAULT_ANOMALIES;
const avs = this.s.players[p].anomalies;
want.forEach((name, i) => {
const j = avs.findIndex((a, k) => k < 4 && k >= i && this.s.cards[a.card].name === name);
[avs[i].card, avs[j].card] = [avs[j].card, avs[i].card];
});
for (let i = 0; i < 4; i++) avs[i + 4].card = avs[i].card;
}
this.s.log = [];
}
// -------------------------------------------------------------------------------------------
// Arranging the board
/** Takes a card of `name` owned by `p` out of its deck, pile, hand or discard. */
take(p: PlayerId, name: string): number {
const pl = this.s.players[p];
for (const zone of [pl.deck, pl.serverPile, pl.hand, pl.discard]) {
const id = zone.find((c) => this.s.cards[c].name === name);
if (id !== undefined) {
removeFrom(zone, id);
return id;
}
}
throw new Error(`No ${name} left for player ${p}`);
}
hand(p: PlayerId, ...names: string[]): number[] {
return names.map((n) => {
const id = this.take(p, n);
this.s.players[p].hand.push(id);
return id;
});
}
/** Puts cards on top of `p`'s deck, first name on top. */
top(p: PlayerId, ...names: string[]): number[] {
const ids = names.map((n) => this.take(p, n));
this.s.players[p].deck.unshift(...ids);
return ids;
}
/** Makes `name` the next Server `p` draws on a capture. */
nextServer(p: PlayerId, name: string): number {
const id = this.take(p, name);
this.s.players[p].serverPile.unshift(id);
return id;
}
bandwidth(p: PlayerId, n: number): this {
this.s.players[p].bandwidth = n;
return this;
}
/** Gives `p` a location with a Server on it. */
own(p: PlayerId, loc: LocId, server = PLAIN_SERVER): number {
const L = this.s.locations[loc];
if (L.server !== null) this.s.players[this.s.cards[L.server].owner].serverPile.push(L.server);
L.owner = p;
L.server = this.take(p, server);
return L.server;
}
/** Puts Anomaly `slot` of `p` in play on `at` (face up). */
place(p: PlayerId, slot: number, at: LocId): AnomalyRef {
const av = this.s.players[p].anomalies[slot - 1];
av.faceUp = true;
av.at = at;
return { player: p, slot };
}
program(p: PlayerId, loc: LocId, name: string): number {
const id = this.take(p, name);
this.s.locations[loc].programs.push(id);
return id;
}
hardware(p: PlayerId, slot: number, name: string): number {
const id = this.take(p, name);
this.s.players[p].anomalies[slot - 1].hardware.push(id);
return id;
}
// -------------------------------------------------------------------------------------------
// Playing
get decider(): PlayerId {
return decider(this.s)!;
}
legal(): Action[] {
return legalActions(this.s);
}
can(a: Action): boolean {
const k = actionKey(a);
return this.legal().some((x) => actionKey(x) === k);
}
/** Applies an action for whoever decides now, and checks the state afterwards. */
act(a: Action): this {
applyAction(this.s, a);
assert.deepEqual(checkInvariants(this.s), [], 'invariants');
return this;
}
/** Passes every open window until a main step decision or a choice. */
settle(): this {
for (let i = 0; i < 50 && !this.s.over && !this.s.choice && openWindow(this.s); i++) this.act({ type: 'pass' });
return this;
}
/** Acts, then passes windows. */
go(a: Action): this {
return this.act(a).settle();
}
end(): this {
return this.settle().go({ type: 'end' });
}
/** Ends steps until the given step of the active player's turn. */
to(step: GameState['step']): this {
for (let i = 0; i < 10 && this.s.step !== step; i++) this.end();
assert.equal(this.s.step, step);
return this;
}
/** Plays an Execution from hand. `from` is the performing Server, when it matters. */
play(p: PlayerId, name: string, target: LocId | null, args: Args = {}, from: LocId | null = null): this {
const card = this.s.players[p].hand.find((id) => this.s.cards[id].name === name);
assert.ok(card !== undefined, `${name} is in hand`);
assert.equal(this.decider, p, `player ${p} decides`);
return this.act({ type: 'play', card, target, args, from });
}
/** Activates the ability of the card `id` (an Anomaly's card id, a Program or Hardware). */
use(id: number, args: Args = {}): this {
return this.act({ type: 'activate', card: id, name: this.s.cards[id].name, args });
}
/** Picks the choice option whose label includes `text` (or the option at an index). */
choose(text: string | number): this {
const ch = this.s.choice;
assert.ok(ch, 'a choice is pending');
const index = typeof text === 'number' ? text : ch.options.findIndex((o) => o.label.includes(text));
assert.ok(index >= 0, `option "${text}" in ${ch.options.map((o) => o.label).join(' / ')}`);
return this.act({ type: 'choose', index });
}
// -------------------------------------------------------------------------------------------
// Reading
anomaly(p: PlayerId, slot: number) {
return anomaly(this.s, { player: p, slot });
}
cores(p: PlayerId, slot: number): number {
return coresOf(this.s, fighterOf(this.s, { player: p, slot }));
}
sides() {
return sideCores(this.s);
}
/** Sets the next dice results (attacker's dice first, then defenders', in roll order). */
rig(...rolls: number[]): this {
this.s.rigged = [...rolls];
return this;
}
logText(): string {
return logFor(this.s, null).join('\n');
}
}