Files
wikideck/tests/game-core.test.ts
T

213 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Core-loop tests owned by engine-a. Keyword/Portal, derivation, property and golden tests: engine-b (tests/game-*.test.ts).
import test from 'node:test';
import assert from 'node:assert/strict';
import {
DEFAULT_RULESET, IllegalActionError, KEYWORDS, PORTALS, Rng, applyAction, cardPower, createMatch, deserialize, isOver,
laneLeader, legalActions, loanerCard, parseRuleset, placeCard, replay, result, revealPortal, serialize, starterDeck,
STARTER_POOL, viewFor, type Action, type GameCard, type KeywordDef, type MatchState, type PlayerId, type PortalDef, type Ruleset,
} from '../shared/game/index.ts';
const decks = (seed = 'd'): [GameCard[], GameCard[]] => [starterDeck(`${seed}-a`), starterDeck(`${seed}-b`)];
const commit = (s: MatchState, player: PlayerId) => applyAction(s, { type: 'commit', player });
const commitBoth = (s: MatchState) => commit(commit(s, 0), 1);
const card = (cost: number, overrides: Partial<GameCard> = {}): GameCard =>
({ ...loanerCard(STARTER_POOL.find(s => s[3] === cost)!), keyword: null, trend: 0, ...overrides });
/** A deck whose every card costs `cost`, so the first plays are predictable. */
const flatDeck = (cost: number, prefix: string, home: GameCard['home'] = 'depth'): GameCard[] =>
Array.from({ length: 12 }, (_, i) => card(cost, { cardId: `${prefix}${i}`, pageId: 1000 + Math.floor(i / 2), home }));
/** Temporarily register a keyword/portal implementation under a v1 id. */
function withHook<T>(registry: Record<string, T>, id: string, def: T, run: () => void) {
const saved = registry[id];
registry[id] = def;
try { run(); } finally { if (saved === undefined) delete registry[id]; else registry[id] = saved; }
}
function randomPlay(seed: number, ruleset: Ruleset = DEFAULT_RULESET): MatchState {
let state = createMatch(ruleset, decks(String(seed)), seed);
const chooser = Rng.fromSeed(`bot:${seed}`);
for (let steps = 0; !isOver(state); steps++) {
assert.ok(steps < 2000, 'match must terminate');
const player = chooser.int(2) as PlayerId;
const actions = legalActions(state, player);
if (actions.length) state = applyAction(state, chooser.pick(actions));
assert.deepEqual(deserialize(serialize(state)), state);
}
return state;
}
test('mulberry32 matches the reference value and is seed-deterministic', () => {
assert.equal(new Rng(1).next(), 0.6270739405881613);
const seq = (r: Rng) => Array.from({ length: 8 }, () => r.next());
assert.deepEqual(seq(Rng.fromSeed(42)), seq(Rng.fromSeed(42)));
assert.notDeepEqual(seq(Rng.fromSeed(42)), seq(Rng.fromSeed(43)));
assert.equal(Rng.fromSeed('lobby-1').state, Rng.fromSeed('lobby-1').state);
});
test('DEFAULT_RULESET matches DESIGN §9 and parses; bad rulesets are rejected', () => {
assert.deepEqual(parseRuleset(DEFAULT_RULESET), DEFAULT_RULESET);
assert.equal(DEFAULT_RULESET.laneCapacity, 3);
assert.deepEqual(DEFAULT_RULESET.powerByCost, [0, 1, 2, 4, 6, 8, 10]);
assert.deepEqual(DEFAULT_RULESET.onTopicBonus, [0, 1, 1, 2, 2, 3, 3]);
assert.equal(DEFAULT_RULESET.topicPool.length, 9);
for (const bad of [{ turns: 13 }, { turnSeconds: 60 }, { energyByTurn: [1, 2] }, { portalReveal: [1, 2] },
{ keywordParams: { nope: {} } }, { keywordsEnabled: ['nope'] }, { extra: 1 }, { mulligan: true },
{ costThresholds: [90, 1, 2, 3, 4] }, { onTopicBonus: 2 }, { topicCount: 2 }, { portalParams: { nope: {} } }])
assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, ...bad }), JSON.stringify(bad));
});
test('setup: one Topic per stat, stats visible, Portals hidden until portalReveal, hands of 4, energy 1', () => {
const state = createMatch(DEFAULT_RULESET, decks(), 7);
assert.equal(state.turn, 1);
assert.deepEqual(state.lanes.map(l => l.topic.stat).sort(), ['attention', 'depth', 'reach']);
assert.deepEqual(state.lanes.map(l => l.portalRevealed), [false, false, false]);
for (const p of state.players) { assert.equal(p.hand.length, 4); assert.equal(p.deck.length, 8); assert.equal(p.energy, 1); }
const view = viewFor(state, 0);
assert.deepEqual(view.lanes.map(l => l.topic.stat), state.lanes.map(l => l.topic.stat));
assert.ok(view.lanes.every(l => l.topic.portal === null && l.topic.name === '?'));
let next = commitBoth(state);
assert.deepEqual(next.lanes.map(l => l.portalRevealed), [true, false, false]);
next = commitBoth(commitBoth(next));
assert.deepEqual(next.lanes.map(l => l.portalRevealed), [true, true, true]);
});
test('decks are validated: size, copies per page, keyword ids, ownedCards', () => {
const [a, b] = decks();
assert.throws(() => createMatch(DEFAULT_RULESET, [a.slice(0, 11), b], 1), IllegalActionError);
const triple = [...a.slice(0, 9), ...[0, 1, 2].map(n => ({ ...a[0], cardId: `x${n}` }))];
assert.throws(() => createMatch(DEFAULT_RULESET, [triple, b], 1), /copies/);
assert.throws(() => createMatch(DEFAULT_RULESET, [[{ ...a[0], keyword: 'nope' }, ...a.slice(1)], b], 1), /unknown keyword/);
const owned = [{ ...a[0], source: 'owned' as const }, ...a.slice(1)];
assert.doesNotThrow(() => createMatch(DEFAULT_RULESET, [owned, b], 1));
assert.throws(() => createMatch({ ...DEFAULT_RULESET, ownedCards: false }, [owned, b], 1), /owned/);
});
test('queued plays are hidden until reveal; undo refunds; committed seats get no actions', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 11);
const play = legalActions(state, 0).find(a => a.type === 'play') as Extract<Action, { type: 'play' }>;
assert.ok(play, 'turn 1 should have a 1-cost play');
state = applyAction(state, play);
assert.equal(viewFor(state, 0).energyLeft, 0);
assert.equal(viewFor(state, 1).opponent.queuedCount, 1);
assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false);
assert.equal(viewFor(applyAction(state, { type: 'undo', player: 0, cardId: play.cardId }), 0).energyLeft, 1);
state = commit(state, 0);
assert.deepEqual(legalActions(state, 0), []);
state = commit(state, 1);
assert.equal(state.turn, 2);
assert.equal(viewFor(state, 1).lanes[play.lane].cards[1][0].card.cardId, play.cardId);
assert.throws(() => applyAction(state, { type: 'play', player: 0, cardId: play.cardId, lane: 0 }), IllegalActionError);
});
test('viewFor never leaks the opponent hand, deck order, queue, seed or RNG state', () => {
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'mine'), flatDeck(1, 'opp')], 'leak-seed');
const play = legalActions(state, 1).find(x => x.type === 'play')!;
state = applyAction(state, play);
const view = viewFor(state, 0);
const json = JSON.stringify(view);
for (const key of ['"seed"', '"rng"', '"deck"', '"log"', '"actions"']) assert.equal(json.includes(key), false, key);
for (const c of [...state.players[1].hand, ...state.players[1].deck, ...state.players[0].deck])
assert.equal(json.includes(`"${c.cardId}"`), false, c.cardId);
assert.deepEqual(view.hand.map(c => c.cardId), state.players[0].hand.map(c => c.cardId));
});
test('energy: energyByTurn + carry (max 1) of unspent energy', () => {
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 3);
const first = state.players[0].hand[0].cardId;
state = applyAction(state, { type: 'play', player: 0, cardId: first, lane: 0 }); // p0 spends 1, p1 saves 1
state = commitBoth(state);
assert.deepEqual(state.players.map(p => p.energy), [2, 3]);
state = commitBoth(state); // both save everything; carry is capped at 1
assert.deepEqual(state.players.map(p => p.energy), [4, 4]);
});
test('reveal is interleaved: initiative 1st, other 1st, initiative 2nd, …; initiative alternates', () => {
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 5);
state = commitBoth(state); // turn 2: 3 energy each (2 + carry 1)
const init = state.initiative;
const ids = (p: PlayerId) => state.players[p].hand.slice(0, 3).map(c => c.cardId);
const [mine, theirs] = [ids(init), ids(init === 0 ? 1 : 0)];
for (const [player, cards] of [[init, mine], [init === 0 ? 1 : 0, theirs.slice(0, 2)]] as const)
cards.forEach((cardId, lane) => { state = applyAction(state, { type: 'play', player, cardId, lane }); });
const before = state.log.length;
state = commitBoth(state);
const order = state.log.slice(before).filter(e => e.t === 'reveal').map(e => (e as { cardId: string }).cardId);
assert.deepEqual(order, [mine[0], theirs[0], mine[1], theirs[1], mine[2]]);
assert.equal(state.initiative, init === 0 ? 1 : 0);
assert.deepEqual(state.lanes.flatMap(l => [...l.cards[0], ...l.cards[1]]).map(c => c.seq).sort((x, y) => x - y), [1, 2, 3, 4, 5]);
});
test('lane power: base + onTopicBonus[cost] + trend, floored at 0', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 5);
const stat = state.lanes[1].topic.stat;
const off = stat === 'depth' ? 'reach' : 'depth';
state = placeCard(state, 0, 1, card(5, { cardId: 'on', home: stat, trend: 1 }));
assert.equal(cardPower(state, state.lanes[1].cards[0][0]), 8 + 3 + 1);
state = placeCard(state, 0, 1, card(2, { cardId: 'off', home: off }));
assert.equal(cardPower(state, state.lanes[1].cards[0][1]), 2);
state = placeCard(state, 1, 1, card(1, { cardId: 'neg', home: off, trend: -1, power: 0 }));
assert.equal(cardPower(state, state.lanes[1].cards[1][0]), 0);
});
test('consensus tie-break: equal power > 0 goes to more on-topic cards; 0–0 has no leader', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 8);
const stat = state.lanes[0].topic.stat;
const off = stat === 'depth' ? 'reach' : 'depth';
assert.equal(laneLeader(state, 0), null);
state = placeCard(state, 0, 0, card(2, { cardId: 'a', home: stat, power: 1 })); // 1 + 1 on-topic = 2
state = placeCard(state, 1, 0, card(2, { cardId: 'b', home: off, power: 2 })); // 2 off-topic
assert.equal(laneLeader(state, 0), 0);
state = placeCard(state, 1, 0, card(1, { cardId: 'c', home: stat, power: 0 })); // +1 on-topic: 3 vs 2
assert.equal(laneLeader(state, 0), 1);
});
test('Portals: capacity override and fizzle at reveal, at-scoring bonus, disabled keywords do not run', () => {
const stub: PortalDef = { id: 'stub', name: 'Stub', text: '', capacity: ctx => ctx.params.value ?? 2 };
const mainPage: PortalDef = { id: 'main-page', name: 'Main Page', text: '', atScoring: ctx => [0, 1].map(p => ctx.state.lanes[ctx.lane].cards[p].length * (ctx.params.amount ?? 1)) as [number, number] };
const bump: KeywordDef = { id: 'rising', name: 'Rising', text: '', onReveal: (_ctx, self) => { self.bonus += 5; } };
withHook(PORTALS, 'stub', stub, () => withHook(PORTALS, 'main-page', mainPage, () => withHook(KEYWORDS, 'rising', bump, () => {
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 2);
state.lanes[0].topic = { id: 'stub', name: 'Stub', stat: 'depth', portal: 'stub' };
state.lanes[1].topic = { id: 'main-page', name: 'Main Page', stat: 'attention', portal: 'main-page' };
state = revealPortal(revealPortal(state, 0), 1);
state = placeCard(placeCard(state, 0, 0, card(1, { cardId: 'p1' })), 0, 0, card(1, { cardId: 'p2' }));
assert.ok(legalActions(state, 0).every(a => a.type !== 'play' || a.lane !== 0), 'Stub holds 2');
state = placeCard(state, 1, 1, card(2, { cardId: 'r', keyword: 'rising' }));
state.ruleset.keywordsEnabled = [];
const hand = state.players[1].hand[0];
state = applyAction(state, { type: 'play', player: 1, cardId: hand.cardId, lane: 1 });
state.players[1].hand[0] = { ...hand, keyword: 'rising' }; // disabled: no +5
while (!isOver(state)) state = commitBoth(state);
const r = result(state)!;
assert.equal(r.lanePower[1][1], cardPower(state, state.lanes[1].cards[1][0]) + cardPower(state, state.lanes[1].cards[1][1]) + 2);
assert.ok(state.lanes[1].cards[1].every(c => c.bonus === 0));
})));
});
test('timeouts with nothing queued concede after afkTurns; concede ends the match', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 17);
state = commit(applyAction(state, { type: 'timeout', player: 0 }), 1);
assert.equal(isOver(state), false);
state = applyAction(state, { type: 'timeout', player: 0 });
assert.deepEqual([result(state)?.winner, result(state)?.reason], [1, 'afk']);
const conceded = applyAction(createMatch(DEFAULT_RULESET, decks(), 1), { type: 'concede', player: 1 });
assert.equal(result(conceded)?.winner, 0);
assert.deepEqual(legalActions(conceded, 0), []);
});
test('two passing players draw after 6 turns', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 21);
while (!isOver(state)) state = commitBoth(state);
const r = result(state)!;
assert.deepEqual([r.winner, r.reason, r.turns], [null, 'draw', 6]);
});
test('random legal play terminates, replays exactly, and survives serialisation after every action', () => {
for (let seed = 0; seed < 20; seed++) {
const end = randomPlay(seed);
assert.ok(result(end)!.turns <= DEFAULT_RULESET.turns);
assert.deepEqual(randomPlay(seed), end);
assert.deepEqual(replay(DEFAULT_RULESET, decks(String(seed)), seed, end.actions), end);
}
});