forked from WikiDeck/wikideck
Pure deterministic off-chain engine in shared/game: createMatch, legalActions, applyAction, isOver, result, viewFor, serialize/deserialize, replay. Placeholder Snap-style lanes rules until DESIGN.md v1; keyword hook registry for engine-b. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
325 lines
15 KiB
TypeScript
325 lines
15 KiB
TypeScript
/**
|
||
* WikiDeck game engine core: pure, deterministic, off-chain.
|
||
* Every exported function treats its inputs as immutable and returns new data.
|
||
* All randomness comes from the match seed via state.rng.
|
||
* Contract: docs/game/ENGINE_API.md.
|
||
*/
|
||
import { KEYWORDS, LANE_MODIFIERS, type EffectContext } from './keywords.ts';
|
||
import { Rng, seedRng } from './rng.ts';
|
||
import { energyForTurn, parseRuleset } from './ruleset.ts';
|
||
import {
|
||
IllegalActionError, PLAYERS,
|
||
type Action, type CardInPlay, type GameCard, type MatchResult, type MatchState,
|
||
type PlayerId, type PlayerState, type PlayerView, type Ruleset,
|
||
} from './types.ts';
|
||
|
||
export const ENGINE_VERSION = 1;
|
||
|
||
const other = (player: PlayerId): PlayerId => (player === 0 ? 1 : 0);
|
||
const clone = <T>(value: T): T => structuredClone(value);
|
||
|
||
// ---------- validation ----------
|
||
|
||
export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[] {
|
||
const problems: string[] = [];
|
||
if (deck.length < rules.deck.min || deck.length > rules.deck.max)
|
||
problems.push(`Deck must have ${rules.deck.min === rules.deck.max ? rules.deck.min : `${rules.deck.min}–${rules.deck.max}`} cards (has ${deck.length})`);
|
||
const ids = new Set<string>();
|
||
const copies = new Map<number, number>();
|
||
for (const card of deck) {
|
||
if (typeof card?.id !== 'string' || !card.id || card.id.length > 128) { problems.push('Card id must be a non-empty string'); continue; }
|
||
if (ids.has(card.id)) problems.push(`Duplicate card id ${card.id}`);
|
||
ids.add(card.id);
|
||
if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 20) problems.push(`Card ${card.id}: bad cost`);
|
||
if (!Number.isInteger(card.power) || card.power < -100 || card.power > 100) problems.push(`Card ${card.id}: bad power`);
|
||
if (card.pageId !== null) {
|
||
const n = (copies.get(card.pageId) ?? 0) + 1;
|
||
copies.set(card.pageId, n);
|
||
if (n === rules.deck.maxCopiesPerPage + 1) problems.push(`More than ${rules.deck.maxCopiesPerPage} copies of page ${card.pageId}`);
|
||
}
|
||
}
|
||
return problems;
|
||
}
|
||
|
||
// ---------- match setup ----------
|
||
|
||
/**
|
||
* Start a match. `decks[0]` belongs to player 0. Throws IllegalActionError for an
|
||
* invalid deck and ZodError for an invalid ruleset.
|
||
*/
|
||
export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: string): MatchState {
|
||
const rules = parseRuleset(clone(ruleset));
|
||
if (typeof seed !== 'string' || !seed) throw new IllegalActionError('Seed must be a non-empty string');
|
||
for (const player of PLAYERS) {
|
||
const problems = validateDeck(rules, decks[player] ?? []);
|
||
if (problems.length) throw new IllegalActionError(`Player ${player} deck: ${problems.join('; ')}`);
|
||
}
|
||
const rng = new Rng(seedRng(seed));
|
||
const modifiers = rules.laneModifiers.pool.length ? rng.shuffle(rules.laneModifiers.pool).slice(0, rules.lanes) : [];
|
||
const newPlayer = (player: PlayerId): PlayerState => ({
|
||
deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, staged: [], ended: false, discard: [],
|
||
});
|
||
const players: [PlayerState, PlayerState] = [newPlayer(0), newPlayer(1)];
|
||
const state: MatchState = {
|
||
schema: 'wikideck-match/1', ruleset: rules, seed, rng: rng.state, turn: 0, phase: 'planning',
|
||
firstToReveal: rng.int(2) as PlayerId, players,
|
||
lanes: Array.from({ length: rules.lanes }, (_, lane) => ({ modifier: modifiers[lane] ?? null, cards: [[], []] as [CardInPlay[], CardInPlay[]] })),
|
||
log: [], actions: [], result: null,
|
||
};
|
||
for (const player of PLAYERS) for (let i = 0; i < rules.hand.start; 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.hand.max) return;
|
||
const card = p.deck.shift()!;
|
||
p.hand.push(card);
|
||
state.log.push({ t: 'draw', player, cardId: card.id });
|
||
}
|
||
|
||
function startTurn(state: MatchState, rng: Rng): void {
|
||
state.turn += 1;
|
||
const energy = energyForTurn(state.ruleset, state.turn);
|
||
if (state.turn > 1) state.firstToReveal = leader(state, rng);
|
||
for (const player of PLAYERS) Object.assign(state.players[player], { energy, staged: [], ended: false });
|
||
state.log.push({ t: 'turnStart', turn: state.turn, energy: [energy, energy] });
|
||
state.ruleset.laneModifiers.revealTurns.forEach((turn, lane) => {
|
||
if (turn === state.turn) state.log.push({ t: 'laneRevealed', lane, modifier: state.lanes[lane].modifier });
|
||
});
|
||
for (const player of PLAYERS) for (let i = 0; i < state.ruleset.hand.drawPerTurn; i++) draw(state, player);
|
||
}
|
||
|
||
/** Player winning more lanes reveals first; then higher total power; then a seeded coin flip. */
|
||
function leader(state: MatchState, rng: Rng): PlayerId {
|
||
const { lanesWon, totalPower } = score(state);
|
||
if (lanesWon[0] !== lanesWon[1]) return lanesWon[0] > lanesWon[1] ? 0 : 1;
|
||
if (totalPower[0] !== totalPower[1]) return totalPower[0] > totalPower[1] ? 0 : 1;
|
||
return rng.int(2) as PlayerId;
|
||
}
|
||
|
||
// ---------- power ----------
|
||
|
||
export function modifierActive(state: MatchState, lane: number): boolean {
|
||
const revealTurn = state.ruleset.laneModifiers.revealTurns[lane] ?? 1;
|
||
return state.lanes[lane]?.modifier != null && state.turn >= revealTurn;
|
||
}
|
||
|
||
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 keywordOf(state: MatchState, card: GameCard) {
|
||
return card.keyword && Object.hasOwn(state.ruleset.keywords, card.keyword) ? KEYWORDS[card.keyword] : undefined;
|
||
}
|
||
|
||
/** Current power of one card in play, including ongoing keyword and lane effects. */
|
||
export function cardPower(state: MatchState, target: CardInPlay): number {
|
||
const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness
|
||
let power = target.card.power + target.bonus;
|
||
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(context(state, scratch, state.ruleset.keywords[keyword.id], source.lane, keyword.id, source.owner), source, target);
|
||
}
|
||
const lane = state.lanes[target.lane];
|
||
if (modifierActive(state, target.lane)) {
|
||
const modifier = LANE_MODIFIERS[lane.modifier!];
|
||
if (modifier?.ongoing) power += modifier.ongoing(context(state, scratch, state.ruleset.laneModifiers.params[modifier.id], target.lane, modifier.id, target.owner), target);
|
||
}
|
||
return power;
|
||
}
|
||
|
||
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];
|
||
}
|
||
|
||
function score(state: MatchState): Omit<MatchResult, 'winner' | 'reason' | 'turns'> {
|
||
const powers = state.lanes.map((_, lane) => lanePower(state, lane));
|
||
const lanesWon: [number, number] = [0, 0];
|
||
const totalPower: [number, number] = [0, 0];
|
||
for (const [a, b] of powers) {
|
||
if (a > b) lanesWon[0]++; else if (b > a) lanesWon[1]++;
|
||
totalPower[0] += a; totalPower[1] += b;
|
||
}
|
||
return { lanesWon, lanePower: powers, totalPower };
|
||
}
|
||
|
||
// ---------- actions ----------
|
||
|
||
function stagedInLane(p: PlayerState, lane: number): number {
|
||
return p.staged.filter(play => play.lane === lane).length;
|
||
}
|
||
|
||
function playProblem(state: MatchState, action: Extract<Action, { type: 'play' }>): string | null {
|
||
const p = state.players[action.player];
|
||
if (p.ended) return 'You already ended your turn';
|
||
const card = p.hand.find(c => c.id === action.cardId);
|
||
if (!card) return 'Card is not in your hand';
|
||
if (p.staged.some(play => play.cardId === action.cardId)) return 'Card is already staged';
|
||
if (!Number.isInteger(action.lane) || action.lane < 0 || action.lane >= state.lanes.length) return 'No such lane';
|
||
if (card.cost > p.energy) return 'Not enough energy';
|
||
if (state.lanes[action.lane].cards[action.player].length + stagedInLane(p, action.lane) >= state.ruleset.laneCapacity) return 'Lane is full';
|
||
if (modifierActive(state, action.lane)) {
|
||
const modifier = LANE_MODIFIERS[state.lanes[action.lane].modifier!];
|
||
const ctx = context(state, new Rng(state.rng), state.ruleset.laneModifiers.params[modifier?.id ?? ''], action.lane, modifier?.id ?? '', action.player);
|
||
if (modifier?.canPlay && !modifier.canPlay(ctx, card, action.player)) return `${modifier.name} lane rejects this card`;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** 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';
|
||
switch (action.type) {
|
||
case 'play': return playProblem(state, action);
|
||
case 'unstage': {
|
||
const p = state.players[action.player];
|
||
if (p.ended) return 'You already ended your turn';
|
||
return p.staged.some(play => play.cardId === action.cardId) ? null : 'Card is not staged';
|
||
}
|
||
case 'endTurn': return state.players[action.player].ended ? 'You already ended your turn' : null;
|
||
case 'concede': return null;
|
||
default: return 'Unknown action';
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Every legal action for `player` except `concede` (always legal while the match
|
||
* is running). `endTurn` is always included while the player hasn't ended.
|
||
*/
|
||
export function legalActions(state: MatchState, player: PlayerId): Action[] {
|
||
if (state.phase === 'over') return [];
|
||
const p = state.players[player];
|
||
if (p.ended) return [];
|
||
const actions: Action[] = [];
|
||
for (const card of p.hand) {
|
||
if (p.staged.some(play => play.cardId === card.id)) continue;
|
||
for (let lane = 0; lane < state.lanes.length; lane++) {
|
||
const action: Action = { type: 'play', player, cardId: card.id, lane };
|
||
if (!playProblem(state, action)) actions.push(action);
|
||
}
|
||
}
|
||
for (const play of p.staged) actions.push({ type: 'unstage', player, cardId: play.cardId });
|
||
actions.push({ type: 'endTurn', 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.staged.push({ cardId: action.cardId, lane: action.lane });
|
||
p.energy -= p.hand.find(c => c.id === action.cardId)!.cost;
|
||
break;
|
||
}
|
||
case 'unstage': {
|
||
const index = p.staged.findIndex(play => play.cardId === action.cardId);
|
||
p.staged.splice(index, 1);
|
||
p.energy += p.hand.find(c => c.id === action.cardId)!.cost;
|
||
break;
|
||
}
|
||
case 'endTurn': {
|
||
p.ended = true;
|
||
if (next.players.every(player => player.ended)) resolveTurn(next, rng);
|
||
break;
|
||
}
|
||
case 'concede': {
|
||
next.log.push({ t: 'concede', player: action.player });
|
||
finish(next, other(action.player), 'concede');
|
||
break;
|
||
}
|
||
}
|
||
next.rng = rng.state;
|
||
return next;
|
||
}
|
||
|
||
function resolveTurn(state: MatchState, rng: Rng): void {
|
||
for (const player of [state.firstToReveal, other(state.firstToReveal)]) {
|
||
const p = state.players[player];
|
||
for (const play of p.staged) {
|
||
const index = p.hand.findIndex(c => c.id === play.cardId);
|
||
const [card] = 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.id, lane: play.lane });
|
||
const keyword = keywordOf(state, card);
|
||
keyword?.onReveal?.(context(state, rng, state.ruleset.keywords[keyword.id], play.lane, keyword.id, player), inPlay);
|
||
if (modifierActive(state, play.lane)) {
|
||
const modifier = LANE_MODIFIERS[state.lanes[play.lane].modifier!];
|
||
modifier?.onReveal?.(context(state, rng, state.ruleset.laneModifiers.params[modifier.id], play.lane, modifier.id, player), inPlay);
|
||
}
|
||
}
|
||
p.staged = [];
|
||
}
|
||
if (state.turn >= state.ruleset.maxTurns) finish(state, null, 'lanes');
|
||
else startTurn(state, rng);
|
||
}
|
||
|
||
function finish(state: MatchState, concedeWinner: PlayerId | null, reason: 'lanes' | 'concede'): void {
|
||
const s = score(state);
|
||
let winner: PlayerId | null = concedeWinner;
|
||
let why: MatchResult['reason'] = reason;
|
||
if (reason !== 'concede') {
|
||
if (s.lanesWon[0] !== s.lanesWon[1]) winner = s.lanesWon[0] > s.lanesWon[1] ? 0 : 1;
|
||
else if (state.ruleset.tieBreak === 'totalPower' && s.totalPower[0] !== s.totalPower[1]) {
|
||
winner = s.totalPower[0] > s.totalPower[1] ? 0 : 1; why = 'totalPower';
|
||
} else why = 'draw';
|
||
}
|
||
state.result = { winner, reason: why, ...s, turns: state.turn };
|
||
state.phase = 'over';
|
||
state.log.push({ t: 'matchOver', result: 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 player. UI and AI should only ever read this. */
|
||
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, firstToReveal: state.firstToReveal,
|
||
energy: me.energy, hand: me.hand, staged: me.staged, ended: me.ended, deckCount: me.deck.length,
|
||
opponent: { handCount: opp.hand.length - opp.staged.length, deckCount: opp.deck.length, stagedCount: opp.staged.length, ended: opp.ended },
|
||
lanes: state.lanes.map((lane, index) => {
|
||
const revealed = modifierActive(state, index);
|
||
const power = lanePower(state, index);
|
||
return {
|
||
modifier: revealed ? lane.modifier : null, modifierRevealed: revealed,
|
||
cards: [lane.cards[you], lane.cards[them]] as [CardInPlay[], CardInPlay[]],
|
||
power: [power[you], power[them]] as [number, number],
|
||
};
|
||
}),
|
||
result: state.result,
|
||
});
|
||
}
|
||
|
||
// ---------- serialisation / replay ----------
|
||
|
||
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: string, actions: readonly Action[]): MatchState {
|
||
return actions.reduce(applyAction, createMatch(ruleset, decks, seed));
|
||
}
|