Files
wikideck/shared/game/engine.ts
T

455 lines
22 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.
/**
* WikiDeck game engine core ("Edit War", docs/game/DESIGN.md): pure,
* deterministic, off-chain. Exported functions never mutate their inputs.
* All randomness comes from the match seed via state.rng (mulberry32, §4).
* Contract: docs/game/ENGINE_API.md.
*/
import { KEYWORDS, KEYWORD_IDS, activePortal, isOnTopic, type EffectContext, type KeywordDef, type PortalDef } from './keywords.ts';
import { Rng, normalizeSeed } from './rng.ts';
import { parseRuleset } from './ruleset.ts';
import {
IllegalActionError, PLAYERS, STATS,
type Action, type CardInPlay, type GameCard, type MatchResult, type MatchState,
type PlayerId, type PlayerState, type PlayerView, type Ruleset, type TopicDef,
} from './types.ts';
export const ENGINE_VERSION = 1;
export const other = (player: PlayerId): PlayerId => (player === 0 ? 1 : 0);
const clone = <T>(value: T): T => structuredClone(value);
const RARITIES = new Set(['Common', 'Rare', 'Epic', 'Legendary']);
const FACTION_SET = new Set(['Space', 'Nature', 'People', 'Science', 'History', 'Culture']);
const CHECKS = new Set(['verified', 'unverified', 'unchecked', 'loaner']);
// ---------- validation ----------
/** Problems with a deck under `rules` (empty = legal). DESIGN §2. */
export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[] {
const problems: string[] = [];
if (!Array.isArray(deck)) return ['Deck must be an array'];
if (deck.length !== rules.deckSize) problems.push(`Deck must have exactly ${rules.deckSize} cards (has ${deck.length})`);
const ids = new Set<string>();
const copies = new Map<string, number>();
let loaners = 0;
for (const card of deck) {
if (typeof card?.cardId !== 'string' || !card.cardId || card.cardId.length > 128) { problems.push('cardId must be a non-empty string'); continue; }
const label = card.cardId;
if (ids.has(card.cardId)) problems.push(`Duplicate cardId ${label}`);
ids.add(card.cardId);
if (card.pageId !== null && !Number.isInteger(card.pageId)) problems.push(`${label}: bad pageId`);
if (card.pageId === null && card.source !== 'loaner') problems.push(`${label}: owned cards need a pageId`);
if (typeof card.title !== 'string' || card.title.length > 256) problems.push(`${label}: bad title`);
if (!FACTION_SET.has(card.faction)) problems.push(`${label}: bad faction`);
if (!RARITIES.has(card.rarity)) problems.push(`${label}: bad rarity`);
if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 6) problems.push(`${label}: cost must be 0–6`);
if (!Number.isInteger(card.power) || card.power < 0 || card.power > 30) problems.push(`${label}: power must be 0–30`);
if (!STATS.includes(card.home)) problems.push(`${label}: bad home stat`);
if (card.trend !== -1 && card.trend !== 0 && card.trend !== 1) problems.push(`${label}: trend must be -1, 0 or 1`);
if (card.keyword !== null && !(KEYWORD_IDS as readonly string[]).includes(card.keyword)) problems.push(`${label}: unknown keyword ${card.keyword}`);
if (card.source !== 'owned' && card.source !== 'loaner') problems.push(`${label}: bad source`);
if (card.check !== undefined && !CHECKS.has(card.check)) problems.push(`${label}: bad check`);
if (card.source === 'loaner') loaners++;
if (card.source === 'owned' && !rules.ownedCards) problems.push(`${label}: owned cards are not allowed in this mode`);
// §2 / §2.1: owned and loaner copies count together by pageId; unpinned loaners (pageId null) by cardId.
const key = card.pageId !== null ? `page:${card.pageId}` : `card:${card.cardId}`;
const n = (copies.get(key) ?? 0) + 1;
copies.set(key, n);
if (n === rules.maxCopiesPerPage + 1) problems.push(`More than ${rules.maxCopiesPerPage} copies of ${card.pageId !== null ? `page ${card.pageId}` : card.cardId}`);
}
if (loaners > rules.maxLoaners) problems.push(`At most ${rules.maxLoaners} loaner cards`);
return problems;
}
// ---------- match setup (§4) ----------
/**
* Draw the match's Topics (§4.2.3). distinctStats: for each stat in STATS order
* (attention, depth, reach) pick one Topic of that stat with rng.int(groupSize),
* then Fisher–Yates the picks, then keep the first topicCount. Otherwise
* Fisher–Yates the whole pool and keep the first topicCount.
*/
function drawTopics(rules: Ruleset, rng: Rng): TopicDef[] {
if (!rules.distinctStats) return rng.shuffle(rules.topicPool).slice(0, rules.topicCount);
const picked: TopicDef[] = [];
for (const stat of STATS) {
const group = rules.topicPool.filter(topic => topic.stat === stat);
if (group.length) picked.push(group[rng.int(group.length)]);
}
return rng.shuffle(picked).slice(0, rules.topicCount);
}
/**
* Start a match. `decks[0]` belongs to seat 0. Seed is a uint32 (or a string,
* hashed with FNV-1a). Throws ZodError for a bad ruleset, IllegalActionError for a bad deck.
*/
export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: number | string): MatchState {
const rules = parseRuleset(clone(ruleset));
const seedValue = normalizeSeed(seed);
for (const player of PLAYERS) {
const problems = validateDeck(rules, decks?.[player] as GameCard[]);
if (problems.length) throw new IllegalActionError(`Seat ${player} deck: ${problems.join('; ')}`);
}
const rng = new Rng(seedValue);
const newPlayer = (player: PlayerId): PlayerState => ({
deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, queue: [], committed: false, afk: 0, carry: 0,
});
const p0 = newPlayer(0);
const p1 = newPlayer(1);
const topics = drawTopics(rules, rng);
const initiative: PlayerId = rng.next() < 0.5 ? 0 : 1;
const state: MatchState = {
schema: 'wikideck-match/1', engineVersion: ENGINE_VERSION, ruleset: rules, seed: seedValue, rng: rng.state,
turn: 0, phase: 'planning', initiative, revealSeq: 0, players: [p0, p1],
lanes: topics.map(topic => ({ topic: clone(topic), portalRevealed: false, cards: [[], []] as [CardInPlay[], CardInPlay[]] })),
log: [], actions: [], result: null,
};
for (const player of PLAYERS) for (let i = 0; i < rules.openingHand; i++) draw(state, player);
startTurn(state, rng);
state.rng = rng.state;
return state;
}
function draw(state: MatchState, player: PlayerId): void {
const p = state.players[player];
if (!p.deck.length || p.hand.length >= state.ruleset.handLimit) return;
const card = p.deck.shift()!;
p.hand.push(card);
state.log.push({ t: 'draw', player, cardId: card.cardId });
}
function context(state: MatchState, rng: Rng, params: Record<string, number> | undefined, lane: number, source: string, player: PlayerId): EffectContext {
return {
state, rng, params: params ?? {}, lane,
log: text => state.log.push({ t: 'effect', source, player, text }),
power: card => cardPower(state, card),
};
}
/** Enabled keyword definition for a card, if any. */
function keywordOf(state: MatchState, card: GameCard): KeywordDef | undefined {
return card.keyword && state.ruleset.keywordsEnabled.includes(card.keyword) ? KEYWORDS[card.keyword] : undefined;
}
function keywordCtx(state: MatchState, rng: Rng, keyword: KeywordDef, card: CardInPlay): EffectContext {
return context(state, rng, state.ruleset.keywordParams[keyword.id], card.lane, keyword.id, card.owner);
}
function portalCtx(state: MatchState, rng: Rng, lane: number, portal: PortalDef, player: PlayerId): EffectContext {
const topic = state.lanes[lane].topic;
const params = state.ruleset.portalParams[topic.id] ?? state.ruleset.portalParams[portal.id];
return context(state, rng, params, lane, portal.id, player);
}
/** Per-seat card capacity of a lane (a Portal may override it, e.g. Stub). */
export function laneCapacity(state: MatchState, lane: number): number {
const portal = activePortal(state, lane);
return portal?.capacity ? portal.capacity(portalCtx(state, new Rng(state.rng), lane, portal, state.initiative)) : state.ruleset.laneCapacity;
}
/** §5.1 Start (Portal reveal, energy, draw), then §5.2 Underdog. Initiative alternates (§5.5). */
function startTurn(state: MatchState, rng: Rng): void {
state.turn += 1;
if (state.turn > 1) state.initiative = other(state.initiative);
const rules = state.ruleset;
state.lanes.forEach((lane, index) => {
if (lane.portalRevealed || (rules.portalReveal[index] ?? 1) > state.turn) return;
lane.portalRevealed = true;
state.log.push({ t: 'portalRevealed', lane: index, topic: clone(lane.topic) });
const portal = activePortal(state, index);
portal?.onPortalReveal?.(portalCtx(state, rng, index, portal, state.initiative));
});
const base = (rules.energyByTurn[state.turn - 1] ?? rules.energyByTurn.at(-1)!) + rules.bonusEnergy;
for (const player of PLAYERS) {
const p = state.players[player];
Object.assign(p, { energy: base + p.carry, queue: [], committed: false });
}
for (const player of PLAYERS) draw(state, player);
if (rules.underdog && state.turn >= 2) {
const led = topicsLed(state);
for (const player of PLAYERS) if (led[player] === 0 && led[other(player)] >= 2) {
state.players[player].energy += 1;
state.log.push({ t: 'underdog', player });
}
}
state.log.push({ t: 'turnStart', turn: state.turn, energy: [state.players[0].energy, state.players[1].energy], initiative: state.initiative });
}
// ---------- power (§6) ----------
/** A card's current lane power (§6, never below 0). */
export function cardPower(state: MatchState, target: CardInPlay): number {
const rules = state.ruleset;
const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness
let power = target.card.power + target.bonus + target.card.trend;
if (isOnTopic(state, target)) power += rules.onTopicBonus[target.card.cost] ?? 0;
for (const lane of state.lanes) for (const side of lane.cards) for (const source of side) {
const keyword = keywordOf(state, source.card);
if (keyword?.ongoing) power += keyword.ongoing(keywordCtx(state, scratch, keyword, source), source, target);
}
const portal = activePortal(state, target.lane);
if (portal?.ongoing) power += portal.ongoing(portalCtx(state, scratch, target.lane, portal, target.owner), target);
return Math.max(0, power);
}
/** [seat 0 power, seat 1 power] in one lane (during play; excludes "at scoring" Portals). */
export function lanePower(state: MatchState, lane: number): [number, number] {
return PLAYERS.map(player => state.lanes[lane].cards[player].reduce((sum, card) => sum + cardPower(state, card), 0)) as [number, number];
}
/** §6: who leads a lane given its powers. Equal and > 0 → more on-topic cards leads (consensus). */
export function laneLeader(state: MatchState, lane: number, power: [number, number] = lanePower(state, lane)): PlayerId | null {
const [a, b] = power;
if (a !== b) return a > b ? 0 : 1;
if (a === 0) return null;
const onTopic = PLAYERS.map(player => state.lanes[lane].cards[player].filter(card => isOnTopic(state, card)).length);
return onTopic[0] === onTopic[1] ? null : onTopic[0] > onTopic[1] ? 0 : 1;
}
/** Number of Topics each seat leads right now (with the consensus tie-break). */
export function topicsLed(state: MatchState): [number, number] {
const led: [number, number] = [0, 0];
state.lanes.forEach((_, lane) => {
const leader = laneLeader(state, lane);
if (leader !== null) led[leader]++;
});
return led;
}
/** Final lane powers: lanePower plus revealed "at scoring" Portals (§7, §10.3). */
export function scoringPower(state: MatchState, lane: number): [number, number] {
const power = lanePower(state, lane);
const portal = activePortal(state, lane);
if (!portal?.atScoring) return power;
const [d0, d1] = portal.atScoring(portalCtx(state, new Rng(state.rng), lane, portal, state.initiative));
return [power[0] + d0, power[1] + d1];
}
// ---------- actions (§5.3) ----------
const queuedCost = (p: PlayerState) => p.queue.reduce((sum, play) => sum + (p.hand.find(c => c.cardId === play.cardId)?.cost ?? 0), 0);
const queuedInLane = (p: PlayerState, lane: number) => p.queue.filter(play => play.lane === lane).length;
function laneRejects(state: MatchState, lane: number, card: GameCard, player: PlayerId): string | null {
const portal = activePortal(state, lane);
if (!portal?.canPlay) return null;
return portal.canPlay(portalCtx(state, new Rng(state.rng), lane, portal, player), card, player) ? null : `${portal.name} rejects this card`;
}
function playProblem(state: MatchState, action: Extract<Action, { type: 'play' }>): string | null {
const p = state.players[action.player];
if (p.committed) return 'Already committed this turn';
const card = p.hand.find(c => c.cardId === action.cardId);
if (!card) return 'Card is not in your hand';
if (p.queue.some(play => play.cardId === action.cardId)) return 'Card is already queued';
if (!Number.isInteger(action.lane) || action.lane < 0 || action.lane >= state.lanes.length) return 'No such Topic';
if (card.cost > p.energy - queuedCost(p)) return 'Not enough energy';
if (state.lanes[action.lane].cards[action.player].length + queuedInLane(p, action.lane) >= laneCapacity(state, action.lane)) return 'Topic is full';
return laneRejects(state, action.lane, card, action.player);
}
/** Why `action` is illegal in `state`, or null if it is legal. */
export function actionProblem(state: MatchState, action: Action): string | null {
if (state.phase === 'over') return 'Match is over';
if (!action || (action.player !== 0 && action.player !== 1)) return 'Unknown player';
const p = state.players[action.player];
switch (action.type) {
case 'play': return playProblem(state, action);
case 'undo':
if (p.committed) return 'Already committed this turn';
return p.queue.some(play => play.cardId === action.cardId) ? null : 'Card is not queued';
case 'commit':
case 'timeout':
return p.committed ? 'Already committed this turn' : null;
case 'concede': return null;
default: return 'Unknown action';
}
}
/**
* Legal actions for `player`: every `play`, every `undo`, and `commit`.
* `concede` (always legal while running) and `timeout` (host-only) are not listed.
* Empty once the player has committed or the match is over.
*/
export function legalActions(state: MatchState, player: PlayerId): Action[] {
if (state.phase === 'over') return [];
const p = state.players[player];
if (p.committed) return [];
const actions: Action[] = [];
for (const card of p.hand) {
if (p.queue.some(play => play.cardId === card.cardId)) continue;
for (let lane = 0; lane < state.lanes.length; lane++) {
const action: Action = { type: 'play', player, cardId: card.cardId, lane };
if (!playProblem(state, action)) actions.push(action);
}
}
for (const play of p.queue) actions.push({ type: 'undo', player, cardId: play.cardId });
actions.push({ type: 'commit', player });
return actions;
}
/** Apply one action and return the new state. Throws IllegalActionError if illegal. */
export function applyAction(state: MatchState, action: Action): MatchState {
const problem = actionProblem(state, action);
if (problem) throw new IllegalActionError(problem);
const next = clone(state);
next.actions.push(clone(action));
const p = next.players[action.player];
const rng = new Rng(next.rng);
switch (action.type) {
case 'play': p.queue.push({ cardId: action.cardId, lane: action.lane }); break;
case 'undo': p.queue.splice(p.queue.findIndex(play => play.cardId === action.cardId), 1); break;
case 'commit': p.committed = true; p.afk = 0; break;
case 'timeout':
p.committed = true;
p.afk = p.queue.length ? 0 : p.afk + 1;
if (p.afk >= next.ruleset.afkTurns) {
next.log.push({ t: 'concede', player: action.player, afk: true });
finish(next, other(action.player), 'afk');
}
break;
case 'concede':
next.log.push({ t: 'concede', player: action.player, afk: false });
finish(next, other(action.player), 'concede');
break;
}
if (next.phase !== 'over' && next.players.every(player => player.committed)) resolveTurn(next, rng);
next.rng = rng.state;
return next;
}
/** §5.4 Reveal (interleaved) and §5.5 End. */
function resolveTurn(state: MatchState, rng: Rng): void {
const rules = state.ruleset;
const order: PlayerId[] = [state.initiative, other(state.initiative)];
// Carry (§5.1): energy not reserved by a queued play. Fizzled plays still spent theirs.
for (const player of PLAYERS) {
const p = state.players[player];
p.carry = Math.min(rules.energyCarryMax, Math.max(0, p.energy - queuedCost(p)));
}
const queues = order.map(player => state.players[player].queue.slice());
for (let i = 0; i < Math.max(queues[0].length, queues[1].length); i++) {
for (const [k, player] of order.entries()) {
const play = queues[k][i];
if (play) reveal(state, rng, player, play.cardId, play.lane);
}
}
for (const player of PLAYERS) state.players[player].queue = [];
for (const player of order) for (const lane of state.lanes) {
for (const card of lane.cards[player].slice().sort((x, y) => x.seq - y.seq)) {
const keyword = keywordOf(state, card.card);
keyword?.endOfTurn?.(keywordCtx(state, rng, keyword, card), card);
}
}
if (state.turn >= rules.turns) finish(state, null, 'topics');
else startTurn(state, rng);
}
function reveal(state: MatchState, rng: Rng, player: PlayerId, cardId: string, lane: number): void {
const p = state.players[player];
const index = p.hand.findIndex(c => c.cardId === cardId);
const card = p.hand[index];
if (index < 0 || state.lanes[lane].cards[player].length >= laneCapacity(state, lane) || laneRejects(state, lane, card, player)) {
state.log.push({ t: 'fizzle', player, cardId, lane }); // stays in hand, energy lost
return;
}
p.hand.splice(index, 1);
const inPlay: CardInPlay = { card, owner: player, lane, turn: state.turn, seq: ++state.revealSeq, bonus: 0 };
state.lanes[lane].cards[player].push(inPlay);
state.log.push({ t: 'reveal', player, cardId, lane });
const keyword = keywordOf(state, card);
keyword?.onReveal?.(keywordCtx(state, rng, keyword, inPlay), inPlay);
const portal = activePortal(state, lane);
portal?.onReveal?.(portalCtx(state, rng, lane, portal, player), inPlay);
}
/** §7 scoring (after the last End phase, with "at scoring" Portals), or a concede. */
function finish(state: MatchState, forcedWinner: PlayerId | null, reason: 'topics' | 'concede' | 'afk'): void {
const lanePowers = state.lanes.map((_, lane) => scoringPower(state, lane));
const led: [number, number] = [0, 0];
const totalPower: [number, number] = [0, 0];
lanePowers.forEach((power, lane) => {
const leader = laneLeader(state, lane, power);
if (leader !== null) led[leader]++;
totalPower[0] += power[0]; totalPower[1] += power[1];
});
let winner: PlayerId | null = forcedWinner;
let why: MatchResult['reason'] = reason;
if (reason === 'topics') {
if (led[0] !== led[1]) winner = led[0] > led[1] ? 0 : 1;
else if (totalPower[0] !== totalPower[1]) { winner = totalPower[0] > totalPower[1] ? 0 : 1; why = 'totalPower'; }
else why = 'draw';
}
state.result = { winner, reason: why, topicsLed: led, lanePower: lanePowers, totalPower, turns: state.turn };
state.phase = 'over';
state.log.push({ t: 'matchOver', result: clone(state.result) });
}
// ---------- queries ----------
export function isOver(state: MatchState): boolean { return state.phase === 'over'; }
/** The final result, or null while the match is running. */
export function result(state: MatchState): MatchResult | null { return state.result; }
/** Hidden-information view for one seat. Send only this to clients and AIs. */
export function viewFor(state: MatchState, you: PlayerId): PlayerView {
const them = other(you);
const me = state.players[you], opp = state.players[them];
return clone({
you, ruleset: state.ruleset, turn: state.turn, phase: state.phase, initiative: state.initiative,
energy: me.energy, energyLeft: me.energy - queuedCost(me), hand: me.hand, queue: me.queue,
committed: me.committed, deckCount: me.deck.length,
opponent: { handCount: opp.hand.length, deckCount: opp.deck.length, committed: opp.committed },
lanes: state.lanes.map((lane, index) => {
const power = lanePower(state, index);
const mine = power[you], theirs = power[them];
const leader = laneLeader(state, index, power);
return {
// Until its Portal is revealed only the stat is visible (the id/name would give the Portal away).
topic: lane.portalRevealed ? lane.topic : { id: `lane-${index + 1}`, name: '?', stat: lane.topic.stat, portal: null },
portalRevealed: lane.portalRevealed,
cards: [lane.cards[you], lane.cards[them]] as [CardInPlay[], CardInPlay[]],
cardPower: [lane.cards[you].map(c => cardPower(state, c)), lane.cards[them].map(c => cardPower(state, c))] as [number[], number[]],
power: [mine, theirs] as [number, number],
leader: leader === null ? null : leader === you ? 'you' as const : 'opponent' as const,
};
}),
result: state.result,
});
}
// ---------- serialisation, replay, test helpers ----------
export function serialize(state: MatchState): string { return JSON.stringify(state); }
export function deserialize(json: string): MatchState {
const state = JSON.parse(json) as MatchState;
if (state?.schema !== 'wikideck-match/1') throw new Error('Not a wikideck-match/1 state');
state.ruleset = parseRuleset(state.ruleset);
return state;
}
/** Rebuild a match from its inputs; a host can verify a reported result this way. */
export function replay(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: number | string, actions: readonly Action[]): MatchState {
let state = createMatch(ruleset, decks, seed);
for (const action of actions) state = applyAction(state, action);
return state;
}
/**
* Test helper: put `card` straight into a lane (no on-reveal, no energy, no hand).
* Returns a new state. For unit-testing keywords against hand-built boards.
*/
export function placeCard(state: MatchState, player: PlayerId, lane: number, card: GameCard, bonus = 0): MatchState {
const next = clone(state);
next.lanes[lane].cards[player].push({ card: clone(card), owner: player, lane, turn: next.turn, seq: ++next.revealSeq, bonus });
return next;
}
/** Test helper: reveal a Topic's Portal now (runs nothing). */
export function revealPortal(state: MatchState, lane: number): MatchState {
const next = clone(state);
next.lanes[lane].portalRevealed = true;
return next;
}