diff --git a/shared/game/cards.ts b/shared/game/cards.ts new file mode 100644 index 0000000..894b126 --- /dev/null +++ b/shared/game/cards.ts @@ -0,0 +1,92 @@ +/** + * Turning WikiDeck data into GameCards, and starter decks for players with no NFTs. + * PLACEHOLDER numbers until docs/game/DESIGN.md v1; engine-b tunes the mapping. + * Starter cards are offline preview cards: not NFTs, never minted or moved. + */ +import { Rng } from './rng.ts'; +import { DEFAULT_RULESET } from './ruleset.ts'; +import type { Category, GameCard, Ruleset } from './types.ts'; + +type StarterSpec = [pageId: number, name: string, category: Category, cost: number, power: number, keyword: string | null]; + +/** 24 curated preview cards, 4 per cost 1–6. pageIds outside shared/catalog.ts are unverified (display only). */ +export const STARTER_POOL: readonly StarterSpec[] = [ + [22780, 'Octopus', 'Nature', 1, 2, null], + [19331, 'Moon', 'Space', 1, 1, 'anchor'], + [23053, 'Periodic table', 'Science', 1, 2, null], + [3383, 'Bronze Age', 'History', 1, 1, 'rally'], + [5843419, 'Chess', 'Culture', 2, 3, null], + [9228, 'Earth', 'Space', 2, 2, 'rally'], + [2008, 'Ada Lovelace', 'People', 2, 4, null], + [21830, 'Honey bee', 'Nature', 2, 3, 'anchor'], + [736, 'Albert Einstein', 'People', 3, 5, null], + [10979, 'Fungus', 'Nature', 3, 4, 'rally'], + [26903, 'Solar System', 'Space', 3, 6, null], + [30758, 'Roman Empire', 'History', 3, 4, 'anchor'], + [9649, 'Evolution', 'Science', 4, 7, null], + [8424, 'Jazz', 'Culture', 4, 6, 'rally'], + [12898, 'Marie Curie', 'People', 4, 8, null], + [14533, 'Silk Road', 'History', 4, 6, 'anchor'], + [19468, 'Mount Everest', 'Nature', 5, 9, null], + [22936, 'Photosynthesis', 'Science', 5, 8, 'rally'], + [18110, 'Leonardo da Vinci', 'People', 5, 10, null], + [14627, 'Ancient Egypt', 'History', 5, 8, 'anchor'], + [4177, 'Black hole', 'Space', 6, 12, null], + [25443, 'Quantum mechanics', 'Science', 6, 11, 'rally'], + [17867, 'Library of Alexandria', 'History', 6, 11, 'anchor'], + [20217, 'Music', 'Culture', 6, 12, null], +]; + +export function starterCard(spec: StarterSpec, copy = 0): GameCard { + const [pageId, name, category, cost, power, keyword] = spec; + return { id: `starter:${pageId}:${copy}`, name, pageId, category, cost, power, keyword, source: 'starter' }; +} + +/** + * A deterministic starter deck: 2 cards of each cost 1–6 (for a 12-card deck), + * drawn from STARTER_POOL by `seed`. Cards whose keyword the ruleset doesn't + * enable still play (as vanilla). Fills to ruleset.deck.min. + */ +export function starterDeck(seed: string, rules: Ruleset = DEFAULT_RULESET): GameCard[] { + const rng = Rng.fromSeed(`starter:${seed}`); + const byCost = new Map(); + for (const spec of STARTER_POOL) byCost.set(spec[3], [...(byCost.get(spec[3]) ?? []), spec]); + const picks: StarterSpec[] = []; + const costs = [...byCost.keys()].sort((a, b) => a - b); + for (const cost of costs) picks.push(...rng.shuffle(byCost.get(cost)!).slice(0, 2)); + const deck = rng.shuffle(picks).slice(0, rules.deck.max).map(spec => starterCard(spec)); + // Pad for modes with bigger decks, respecting maxCopiesPerPage. + let copy = 1; + while (deck.length < rules.deck.min && copy < rules.deck.maxCopiesPerPage) { + for (const spec of rng.shuffle(STARTER_POOL)) { + if (deck.length >= rules.deck.min) break; + deck.push(starterCard(spec, copy)); + } + copy++; + } + return deck; +} + +/** Input for an owned card; matches PageEnrichment / MintStatsSnapshot fields (shared/enrichment.ts). */ +export interface CardSource { + id: string; + title: string; + pageId: number; + category: Category; + stats: { attention: number | null; depth: number; reach: number }; +} + +/** + * PLACEHOLDER stat → card mapping (DESIGN.md will replace it). Famous cards cost + * more (sidegrade): cost from the mean score, power = 2·cost (+1 if no keyword). + */ +export function cardFromStats(source: CardSource): GameCard { + const { attention, depth, reach } = source.stats; + const mean = ((attention ?? 0) + depth + reach) / 3; + const cost = Math.max(1, Math.min(6, Math.ceil(mean / (100 / 6)))); + const keyword = depth >= reach && depth >= (attention ?? 0) ? 'anchor' : reach >= (attention ?? 0) ? 'rally' : null; + return { + id: source.id, name: source.title, pageId: source.pageId, category: source.category, + cost, power: 2 * cost + (keyword ? 0 : 1), keyword, source: 'owned', + }; +} diff --git a/shared/game/engine.ts b/shared/game/engine.ts new file mode 100644 index 0000000..dfea21f --- /dev/null +++ b/shared/game/engine.ts @@ -0,0 +1,324 @@ +/** + * 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 = (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(); + const copies = new Map(); + 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 | 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 { + 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): 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)); +} diff --git a/shared/game/index.ts b/shared/game/index.ts new file mode 100644 index 0000000..8891a8e --- /dev/null +++ b/shared/game/index.ts @@ -0,0 +1,10 @@ +/** Public entry point of the WikiDeck game engine. See docs/game/ENGINE_API.md. */ +export * from './types.ts'; +export { Rng, seedRng, type RngState } from './rng.ts'; +export { DEFAULT_RULESET, RulesetSchema, parseRuleset, energyForTurn } from './ruleset.ts'; +export { + ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor, + serialize, deserialize, replay, validateDeck, cardPower, lanePower, modifierActive, +} from './engine.ts'; +export { KEYWORDS, LANE_MODIFIERS, CATEGORY_ORDER, type KeywordDef, type LaneModifierDef, type EffectContext } from './keywords.ts'; +export { STARTER_POOL, starterCard, starterDeck, cardFromStats, type CardSource } from './cards.ts'; diff --git a/shared/game/keywords.ts b/shared/game/keywords.ts new file mode 100644 index 0000000..32c8837 --- /dev/null +++ b/shared/game/keywords.ts @@ -0,0 +1,85 @@ +/** + * Keyword and lane-modifier registry. Effects are code here, but which ones a + * mode uses and their numbers are data (Ruleset.keywords / laneModifiers.params). + * Owner: engine-b (claude/wikideck#3). engine-a owns the hook contract below. + * + * Hook contract: + * - onReveal: runs once when the card is revealed, after it is placed in its lane. + * May mutate ctx.state (e.g. add `bonus` to cards, draw cards) but must use ctx.rng + * for any randomness and must not throw. + * - ongoing: pure; returns a power delta for `target` while `source` is in play. + * Called for every (source, target) pair in play, including source === target. + * - Lane modifiers have the same shape; `source` is null and `lane` is the modifier's lane. + * canPlay lets a lane reject a card (checked when staging). + */ +import type { Rng } from './rng.ts'; +import type { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts'; + +export interface EffectContext { + state: MatchState; + rng: Rng; + /** Tunable numbers for this keyword/modifier from the ruleset. */ + params: Record; + lane: number; + log(text: string): void; +} + +export interface KeywordDef { + id: string; + name: string; + /** Short rules text with {param} placeholders, for card faces/tooltips. */ + text: string; + onReveal?(ctx: EffectContext, self: CardInPlay): void; + ongoing?(ctx: EffectContext, self: CardInPlay, target: CardInPlay): number; +} + +export interface LaneModifierDef { + id: string; + name: string; + text: string; + /** Runs when any card is revealed in this lane (after its own onReveal). */ + onReveal?(ctx: EffectContext, card: CardInPlay): void; + ongoing?(ctx: EffectContext, target: CardInPlay): number; + canPlay?(ctx: EffectContext, card: GameCard, player: PlayerId): boolean; +} + +/** Cards on the same side of the same lane, excluding `self`. */ +export function allies(state: MatchState, self: CardInPlay): CardInPlay[] { + return state.lanes[self.lane].cards[self.owner].filter(card => card !== self); +} + +export const KEYWORDS: Record = { + // Examples so the hook contract is exercised; engine-b replaces/extends per DESIGN.md. + rally: { + id: 'rally', name: 'Rally', text: 'On reveal: +{amount} power to your other cards here.', + onReveal(ctx, self) { + const amount = ctx.params.amount ?? 1; + for (const ally of allies(ctx.state, self)) ally.bonus += amount; + ctx.log(`Rally +${amount}`); + }, + }, + anchor: { + id: 'anchor', name: 'Anchor', text: 'Ongoing: +{amount} power if this is your only card here.', + ongoing(ctx, self, target) { + return target === self && allies(ctx.state, self).length === 0 ? ctx.params.amount ?? 2 : 0; + }, + }, +}; + +export const LANE_MODIFIERS: Record = { + plain: { id: 'plain', name: 'Plain', text: 'No effect.' }, + portal: { + id: 'portal', name: 'Portal', text: 'Cards of category {category} get +{amount} power here.', + // params.categoryIndex picks from CATEGORY_ORDER so params stay numeric. + ongoing(ctx, target) { + const category = CATEGORY_ORDER[ctx.params.categoryIndex ?? 0]; + return target.card.category === category ? ctx.params.amount ?? 2 : 0; + }, + }, + narrow: { + id: 'narrow', name: 'Narrow', text: 'Only cards costing {maxCost} or less can be played here.', + canPlay(ctx, card) { return card.cost <= (ctx.params.maxCost ?? 3); }, + }, +}; + +export const CATEGORY_ORDER = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const; diff --git a/shared/game/rng.ts b/shared/game/rng.ts new file mode 100644 index 0000000..8a11ea8 --- /dev/null +++ b/shared/game/rng.ts @@ -0,0 +1,73 @@ +/** + * Seeded, serialisable PRNG for the game engine (off-chain only). + * sfc32 seeded by cyrb128 of a string. The state is four uint32 numbers so it + * round-trips through JSON and a match can be resumed or replayed exactly. + */ +export type RngState = [number, number, number, number]; + +function cyrb128(text: string): RngState { + let h1 = 1779033703, h2 = 3144134277, h3 = 1013904242, h4 = 2773480762; + for (let i = 0; i < text.length; i++) { + const k = text.charCodeAt(i); + h1 = h2 ^ Math.imul(h1 ^ k, 597399067); + h2 = h3 ^ Math.imul(h2 ^ k, 2869860233); + h3 = h4 ^ Math.imul(h3 ^ k, 951274213); + h4 = h1 ^ Math.imul(h4 ^ k, 2716044179); + } + h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067); + h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233); + h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213); + h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179); + h1 ^= h2 ^ h3 ^ h4; h2 ^= h1; h3 ^= h1; h4 ^= h1; + return [h1 >>> 0, h2 >>> 0, h3 >>> 0, h4 >>> 0]; +} + +export function seedRng(seed: string): RngState { + const state = cyrb128(seed); + // Warm up so similar seeds diverge. + const rng = new Rng(state); + for (let i = 0; i < 12; i++) rng.nextUint32(); + return rng.state; +} + +/** Mutable wrapper over an RngState. The engine keeps `state` inside MatchState. */ +export class Rng { + state: RngState; + constructor(state: RngState) { this.state = [state[0] >>> 0, state[1] >>> 0, state[2] >>> 0, state[3] >>> 0]; } + static fromSeed(seed: string): Rng { return new Rng(seedRng(seed)); } + + nextUint32(): number { + let [a, b, c, d] = this.state; + const t = (((a + b) | 0) + d) | 0; + d = (d + 1) | 0; + a = b ^ (b >>> 9); + b = (c + (c << 3)) | 0; + c = (c << 21) | (c >>> 11); + c = (c + t) | 0; + this.state = [a >>> 0, b >>> 0, c >>> 0, d >>> 0]; + return t >>> 0; + } + /** Float in [0, 1). */ + next(): number { return this.nextUint32() / 4294967296; } + /** Integer in [0, n). Unbiased via rejection sampling. */ + int(n: number): number { + if (!Number.isInteger(n) || n <= 0 || n > 4294967296) throw new RangeError('Rng.int needs a positive integer bound'); + const limit = 4294967296 - (4294967296 % n); + let x: number; + do x = this.nextUint32(); while (x >= limit); + return x % n; + } + pick(items: readonly T[]): T { + if (!items.length) throw new RangeError('Rng.pick on empty list'); + return items[this.int(items.length)]; + } + /** Fisher–Yates; returns a new array. */ + shuffle(items: readonly T[]): T[] { + const out = items.slice(); + for (let i = out.length - 1; i > 0; i--) { + const j = this.int(i + 1); + [out[i], out[j]] = [out[j], out[i]]; + } + return out; + } +} diff --git a/shared/game/ruleset.ts b/shared/game/ruleset.ts new file mode 100644 index 0000000..d7305ca --- /dev/null +++ b/shared/game/ruleset.ts @@ -0,0 +1,70 @@ +/** + * Ruleset: every rule number as data, so peer-hosted modes can vary them + * without running code. parseRuleset() is the only way untrusted JSON should + * become a Ruleset; it enforces bounds that keep matches short and terminating. + */ +import { z } from 'zod'; +import { KEYWORDS, LANE_MODIFIERS } from './keywords.ts'; +import type { Ruleset } from './types.ts'; + +const int = (min: number, max: number) => z.number().int().min(min).max(max); +const params = z.record(z.string().max(32), z.number().finite().min(-100).max(100)) + .refine(value => Object.keys(value).length <= 8, 'Too many params'); + +export const RulesetSchema = z.object({ + id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,47}$/), + name: z.string().min(1).max(64), + version: int(1, 1_000_000), + lanes: int(1, 5), + laneCapacity: int(1, 8), + maxTurns: int(1, 12), + deck: z.object({ min: int(1, 40), max: int(1, 40), maxCopiesPerPage: int(1, 40) }).strict(), + hand: z.object({ start: int(0, 10), max: int(1, 12), drawPerTurn: int(0, 3) }).strict(), + energy: z.object({ start: int(0, 20), perTurn: int(0, 5), max: int(1, 20) }).strict(), + keywords: z.record(z.string(), params).refine(value => Object.keys(value).length <= 32, 'Too many keywords'), + laneModifiers: z.object({ + pool: z.array(z.string()).max(32), + revealTurns: z.array(int(1, 12)).max(5), + params: z.record(z.string(), params), + }).strict(), + tieBreak: z.enum(['totalPower', 'draw']), +}).strict().superRefine((rules, ctx) => { + const issue = (message: string) => ctx.addIssue({ code: 'custom', message }); + if (rules.deck.min > rules.deck.max) issue('deck.min > deck.max'); + if (rules.hand.start > rules.hand.max) issue('hand.start > hand.max'); + if (rules.energy.start > rules.energy.max) issue('energy.start > energy.max'); + if (rules.laneModifiers.revealTurns.length !== rules.lanes) issue('laneModifiers.revealTurns must have one entry per lane'); + if (rules.laneModifiers.pool.length && rules.laneModifiers.pool.length < rules.lanes) issue('laneModifiers.pool needs at least one modifier per lane (or be empty)'); + for (const id of Object.keys(rules.keywords)) if (!Object.hasOwn(KEYWORDS, id)) issue(`Unknown keyword: ${id}`); + for (const id of [...rules.laneModifiers.pool, ...Object.keys(rules.laneModifiers.params)]) + if (!Object.hasOwn(LANE_MODIFIERS, id)) issue(`Unknown lane modifier: ${id}`); +}); + +/** Validate untrusted ruleset JSON. Throws a ZodError with readable issues. */ +export function parseRuleset(input: unknown): Ruleset { + return RulesetSchema.parse(input) as Ruleset; +} + +/** Placeholder base rules (Snap-style lanes) until DESIGN.md v1 lands. */ +export const DEFAULT_RULESET: Ruleset = { + id: 'wikideck-standard', + name: 'WikiDeck Standard', + version: 1, + lanes: 3, + laneCapacity: 4, + maxTurns: 6, + deck: { min: 12, max: 12, maxCopiesPerPage: 2 }, + hand: { start: 3, max: 7, drawPerTurn: 1 }, + energy: { start: 1, perTurn: 1, max: 6 }, + keywords: { rally: { amount: 1 }, anchor: { amount: 2 } }, + laneModifiers: { + pool: ['plain', 'portal', 'narrow'], + revealTurns: [1, 2, 3], + params: { portal: { categoryIndex: 0, amount: 2 }, narrow: { maxCost: 3 } }, + }, + tieBreak: 'totalPower', +}; + +export function energyForTurn(rules: Ruleset, turn: number): number { + return Math.min(rules.energy.max, rules.energy.start + (turn - 1) * rules.energy.perTurn); +} diff --git a/shared/game/types.ts b/shared/game/types.ts new file mode 100644 index 0000000..435d3dd --- /dev/null +++ b/shared/game/types.ts @@ -0,0 +1,158 @@ +/** + * WikiDeck game engine types (off-chain). Everything here is plain JSON data: + * MatchState round-trips through JSON.stringify/parse with no loss. + * Contract: docs/game/ENGINE_API.md. Announce changes on claude/wikideck#3. + */ +import type { RngState } from './rng.ts'; + +export type PlayerId = 0 | 1; +export const PLAYERS: readonly PlayerId[] = [0, 1]; + +/** Category buckets from server/wiki.ts. */ +export type Category = 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture'; + +/** A card as the engine sees it. Built from enrichment data by cards.ts, or a starter/loaner card. */ +export interface GameCard { + /** Unique within one deck (e.g. the NFT card hash, or `starter::`). */ + id: string; + name: string; + pageId: number | null; + category: Category; + cost: number; + power: number; + /** Keyword id from the ruleset's keyword list, or null. */ + keyword: string | null; + /** 'owned' = an NFT the player holds (never moved or burned by a match). */ + source: 'owned' | 'starter' | 'loaner'; + /** Optional display/tie-break data; never used for rules unless a keyword says so. */ + meta?: Record; +} + +/** All rule numbers. Peer-hosted modes override these as data (see ruleset.ts). */ +export interface Ruleset { + id: string; + name: string; + version: number; + lanes: number; + /** Cards that may sit on one side of one lane. */ + laneCapacity: number; + maxTurns: number; + deck: { min: number; max: number; maxCopiesPerPage: number }; + hand: { start: number; max: number; drawPerTurn: number }; + /** Energy available on turn t (1-based) = min(max, start + (t - 1) * perTurn). Unspent energy is lost. */ + energy: { start: number; perTurn: number; max: number }; + /** Keyword ids that cards may carry in this mode, with tunable numbers per keyword. */ + keywords: Record>; + laneModifiers: { + /** Pool of lane modifier ids; one is drawn (without replacement) per lane at match start. */ + pool: string[]; + /** Turn on which lane i's modifier becomes visible and active (length = lanes). */ + revealTurns: number[]; + params: Record>; + }; + /** How the match ends when lanes tie on count. */ + tieBreak: 'totalPower' | 'draw'; +} + +export interface CardInPlay { + card: GameCard; + owner: PlayerId; + lane: number; + /** Turn the card was revealed. */ + turn: number; + /** Permanent power changes from effects (onReveal buffs etc.). */ + bonus: number; +} + +export interface StagedPlay { cardId: string; lane: number } + +export interface PlayerState { + deck: GameCard[]; + hand: GameCard[]; + /** Energy left this turn (after staging). */ + energy: number; + /** Plays chosen this turn, hidden from the opponent until reveal. Order matters. */ + staged: StagedPlay[]; + ended: boolean; + discard: GameCard[]; +} + +export interface LaneState { + modifier: string | null; + cards: [CardInPlay[], CardInPlay[]]; +} + +export type MatchPhase = 'planning' | 'over'; + +export type LogEvent = + | { t: 'turnStart'; turn: number; energy: [number, number] } + | { t: 'draw'; player: PlayerId; cardId: string } + | { t: 'reveal'; player: PlayerId; cardId: string; lane: number } + | { t: 'laneRevealed'; lane: number; modifier: string | null } + | { t: 'effect'; source: string; player: PlayerId; text: string } + | { t: 'concede'; player: PlayerId } + | { t: 'matchOver'; result: MatchResult }; + +export interface MatchState { + schema: 'wikideck-match/1'; + ruleset: Ruleset; + seed: string; + rng: RngState; + turn: number; + phase: MatchPhase; + /** Player who reveals first this turn. */ + firstToReveal: PlayerId; + players: [PlayerState, PlayerState]; + lanes: LaneState[]; + log: LogEvent[]; + /** Every action applied so far: (ruleset, decks, seed, actions) replays the match exactly. */ + actions: Action[]; + result: MatchResult | null; +} + +export type Action = + | { type: 'play'; player: PlayerId; cardId: string; lane: number } + /** Take back a staged (unrevealed) play this turn; refunds its energy. */ + | { type: 'unstage'; player: PlayerId; cardId: string } + | { type: 'endTurn'; player: PlayerId } + | { type: 'concede'; player: PlayerId }; + +export interface MatchResult { + /** null = draw. */ + winner: PlayerId | null; + reason: 'lanes' | 'totalPower' | 'draw' | 'concede'; + lanesWon: [number, number]; + /** lanePower[lane][player] at the end. */ + lanePower: [number, number][]; + totalPower: [number, number]; + turns: number; +} + +/** What one player is allowed to see. Use this for UI and AI, never raw MatchState. */ +export interface PlayerView { + you: PlayerId; + ruleset: Ruleset; + turn: number; + phase: MatchPhase; + firstToReveal: PlayerId; + energy: number; + hand: GameCard[]; + staged: StagedPlay[]; + ended: boolean; + deckCount: number; + opponent: { handCount: number; deckCount: number; stagedCount: number; ended: boolean }; + lanes: { + /** null when not yet revealed. */ + modifier: string | null; + modifierRevealed: boolean; + /** cards[0] = yours, cards[1] = opponent's (revealed only). */ + cards: [CardInPlay[], CardInPlay[]]; + /** power[0] = yours, power[1] = opponent's. */ + power: [number, number]; + }[]; + result: MatchResult | null; +} + +export class IllegalActionError extends Error { + constructor(message: string) { super(message); this.name = 'IllegalActionError'; } +} diff --git a/tests/game-engine.test.ts b/tests/game-engine.test.ts new file mode 100644 index 0000000..c4255b2 --- /dev/null +++ b/tests/game-engine.test.ts @@ -0,0 +1,95 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + DEFAULT_RULESET, IllegalActionError, Rng, applyAction, createMatch, deserialize, isOver, legalActions, + parseRuleset, replay, result, serialize, starterDeck, viewFor, type Action, type GameCard, type MatchState, type PlayerId, +} from '../shared/game/index.ts'; + +const decks = (seed = 'd'): [GameCard[], GameCard[]] => [starterDeck(`${seed}-a`), starterDeck(`${seed}-b`)]; + +function randomPlay(seed: string, ruleset = DEFAULT_RULESET): MatchState { + let state = createMatch(ruleset, decks(seed), seed); + const chooser = Rng.fromSeed(`bot:${seed}`); + for (let steps = 0; !isOver(state); steps++) { + assert.ok(steps < 1000, 'match must terminate'); + const player = chooser.int(2) as PlayerId; + const actions = legalActions(state, player); + if (!actions.length) continue; + state = applyAction(state, chooser.pick(actions)); + } + return state; +} + +test('rng is deterministic and seed-sensitive', () => { + const a = Rng.fromSeed('x'), b = Rng.fromSeed('x'), c = Rng.fromSeed('y'); + const seq = (r: Rng) => Array.from({ length: 8 }, () => r.nextUint32()); + assert.deepEqual(seq(a), seq(b)); + assert.notDeepEqual(seq(Rng.fromSeed('x')), seq(c)); + const r = Rng.fromSeed('bounds'); + for (let i = 0; i < 1000; i++) { const n = r.int(7); assert.ok(n >= 0 && n < 7); } +}); + +test('default ruleset validates; bad rulesets are rejected', () => { + assert.deepEqual(parseRuleset(DEFAULT_RULESET), DEFAULT_RULESET); + assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, maxTurns: 99 })); + assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, keywords: { nope: {} } })); + assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, extra: 1 })); +}); + +test('starter decks are legal, deterministic and non-NFT', () => { + const deck = starterDeck('s'); + assert.equal(deck.length, 12); + assert.deepEqual(deck, starterDeck('s')); + assert.ok(deck.every(card => card.source === 'starter')); + assert.deepEqual(deck.map(c => c.cost).sort().join(''), '112233445566'); +}); + +test('match setup: hands, energy, turn 1', () => { + const state = createMatch(DEFAULT_RULESET, decks(), 'setup'); + assert.equal(state.turn, 1); + for (const p of state.players) { assert.equal(p.hand.length, 4); assert.equal(p.deck.length, 8); assert.equal(p.energy, 1); } + assert.throws(() => createMatch(DEFAULT_RULESET, [decks()[0].slice(0, 5), decks()[1]], 's'), IllegalActionError); +}); + +test('staging is hidden from the opponent until reveal', () => { + let state = createMatch(DEFAULT_RULESET, decks(), 'hidden'); + const play = legalActions(state, 0).find(a => a.type === 'play') as Extract; + assert.ok(play, 'turn 1 should have a 1-cost play'); + state = applyAction(state, play); + assert.equal(viewFor(state, 1).opponent.stagedCount, 1); + assert.equal(viewFor(state, 1).lanes[play.lane].cards[1].length, 0); + assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false); + state = applyAction(state, { type: 'endTurn', player: 0 }); + state = applyAction(state, { type: 'endTurn', player: 1 }); + assert.equal(state.turn, 2); + assert.equal(viewFor(state, 1).lanes[play.lane].cards[1][0].card.id, play.cardId); + assert.throws(() => applyAction(state, { type: 'play', player: 0, cardId: play.cardId, lane: 0 }), IllegalActionError); +}); + +test('unstage refunds energy', () => { + let state = createMatch(DEFAULT_RULESET, decks(), 'unstage'); + const play = legalActions(state, 0).find(a => a.type === 'play') as Extract; + state = applyAction(state, play); + state = applyAction(state, { type: 'unstage', player: 0, cardId: play.cardId }); + assert.equal(state.players[0].energy, 1); + assert.equal(state.players[0].staged.length, 0); +}); + +test('concede ends the match for the other player', () => { + const state = applyAction(createMatch(DEFAULT_RULESET, decks(), 'c'), { type: 'concede', player: 1 }); + assert.equal(isOver(state), true); + assert.equal(result(state)?.winner, 0); + assert.deepEqual(legalActions(state, 0), []); +}); + +test('random legal play terminates within maxTurns, and replays and serialises exactly', () => { + for (let i = 0; i < 40; i++) { + const seed = `prop-${i}`; + const end = randomPlay(seed); + const r = result(end)!; + assert.ok(r.turns <= DEFAULT_RULESET.maxTurns); + assert.deepEqual(randomPlay(seed), end); + assert.deepEqual(replay(DEFAULT_RULESET, decks(seed), seed, end.actions), end); + assert.deepEqual(deserialize(serialize(end)), end); + } +});