forked from WikiDeck/wikideck
mulberry32 uint32 seed with the §4 draw order, Topics with stats and Portals, staggered reveal, initiative and underdog rules, queue/undo/commit/timeout actions, §9 flat RulesConfig with zod bounds, viewFor hidden info, replay. cards.ts left to engine-b; placeholder loaners in starter.ts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
391 lines
19 KiB
TypeScript
391 lines
19 KiB
TypeScript
/**
|
||
* 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, PORTALS, type EffectContext } 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']);
|
||
|
||
// ---------- 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<number, 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 (!Number.isInteger(card.pageId)) problems.push(`${label}: bad 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 && !Object.hasOwn(KEYWORDS, card.keyword)) problems.push(`${label}: unknown keyword ${card.keyword}`);
|
||
if (card.source !== 'owned' && card.source !== 'loaner') problems.push(`${label}: bad source`);
|
||
if (card.source === 'loaner') loaners++;
|
||
const n = (copies.get(card.pageId) ?? 0) + 1;
|
||
copies.set(card.pageId, n);
|
||
if (n === rules.maxCopiesPerPage + 1) problems.push(`More than ${rules.maxCopiesPerPage} copies of page ${card.pageId}`);
|
||
}
|
||
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,
|
||
});
|
||
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, players: [p0, p1],
|
||
lanes: topics.map(topic => ({ topic: clone(topic), revealed: 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 }) };
|
||
}
|
||
|
||
function portalOf(state: MatchState, lane: number) {
|
||
const l = state.lanes[lane];
|
||
return l?.revealed && l.topic.portal ? PORTALS[l.topic.portal] : undefined;
|
||
}
|
||
|
||
/** §5.1 Start, then §5.2 Underdog. */
|
||
function startTurn(state: MatchState, rng: Rng): void {
|
||
state.turn += 1;
|
||
const rules = state.ruleset;
|
||
state.lanes.forEach((lane, index) => {
|
||
if (lane.revealed || (rules.revealSchedule[index] ?? 1) > state.turn) return;
|
||
lane.revealed = true;
|
||
state.log.push({ t: 'topicRevealed', lane: index, topic: clone(lane.topic) });
|
||
const portal = portalOf(state, index);
|
||
portal?.onTopicReveal?.(context(state, rng, rules.portalParams[portal.id], index, portal.id, state.initiative));
|
||
});
|
||
const base = (rules.energyByTurn[state.turn - 1] ?? rules.energyByTurn.at(-1)!) + rules.bonusEnergy;
|
||
for (const player of PLAYERS) Object.assign(state.players[player], { energy: base, 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 (never below 0). */
|
||
export function cardPower(state: MatchState, target: CardInPlay): number {
|
||
const rules = state.ruleset;
|
||
const lane = state.lanes[target.lane];
|
||
const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness
|
||
let power = target.card.power + target.bonus + target.card.trend;
|
||
if (lane.revealed && lane.topic.stat === target.card.home) power += rules.onTopicBonus;
|
||
for (const l of state.lanes) for (const side of l.cards) for (const source of side) {
|
||
const keyword = source.card.keyword ? KEYWORDS[source.card.keyword] : undefined;
|
||
if (keyword?.ongoing) power += keyword.ongoing(context(state, scratch, rules.keywordParams[keyword.id], source.lane, keyword.id, source.owner), source, target);
|
||
}
|
||
const portal = portalOf(state, target.lane);
|
||
if (portal?.ongoing) power += portal.ongoing(context(state, scratch, rules.portalParams[portal.id], target.lane, portal.id, target.owner), target);
|
||
return Math.max(0, power);
|
||
}
|
||
|
||
/** [seat 0 power, seat 1 power] in one lane. */
|
||
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];
|
||
}
|
||
|
||
/** Number of Topics each seat leads (strictly more power). */
|
||
export function topicsLed(state: MatchState): [number, number] {
|
||
const led: [number, number] = [0, 0];
|
||
state.lanes.forEach((_, lane) => {
|
||
const [a, b] = lanePower(state, lane);
|
||
if (a > b) led[0]++; else if (b > a) led[1]++;
|
||
});
|
||
return led;
|
||
}
|
||
|
||
// ---------- 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 = portalOf(state, lane);
|
||
if (!portal?.canPlay) return null;
|
||
const ctx = context(state, new Rng(state.rng), state.ruleset.portalParams[portal.id], lane, portal.id, player);
|
||
return portal.canPlay(ctx, 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) >= state.ruleset.laneCapacity) 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 and §5.5 End. */
|
||
function resolveTurn(state: MatchState, rng: Rng): void {
|
||
const rules = state.ruleset;
|
||
const order: PlayerId[] = [state.initiative, other(state.initiative)];
|
||
for (const player of order) {
|
||
const p = state.players[player];
|
||
for (const play of p.queue) {
|
||
const index = p.hand.findIndex(c => c.cardId === play.cardId);
|
||
const card = p.hand[index];
|
||
if (index < 0 || state.lanes[play.lane].cards[player].length >= rules.laneCapacity || laneRejects(state, play.lane, card, player)) {
|
||
state.log.push({ t: 'fizzle', player, cardId: play.cardId, lane: play.lane }); // stays in hand, energy lost
|
||
continue;
|
||
}
|
||
p.hand.splice(index, 1);
|
||
const inPlay: CardInPlay = { card, owner: player, lane: play.lane, turn: state.turn, bonus: 0 };
|
||
state.lanes[play.lane].cards[player].push(inPlay);
|
||
state.log.push({ t: 'reveal', player, cardId: card.cardId, lane: play.lane });
|
||
const keyword = card.keyword ? KEYWORDS[card.keyword] : undefined;
|
||
keyword?.onReveal?.(context(state, rng, rules.keywordParams[keyword.id], play.lane, keyword.id, player), inPlay);
|
||
const portal = portalOf(state, play.lane);
|
||
portal?.onReveal?.(context(state, rng, rules.portalParams[portal.id], play.lane, portal.id, player), inPlay);
|
||
}
|
||
p.queue = [];
|
||
}
|
||
for (const player of order) for (const lane of state.lanes) for (const card of lane.cards[player].slice()) {
|
||
const keyword = card.card.keyword ? KEYWORDS[card.card.keyword] : undefined;
|
||
keyword?.endOfTurn?.(context(state, rng, rules.keywordParams[keyword.id], card.lane, keyword.id, player), card);
|
||
}
|
||
if (state.turn >= rules.turns) { finish(state, null, 'topics'); return; }
|
||
const led = topicsLed(state);
|
||
state.initiative = led[0] !== led[1] ? (led[0] > led[1] ? 0 : 1) : other(state.initiative);
|
||
startTurn(state, rng);
|
||
}
|
||
|
||
/** §7. */
|
||
function finish(state: MatchState, forcedWinner: PlayerId | null, reason: 'topics' | 'concede' | 'afk'): void {
|
||
const lanePowers = state.lanes.map((_, lane) => lanePower(state, lane));
|
||
const topicsLedNow = topicsLed(state);
|
||
const totalPower: [number, number] = [0, 0];
|
||
for (const [a, b] of lanePowers) { totalPower[0] += a; totalPower[1] += b; }
|
||
let winner: PlayerId | null = forcedWinner;
|
||
let why: MatchResult['reason'] = reason;
|
||
if (reason === 'topics') {
|
||
if (topicsLedNow[0] !== topicsLedNow[1]) winner = topicsLedNow[0] > topicsLedNow[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: topicsLedNow, 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 - opp.queue.length, deckCount: opp.deck.length, queuedCount: opp.queue.length, committed: opp.committed },
|
||
lanes: state.lanes.map((lane, index) => {
|
||
const power = lanePower(state, index);
|
||
const mine = power[you], theirs = power[them];
|
||
return {
|
||
topic: lane.revealed ? lane.topic : null,
|
||
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: mine > theirs ? 'you' as const : theirs > mine ? 'opponent' as const : null,
|
||
};
|
||
}),
|
||
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, bonus });
|
||
return next;
|
||
}
|
||
|
||
/** Test helper: flip a Topic face-up (runs nothing). */
|
||
export function revealTopic(state: MatchState, lane: number): MatchState {
|
||
const next = clone(state);
|
||
next.lanes[lane].revealed = true;
|
||
return next;
|
||
}
|