Engine core: align with DESIGN.md draft (Edit War)

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>
This commit is contained in:
2026-11-16 22:55:51 -05:00
co-authored by Claude Opus 5.5
parent 7c86ed35f5
commit f3b6097640
10 changed files with 707 additions and 550 deletions
-92
View File
@@ -1,92 +0,0 @@
/**
* 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<number, StarterSpec[]>();
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',
};
}
+235 -169
View File
@@ -1,72 +1,103 @@
/** /**
* WikiDeck game engine core: pure, deterministic, off-chain. * WikiDeck game engine core ("Edit War", docs/game/DESIGN.md): pure,
* Every exported function treats its inputs as immutable and returns new data. * deterministic, off-chain. Exported functions never mutate their inputs.
* All randomness comes from the match seed via state.rng. * All randomness comes from the match seed via state.rng (mulberry32, §4).
* Contract: docs/game/ENGINE_API.md. * Contract: docs/game/ENGINE_API.md.
*/ */
import { KEYWORDS, LANE_MODIFIERS, type EffectContext } from './keywords.ts'; import { KEYWORDS, PORTALS, type EffectContext } from './keywords.ts';
import { Rng, seedRng } from './rng.ts'; import { Rng, normalizeSeed } from './rng.ts';
import { energyForTurn, parseRuleset } from './ruleset.ts'; import { parseRuleset } from './ruleset.ts';
import { import {
IllegalActionError, PLAYERS, IllegalActionError, PLAYERS, STATS,
type Action, type CardInPlay, type GameCard, type MatchResult, type MatchState, type Action, type CardInPlay, type GameCard, type MatchResult, type MatchState,
type PlayerId, type PlayerState, type PlayerView, type Ruleset, type PlayerId, type PlayerState, type PlayerView, type Ruleset, type TopicDef,
} from './types.ts'; } from './types.ts';
export const ENGINE_VERSION = 1; export const ENGINE_VERSION = 1;
const other = (player: PlayerId): PlayerId => (player === 0 ? 1 : 0); export const other = (player: PlayerId): PlayerId => (player === 0 ? 1 : 0);
const clone = <T>(value: T): T => structuredClone(value); 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 ---------- // ---------- validation ----------
/** Problems with a deck under `rules` (empty = legal). DESIGN §2. */
export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[] { export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[] {
const problems: string[] = []; const problems: string[] = [];
if (deck.length < rules.deck.min || deck.length > rules.deck.max) if (!Array.isArray(deck)) return ['Deck must be an array'];
problems.push(`Deck must have ${rules.deck.min === rules.deck.max ? rules.deck.min : `${rules.deck.min}–${rules.deck.max}`} cards (has ${deck.length})`); if (deck.length !== rules.deckSize) problems.push(`Deck must have exactly ${rules.deckSize} cards (has ${deck.length})`);
const ids = new Set<string>(); const ids = new Set<string>();
const copies = new Map<number, number>(); const copies = new Map<number, number>();
let loaners = 0;
for (const card of deck) { 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 (typeof card?.cardId !== 'string' || !card.cardId || card.cardId.length > 128) { problems.push('cardId must be a non-empty string'); continue; }
if (ids.has(card.id)) problems.push(`Duplicate card id ${card.id}`); const label = card.cardId;
ids.add(card.id); if (ids.has(card.cardId)) problems.push(`Duplicate cardId ${label}`);
if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 20) problems.push(`Card ${card.id}: bad cost`); ids.add(card.cardId);
if (!Number.isInteger(card.power) || card.power < -100 || card.power > 100) problems.push(`Card ${card.id}: bad power`); if (!Number.isInteger(card.pageId)) problems.push(`${label}: bad pageId`);
if (card.pageId !== null) { if (typeof card.title !== 'string' || card.title.length > 256) problems.push(`${label}: bad title`);
const n = (copies.get(card.pageId) ?? 0) + 1; if (!FACTION_SET.has(card.faction)) problems.push(`${label}: bad faction`);
copies.set(card.pageId, n); if (!RARITIES.has(card.rarity)) problems.push(`${label}: bad rarity`);
if (n === rules.deck.maxCopiesPerPage + 1) problems.push(`More than ${rules.deck.maxCopiesPerPage} copies of page ${card.pageId}`); 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; return problems;
} }
// ---------- match setup ---------- // ---------- match setup (§4) ----------
/** /**
* Start a match. `decks[0]` belongs to player 0. Throws IllegalActionError for an * Draw the match's Topics (§4.2.3). distinctStats: for each stat in STATS order
* invalid deck and ZodError for an invalid ruleset. * (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.
*/ */
export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: string): MatchState { function drawTopics(rules: Ruleset, rng: Rng): TopicDef[] {
const rules = parseRuleset(clone(ruleset)); if (!rules.distinctStats) return rng.shuffle(rules.topicPool).slice(0, rules.topicCount);
if (typeof seed !== 'string' || !seed) throw new IllegalActionError('Seed must be a non-empty string'); const picked: TopicDef[] = [];
for (const player of PLAYERS) { for (const stat of STATS) {
const problems = validateDeck(rules, decks[player] ?? []); const group = rules.topicPool.filter(topic => topic.stat === stat);
if (problems.length) throw new IllegalActionError(`Player ${player} deck: ${problems.join('; ')}`); if (group.length) picked.push(group[rng.int(group.length)]);
} }
const rng = new Rng(seedRng(seed)); return rng.shuffle(picked).slice(0, rules.topicCount);
const modifiers = rules.laneModifiers.pool.length ? rng.shuffle(rules.laneModifiers.pool).slice(0, rules.lanes) : []; }
/**
* 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 => ({ const newPlayer = (player: PlayerId): PlayerState => ({
deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, staged: [], ended: false, discard: [], deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, queue: [], committed: false, afk: 0,
}); });
const players: [PlayerState, PlayerState] = [newPlayer(0), newPlayer(1)]; 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 = { const state: MatchState = {
schema: 'wikideck-match/1', ruleset: rules, seed, rng: rng.state, turn: 0, phase: 'planning', schema: 'wikideck-match/1', engineVersion: ENGINE_VERSION, ruleset: rules, seed: seedValue, rng: rng.state,
firstToReveal: rng.int(2) as PlayerId, players, turn: 0, phase: 'planning', initiative, players: [p0, p1],
lanes: Array.from({ length: rules.lanes }, (_, lane) => ({ modifier: modifiers[lane] ?? null, cards: [[], []] as [CardInPlay[], CardInPlay[]] })), lanes: topics.map(topic => ({ topic: clone(topic), revealed: false, cards: [[], []] as [CardInPlay[], CardInPlay[]] })),
log: [], actions: [], result: null, log: [], actions: [], result: null,
}; };
for (const player of PLAYERS) for (let i = 0; i < rules.hand.start; i++) draw(state, player); for (const player of PLAYERS) for (let i = 0; i < rules.openingHand; i++) draw(state, player);
startTurn(state, rng); startTurn(state, rng);
state.rng = rng.state; state.rng = rng.state;
return state; return state;
@@ -74,136 +105,139 @@ export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard
function draw(state: MatchState, player: PlayerId): void { function draw(state: MatchState, player: PlayerId): void {
const p = state.players[player]; const p = state.players[player];
if (!p.deck.length || p.hand.length >= state.ruleset.hand.max) return; if (!p.deck.length || p.hand.length >= state.ruleset.handLimit) return;
const card = p.deck.shift()!; const card = p.deck.shift()!;
p.hand.push(card); p.hand.push(card);
state.log.push({ t: 'draw', player, cardId: card.id }); state.log.push({ t: 'draw', player, cardId: card.cardId });
}
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 { 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 }) }; return { state, rng, params: params ?? {}, lane, log: text => state.log.push({ t: 'effect', source, player, text }) };
} }
function keywordOf(state: MatchState, card: GameCard) { function portalOf(state: MatchState, lane: number) {
return card.keyword && Object.hasOwn(state.ruleset.keywords, card.keyword) ? KEYWORDS[card.keyword] : undefined; const l = state.lanes[lane];
return l?.revealed && l.topic.portal ? PORTALS[l.topic.portal] : undefined;
} }
/** Current power of one card in play, including ongoing keyword and lane effects. */ /** §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 { export function cardPower(state: MatchState, target: CardInPlay): number {
const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness const rules = state.ruleset;
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]; const lane = state.lanes[target.lane];
if (modifierActive(state, target.lane)) { const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness
const modifier = LANE_MODIFIERS[lane.modifier!]; let power = target.card.power + target.bonus + target.card.trend;
if (modifier?.ongoing) power += modifier.ongoing(context(state, scratch, state.ruleset.laneModifiers.params[modifier.id], target.lane, modifier.id, target.owner), target); 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);
} }
return power; 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] { 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]; 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'> { /** Number of Topics each seat leads (strictly more power). */
const powers = state.lanes.map((_, lane) => lanePower(state, lane)); export function topicsLed(state: MatchState): [number, number] {
const lanesWon: [number, number] = [0, 0]; const led: [number, number] = [0, 0];
const totalPower: [number, number] = [0, 0]; state.lanes.forEach((_, lane) => {
for (const [a, b] of powers) { const [a, b] = lanePower(state, lane);
if (a > b) lanesWon[0]++; else if (b > a) lanesWon[1]++; if (a > b) led[0]++; else if (b > a) led[1]++;
totalPower[0] += a; totalPower[1] += b; });
} return led;
return { lanesWon, lanePower: powers, totalPower };
} }
// ---------- actions ---------- // ---------- actions (§5.3) ----------
function stagedInLane(p: PlayerState, lane: number): number { const queuedCost = (p: PlayerState) => p.queue.reduce((sum, play) => sum + (p.hand.find(c => c.cardId === play.cardId)?.cost ?? 0), 0);
return p.staged.filter(play => play.lane === lane).length; 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 { function playProblem(state: MatchState, action: Extract<Action, { type: 'play' }>): string | null {
const p = state.players[action.player]; const p = state.players[action.player];
if (p.ended) return 'You already ended your turn'; if (p.committed) return 'Already committed this turn';
const card = p.hand.find(c => c.id === action.cardId); const card = p.hand.find(c => c.cardId === action.cardId);
if (!card) return 'Card is not in your hand'; if (!card) return 'Card is not in your hand';
if (p.staged.some(play => play.cardId === action.cardId)) return 'Card is already staged'; 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 lane'; if (!Number.isInteger(action.lane) || action.lane < 0 || action.lane >= state.lanes.length) return 'No such Topic';
if (card.cost > p.energy) return 'Not enough energy'; if (card.cost > p.energy - queuedCost(p)) 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 (state.lanes[action.lane].cards[action.player].length + queuedInLane(p, action.lane) >= state.ruleset.laneCapacity) return 'Topic is full';
if (modifierActive(state, action.lane)) { return laneRejects(state, action.lane, card, action.player);
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. */ /** Why `action` is illegal in `state`, or null if it is legal. */
export function actionProblem(state: MatchState, action: Action): string | null { export function actionProblem(state: MatchState, action: Action): string | null {
if (state.phase === 'over') return 'Match is over'; if (state.phase === 'over') return 'Match is over';
if (!action || (action.player !== 0 && action.player !== 1)) return 'Unknown player'; if (!action || (action.player !== 0 && action.player !== 1)) return 'Unknown player';
const p = state.players[action.player];
switch (action.type) { switch (action.type) {
case 'play': return playProblem(state, action); case 'play': return playProblem(state, action);
case 'unstage': { case 'undo':
const p = state.players[action.player]; if (p.committed) return 'Already committed this turn';
if (p.ended) return 'You already ended your turn'; return p.queue.some(play => play.cardId === action.cardId) ? null : 'Card is not queued';
return p.staged.some(play => play.cardId === action.cardId) ? null : 'Card is not staged'; case 'commit':
} case 'timeout':
case 'endTurn': return state.players[action.player].ended ? 'You already ended your turn' : null; return p.committed ? 'Already committed this turn' : null;
case 'concede': return null; case 'concede': return null;
default: return 'Unknown action'; default: return 'Unknown action';
} }
} }
/** /**
* Every legal action for `player` except `concede` (always legal while the match * Legal actions for `player`: every `play`, every `undo`, and `commit`.
* is running). `endTurn` is always included while the player hasn't ended. * `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[] { export function legalActions(state: MatchState, player: PlayerId): Action[] {
if (state.phase === 'over') return []; if (state.phase === 'over') return [];
const p = state.players[player]; const p = state.players[player];
if (p.ended) return []; if (p.committed) return [];
const actions: Action[] = []; const actions: Action[] = [];
for (const card of p.hand) { for (const card of p.hand) {
if (p.staged.some(play => play.cardId === card.id)) continue; if (p.queue.some(play => play.cardId === card.cardId)) continue;
for (let lane = 0; lane < state.lanes.length; lane++) { for (let lane = 0; lane < state.lanes.length; lane++) {
const action: Action = { type: 'play', player, cardId: card.id, lane }; const action: Action = { type: 'play', player, cardId: card.cardId, lane };
if (!playProblem(state, action)) actions.push(action); if (!playProblem(state, action)) actions.push(action);
} }
} }
for (const play of p.staged) actions.push({ type: 'unstage', player, cardId: play.cardId }); for (const play of p.queue) actions.push({ type: 'undo', player, cardId: play.cardId });
actions.push({ type: 'endTurn', player }); actions.push({ type: 'commit', player });
return actions; return actions;
} }
@@ -216,67 +250,77 @@ export function applyAction(state: MatchState, action: Action): MatchState {
const p = next.players[action.player]; const p = next.players[action.player];
const rng = new Rng(next.rng); const rng = new Rng(next.rng);
switch (action.type) { switch (action.type) {
case 'play': { case 'play': p.queue.push({ cardId: action.cardId, lane: action.lane }); break;
p.staged.push({ cardId: action.cardId, lane: action.lane }); case 'undo': p.queue.splice(p.queue.findIndex(play => play.cardId === action.cardId), 1); break;
p.energy -= p.hand.find(c => c.id === action.cardId)!.cost; 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; break;
} case 'concede':
case 'unstage': { next.log.push({ t: 'concede', player: action.player, afk: false });
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'); finish(next, other(action.player), 'concede');
break; break;
}
} }
if (next.phase !== 'over' && next.players.every(player => player.committed)) resolveTurn(next, rng);
next.rng = rng.state; next.rng = rng.state;
return next; return next;
} }
/** §5.4 Reveal and §5.5 End. */
function resolveTurn(state: MatchState, rng: Rng): void { function resolveTurn(state: MatchState, rng: Rng): void {
for (const player of [state.firstToReveal, other(state.firstToReveal)]) { const rules = state.ruleset;
const order: PlayerId[] = [state.initiative, other(state.initiative)];
for (const player of order) {
const p = state.players[player]; const p = state.players[player];
for (const play of p.staged) { for (const play of p.queue) {
const index = p.hand.findIndex(c => c.id === play.cardId); const index = p.hand.findIndex(c => c.cardId === play.cardId);
const [card] = p.hand.splice(index, 1); 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 }; const inPlay: CardInPlay = { card, owner: player, lane: play.lane, turn: state.turn, bonus: 0 };
state.lanes[play.lane].cards[player].push(inPlay); state.lanes[play.lane].cards[player].push(inPlay);
state.log.push({ t: 'reveal', player, cardId: card.id, lane: play.lane }); state.log.push({ t: 'reveal', player, cardId: card.cardId, lane: play.lane });
const keyword = keywordOf(state, card); const keyword = card.keyword ? KEYWORDS[card.keyword] : undefined;
keyword?.onReveal?.(context(state, rng, state.ruleset.keywords[keyword.id], play.lane, keyword.id, player), inPlay); keyword?.onReveal?.(context(state, rng, rules.keywordParams[keyword.id], play.lane, keyword.id, player), inPlay);
if (modifierActive(state, play.lane)) { const portal = portalOf(state, play.lane);
const modifier = LANE_MODIFIERS[state.lanes[play.lane].modifier!]; portal?.onReveal?.(context(state, rng, rules.portalParams[portal.id], play.lane, portal.id, player), inPlay);
modifier?.onReveal?.(context(state, rng, state.ruleset.laneModifiers.params[modifier.id], play.lane, modifier.id, player), inPlay);
}
} }
p.staged = []; p.queue = [];
} }
if (state.turn >= state.ruleset.maxTurns) finish(state, null, 'lanes'); for (const player of order) for (const lane of state.lanes) for (const card of lane.cards[player].slice()) {
else startTurn(state, rng); 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);
} }
function finish(state: MatchState, concedeWinner: PlayerId | null, reason: 'lanes' | 'concede'): void { /** §7. */
const s = score(state); function finish(state: MatchState, forcedWinner: PlayerId | null, reason: 'topics' | 'concede' | 'afk'): void {
let winner: PlayerId | null = concedeWinner; 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; let why: MatchResult['reason'] = reason;
if (reason !== 'concede') { if (reason === 'topics') {
if (s.lanesWon[0] !== s.lanesWon[1]) winner = s.lanesWon[0] > s.lanesWon[1] ? 0 : 1; if (topicsLedNow[0] !== topicsLedNow[1]) winner = topicsLedNow[0] > topicsLedNow[1] ? 0 : 1;
else if (state.ruleset.tieBreak === 'totalPower' && s.totalPower[0] !== s.totalPower[1]) { else if (totalPower[0] !== totalPower[1]) { winner = totalPower[0] > totalPower[1] ? 0 : 1; why = 'totalPower'; }
winner = s.totalPower[0] > s.totalPower[1] ? 0 : 1; why = 'totalPower'; else why = 'draw';
} else why = 'draw';
} }
state.result = { winner, reason: why, ...s, turns: state.turn }; state.result = { winner, reason: why, topicsLed: topicsLedNow, lanePower: lanePowers, totalPower, turns: state.turn };
state.phase = 'over'; state.phase = 'over';
state.log.push({ t: 'matchOver', result: state.result }); state.log.push({ t: 'matchOver', result: clone(state.result) });
} }
// ---------- queries ---------- // ---------- queries ----------
@@ -286,28 +330,31 @@ export function isOver(state: MatchState): boolean { return state.phase === 'ove
/** The final result, or null while the match is running. */ /** The final result, or null while the match is running. */
export function result(state: MatchState): MatchResult | null { return state.result; } export function result(state: MatchState): MatchResult | null { return state.result; }
/** Hidden-information view for one player. UI and AI should only ever read this. */ /** Hidden-information view for one seat. Send only this to clients and AIs. */
export function viewFor(state: MatchState, you: PlayerId): PlayerView { export function viewFor(state: MatchState, you: PlayerId): PlayerView {
const them = other(you); const them = other(you);
const me = state.players[you], opp = state.players[them]; const me = state.players[you], opp = state.players[them];
return clone({ return clone({
you, ruleset: state.ruleset, turn: state.turn, phase: state.phase, firstToReveal: state.firstToReveal, you, ruleset: state.ruleset, turn: state.turn, phase: state.phase, initiative: state.initiative,
energy: me.energy, hand: me.hand, staged: me.staged, ended: me.ended, deckCount: me.deck.length, energy: me.energy, energyLeft: me.energy - queuedCost(me), hand: me.hand, queue: me.queue,
opponent: { handCount: opp.hand.length - opp.staged.length, deckCount: opp.deck.length, stagedCount: opp.staged.length, ended: opp.ended }, 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) => { lanes: state.lanes.map((lane, index) => {
const revealed = modifierActive(state, index);
const power = lanePower(state, index); const power = lanePower(state, index);
const mine = power[you], theirs = power[them];
return { return {
modifier: revealed ? lane.modifier : null, modifierRevealed: revealed, topic: lane.revealed ? lane.topic : null,
cards: [lane.cards[you], lane.cards[them]] as [CardInPlay[], CardInPlay[]], cards: [lane.cards[you], lane.cards[them]] as [CardInPlay[], CardInPlay[]],
power: [power[you], power[them]] as [number, number], 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, result: state.result,
}); });
} }
// ---------- serialisation / replay ---------- // ---------- serialisation, replay, test helpers ----------
export function serialize(state: MatchState): string { return JSON.stringify(state); } export function serialize(state: MatchState): string { return JSON.stringify(state); }
@@ -319,6 +366,25 @@ export function deserialize(json: string): MatchState {
} }
/** Rebuild a match from its inputs; a host can verify a reported result this way. */ /** 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 { export function replay(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: number | string, actions: readonly Action[]): MatchState {
return actions.reduce(applyAction, createMatch(ruleset, decks, seed)); 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;
} }
+6 -6
View File
@@ -1,10 +1,10 @@
/** Public entry point of the WikiDeck game engine. See docs/game/ENGINE_API.md. */ /** Public entry point of the WikiDeck game engine. Other teams import only from here. See docs/game/ENGINE_API.md. */
export * from './types.ts'; export * from './types.ts';
export { Rng, seedRng, type RngState } from './rng.ts'; export { Rng, seedFromString, normalizeSeed, type RngState } from './rng.ts';
export { DEFAULT_RULESET, RulesetSchema, parseRuleset, energyForTurn } from './ruleset.ts'; export { DEFAULT_RULESET, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
export { export {
ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor, ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor,
serialize, deserialize, replay, validateDeck, cardPower, lanePower, modifierActive, serialize, deserialize, replay, validateDeck, cardPower, lanePower, topicsLed, other, placeCard, revealTopic,
} from './engine.ts'; } from './engine.ts';
export { KEYWORDS, LANE_MODIFIERS, CATEGORY_ORDER, type KeywordDef, type LaneModifierDef, type EffectContext } from './keywords.ts'; export { KEYWORDS, PORTALS, allies, type KeywordDef, type PortalDef, type EffectContext } from './keywords.ts';
export { STARTER_POOL, starterCard, starterDeck, cardFromStats, type CardSource } from './cards.ts'; export { STARTER_POOL, loanerCard, previewPool, starterDeck } from './starter.ts';
+34 -32
View File
@@ -1,16 +1,20 @@
/** /**
* Keyword and lane-modifier registry. Effects are code here, but which ones a * Keyword and Portal registry (DESIGN §10, §10.3). Effects are code here; which
* mode uses and their numbers are data (Ruleset.keywords / laneModifiers.params). * ones a card/topic uses and their numbers are data (GameCard.keyword,
* Owner: engine-b (claude/wikideck#3). engine-a owns the hook contract below. * TopicDef.portal, Ruleset.keywordParams / portalParams).
* Owner of the effects: engine-b (claude/wikideck#3). engine-a owns the hook contract:
* *
* Hook contract: * - Hooks get an EffectContext over the engine's *working copy* of the state and may
* - onReveal: runs once when the card is revealed, after it is placed in its lane. * mutate it (e.g. `bonus` on cards). Mutating is safe: applyAction already cloned.
* May mutate ctx.state (e.g. add `bonus` to cards, draw cards) but must use ctx.rng * Any randomness must come from ctx.rng (the match RNG, in resolution order, §4.2.5).
* for any randomness and must not throw. * - onReveal: once, right after the card enters its lane (§5.4).
* - ongoing: pure; returns a power delta for `target` while `source` is in play. * - endOfTurn: every card in play, at §5.5, initiative player's cards first, lanes left→right,
* Called for every (source, target) pair in play, including source === target. * in play order.
* - Lane modifiers have the same shape; `source` is null and `lane` is the modifier's lane. * - ongoing: PURE. Returns a power delta for `target` while `self` is in play. Called for every
* canPlay lets a lane reject a card (checked when staging). * (self, target) pair in play, including self === target. ctx.rng is a throwaway copy.
* - Portals: same shape; ongoing/canPlay/onReveal only apply while the Topic is revealed.
* onTopicReveal runs when the Topic flips face-up (§5.1).
* - Hooks must not throw, must not move/remove cards (§10 v1 constraint).
*/ */
import type { Rng } from './rng.ts'; import type { Rng } from './rng.ts';
import type { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts'; import type { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts';
@@ -18,28 +22,33 @@ import type { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts';
export interface EffectContext { export interface EffectContext {
state: MatchState; state: MatchState;
rng: Rng; rng: Rng;
/** Tunable numbers for this keyword/modifier from the ruleset. */ /** Tunable numbers for this keyword/portal from Ruleset.keywordParams / portalParams. */
params: Record<string, number>; params: Record<string, number>;
/** Lane the effect lives in. */
lane: number; lane: number;
/** Add a line to the match log (attributed to this keyword/portal). */
log(text: string): void; log(text: string): void;
} }
export interface KeywordDef { export interface KeywordDef {
id: string; id: string;
name: string; name: string;
/** Short rules text with {param} placeholders, for card faces/tooltips. */ /** One short line of reminder text with {param} placeholders. */
text: string; text: string;
onReveal?(ctx: EffectContext, self: CardInPlay): void; onReveal?(ctx: EffectContext, self: CardInPlay): void;
endOfTurn?(ctx: EffectContext, self: CardInPlay): void;
ongoing?(ctx: EffectContext, self: CardInPlay, target: CardInPlay): number; ongoing?(ctx: EffectContext, self: CardInPlay, target: CardInPlay): number;
} }
export interface LaneModifierDef { export interface PortalDef {
id: string; id: string;
name: string; name: string;
text: string; text: string;
/** Runs when any card is revealed in this lane (after its own onReveal). */ onTopicReveal?(ctx: EffectContext): void;
/** Runs when any card is revealed in this Topic (after the card's own onReveal). */
onReveal?(ctx: EffectContext, card: CardInPlay): void; onReveal?(ctx: EffectContext, card: CardInPlay): void;
ongoing?(ctx: EffectContext, target: CardInPlay): number; ongoing?(ctx: EffectContext, target: CardInPlay): number;
/** Lets a Topic reject a card; checked when queuing and again at reveal. */
canPlay?(ctx: EffectContext, card: GameCard, player: PlayerId): boolean; canPlay?(ctx: EffectContext, card: GameCard, player: PlayerId): boolean;
} }
@@ -48,38 +57,31 @@ export function allies(state: MatchState, self: CardInPlay): CardInPlay[] {
return state.lanes[self.lane].cards[self.owner].filter(card => card !== self); return state.lanes[self.lane].cards[self.owner].filter(card => card !== self);
} }
/** PLACEHOLDERS so the hook contract is exercised; engine-b replaces these per DESIGN §10. */
export const KEYWORDS: Record<string, KeywordDef> = { export const KEYWORDS: Record<string, KeywordDef> = {
// Examples so the hook contract is exercised; engine-b replaces/extends per DESIGN.md.
rally: { rally: {
id: 'rally', name: 'Rally', text: 'On reveal: +{amount} power to your other cards here.', id: 'rally', name: 'Rally', text: 'On reveal: +{amount} to your other cards here.',
onReveal(ctx, self) { onReveal(ctx, self) {
const amount = ctx.params.amount ?? 1; const amount = ctx.params.amount ?? 1;
for (const ally of allies(ctx.state, self)) ally.bonus += amount; for (const ally of allies(ctx.state, self)) ally.bonus += amount;
ctx.log(`Rally +${amount}`); ctx.log(`${self.card.title}: Rally +${amount}`);
}, },
}, },
anchor: { anchor: {
id: 'anchor', name: 'Anchor', text: 'Ongoing: +{amount} power if this is your only card here.', id: 'anchor', name: 'Anchor', text: 'Ongoing: +{amount} if alone here.',
ongoing(ctx, self, target) { ongoing(ctx, self, target) {
return target === self && allies(ctx.state, self).length === 0 ? ctx.params.amount ?? 2 : 0; return target === self && allies(ctx.state, self).length === 0 ? ctx.params.amount ?? 2 : 0;
}, },
}, },
}; };
export const LANE_MODIFIERS: Record<string, LaneModifierDef> = { export const PORTALS: Record<string, PortalDef> = {
plain: { id: 'plain', name: 'Plain', text: 'No effect.' }, spotlight: {
portal: { id: 'spotlight', name: 'Spotlight', text: 'Cards here get +{amount}.',
id: 'portal', name: 'Portal', text: 'Cards of category {category} get +{amount} power here.', ongoing(ctx) { return ctx.params.amount ?? 1; },
// 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: { paywall: {
id: 'narrow', name: 'Narrow', text: 'Only cards costing {maxCost} or less can be played here.', id: 'paywall', name: 'Paywall', text: 'Only cards costing {maxCost} or less.',
canPlay(ctx, card) { return card.cost <= (ctx.params.maxCost ?? 3); }, canPlay(ctx, card) { return card.cost <= (ctx.params.maxCost ?? 3); },
}, },
}; };
export const CATEGORY_ORDER = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const;
+25 -42
View File
@@ -1,67 +1,50 @@
/** /**
* Seeded, serialisable PRNG for the game engine (off-chain only). * 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 * DESIGN.md §4: mulberry32(seed: uint32). The state is one uint32, so it
* round-trips through JSON and a match can be resumed or replayed exactly. * round-trips through JSON and a match can be resumed or replayed exactly.
*/ */
export type RngState = [number, number, number, number]; export type RngState = number;
function cyrb128(text: string): RngState { /** Hash a string seed (e.g. a lobby id) to a uint32 with FNV-1a. */
let h1 = 1779033703, h2 = 3144134277, h3 = 1013904242, h4 = 2773480762; export function seedFromString(text: string): number {
let h = 0x811c9dc5;
for (let i = 0; i < text.length; i++) { for (let i = 0; i < text.length; i++) {
const k = text.charCodeAt(i); h ^= text.charCodeAt(i);
h1 = h2 ^ Math.imul(h1 ^ k, 597399067); h = Math.imul(h, 0x01000193);
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); return h >>> 0;
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 { export function normalizeSeed(seed: number | string): number {
const state = cyrb128(seed); if (typeof seed === 'string') return seedFromString(seed);
// Warm up so similar seeds diverge. if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) throw new RangeError('Seed must be a uint32 or a string');
const rng = new Rng(state); return seed >>> 0;
for (let i = 0; i < 12; i++) rng.nextUint32();
return rng.state;
} }
/** Mutable wrapper over an RngState. The engine keeps `state` inside MatchState. */ /** Mutable wrapper over an RngState. The engine keeps `state` inside MatchState. */
export class Rng { export class Rng {
state: RngState; state: RngState;
constructor(state: RngState) { this.state = [state[0] >>> 0, state[1] >>> 0, state[2] >>> 0, state[3] >>> 0]; } constructor(state: RngState) { this.state = state >>> 0; }
static fromSeed(seed: string): Rng { return new Rng(seedRng(seed)); } static fromSeed(seed: number | string): Rng { return new Rng(normalizeSeed(seed)); }
nextUint32(): number { /** mulberry32: float in [0, 1). */
let [a, b, c, d] = this.state; next(): number {
const t = (((a + b) | 0) + d) | 0; this.state = (this.state + 0x6d2b79f5) >>> 0;
d = (d + 1) | 0; let t = this.state;
a = b ^ (b >>> 9); t = Math.imul(t ^ (t >>> 15), t | 1);
b = (c + (c << 3)) | 0; t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
c = (c << 21) | (c >>> 11); return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
c = (c + t) | 0;
this.state = [a >>> 0, b >>> 0, c >>> 0, d >>> 0];
return t >>> 0;
} }
/** Float in [0, 1). */ /** Integer in [0, n): floor(next() × n), as DESIGN.md §4 specifies. */
next(): number { return this.nextUint32() / 4294967296; }
/** Integer in [0, n). Unbiased via rejection sampling. */
int(n: number): number { int(n: number): number {
if (!Number.isInteger(n) || n <= 0 || n > 4294967296) throw new RangeError('Rng.int needs a positive integer bound'); if (!Number.isInteger(n) || n <= 0) throw new RangeError('Rng.int needs a positive integer bound');
const limit = 4294967296 - (4294967296 % n); return Math.floor(this.next() * n);
let x: number;
do x = this.nextUint32(); while (x >= limit);
return x % n;
} }
pick<T>(items: readonly T[]): T { pick<T>(items: readonly T[]): T {
if (!items.length) throw new RangeError('Rng.pick on empty list'); if (!items.length) throw new RangeError('Rng.pick on empty list');
return items[this.int(items.length)]; return items[this.int(items.length)];
} }
/** Fisher–Yates; returns a new array. */ /** Fisher–Yates per DESIGN.md §4: i from n−1 down to 1, j = floor(next() × (i+1)). Returns a new array. */
shuffle<T>(items: readonly T[]): T[] { shuffle<T>(items: readonly T[]): T[] {
const out = items.slice(); const out = items.slice();
for (let i = out.length - 1; i > 0; i--) { for (let i = out.length - 1; i > 0; i--) {
+93 -52
View File
@@ -1,43 +1,74 @@
/** /**
* Ruleset: every rule number as data, so peer-hosted modes can vary them * Ruleset (DESIGN §9 RulesConfig): every rule number as data, so peer-hosted
* without running code. parseRuleset() is the only way untrusted JSON should * modes can vary them without running code. parseRuleset() is the only way
* become a Ruleset; it enforces bounds that keep matches short and terminating. * untrusted JSON should become a Ruleset; its bounds keep matches short and
* guarantee termination.
*/ */
import { z } from 'zod'; import { z } from 'zod';
import { KEYWORDS, LANE_MODIFIERS } from './keywords.ts'; import { KEYWORDS, PORTALS } from './keywords.ts';
import type { Ruleset } from './types.ts'; import { STATS, type Ruleset } from './types.ts';
const int = (min: number, max: number) => z.number().int().min(min).max(max); 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)) const id = z.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/);
.refine(value => Object.keys(value).length <= 8, 'Too many params'); const params = z.record(z.string().regex(/^[A-Za-z0-9]{1,24}$/), z.number().finite().min(-100).max(100))
.refine(value => Object.keys(value).length <= 8, 'At most 8 params');
const paramTable = z.record(id, params).refine(value => Object.keys(value).length <= 32, 'At most 32 entries');
export const TopicSchema = z.object({
id, name: z.string().min(1).max(32), stat: z.enum(STATS as [string, ...string[]]), portal: id.nullable(),
}).strict();
export const RulesetSchema = z.object({ export const RulesetSchema = z.object({
id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,47}$/), version: z.string().min(1).max(16),
name: z.string().min(1).max(64), deckSize: int(1, 30),
version: int(1, 1_000_000), maxCopiesPerPage: int(1, 30),
lanes: int(1, 5), maxLoaners: int(0, 30),
openingHand: int(0, 10),
handLimit: int(1, 12),
mulligan: z.literal(false), // not implemented in v1
turns: int(1, 12),
turnSeconds: int(5, 120),
afkTurns: int(1, 12),
energyByTurn: z.array(int(0, 20)).min(1).max(12),
bonusEnergy: int(0, 10),
underdog: z.boolean(),
topicCount: int(1, 5),
distinctStats: z.boolean(),
revealSchedule: z.array(int(1, 12)).max(5),
laneCapacity: int(1, 8), laneCapacity: int(1, 8),
maxTurns: int(1, 12), topicPool: z.array(TopicSchema).min(1).max(32),
deck: z.object({ min: int(1, 40), max: int(1, 40), maxCopiesPerPage: int(1, 40) }).strict(), costThresholds: z.array(int(0, 100)).length(5),
hand: z.object({ start: int(0, 10), max: int(1, 12), drawPerTurn: int(0, 3) }).strict(), powerByCost: z.array(int(0, 30)).length(7),
energy: z.object({ start: int(0, 20), perTurn: int(0, 5), max: int(1, 20) }).strict(), onTopicBonus: int(0, 10),
keywords: z.record(z.string(), params).refine(value => Object.keys(value).length <= 32, 'Too many keywords'), trendUp: z.number().finite().min(-1000).max(1000),
laneModifiers: z.object({ trendDown: z.number().finite().min(-1000).max(1000),
pool: z.array(z.string()).max(32), factionSynergyCap: int(0, 12),
revealTurns: z.array(int(1, 12)).max(5), verifyStats: z.boolean(),
params: z.record(z.string(), params), percentiles: id,
}).strict(), starterDecks: id,
tieBreak: z.enum(['totalPower', 'draw']), keywordParams: paramTable,
portalParams: paramTable,
}).strict().superRefine((rules, ctx) => { }).strict().superRefine((rules, ctx) => {
const issue = (message: string) => ctx.addIssue({ code: 'custom', message }); const issue = (message: string) => ctx.addIssue({ code: 'custom', message });
if (rules.deck.min > rules.deck.max) issue('deck.min > deck.max'); if (rules.turns * rules.turnSeconds > 240) issue('turns × turnSeconds must be ≤ 240');
if (rules.hand.start > rules.hand.max) issue('hand.start > hand.max'); if (rules.energyByTurn.length < rules.turns) issue('energyByTurn needs one entry per turn');
if (rules.energy.start > rules.energy.max) issue('energy.start > energy.max'); if (rules.revealSchedule.length !== rules.topicCount) issue('revealSchedule needs one entry per Topic');
if (rules.laneModifiers.revealTurns.length !== rules.lanes) issue('laneModifiers.revealTurns must have one entry per lane'); if (rules.openingHand > rules.handLimit) issue('openingHand > handLimit');
if (rules.laneModifiers.pool.length && rules.laneModifiers.pool.length < rules.lanes) issue('laneModifiers.pool needs at least one modifier per lane (or be empty)'); if (rules.trendDown > rules.trendUp) issue('trendDown > trendUp');
for (const id of Object.keys(rules.keywords)) if (!Object.hasOwn(KEYWORDS, id)) issue(`Unknown keyword: ${id}`); if (rules.costThresholds.some((value, i) => i > 0 && value < rules.costThresholds[i - 1])) issue('costThresholds must ascend');
for (const id of [...rules.laneModifiers.pool, ...Object.keys(rules.laneModifiers.params)]) if (rules.distinctStats) {
if (!Object.hasOwn(LANE_MODIFIERS, id)) issue(`Unknown lane modifier: ${id}`); if (rules.topicCount > STATS.length) issue('distinctStats allows at most 3 Topics');
const stats = new Set(rules.topicPool.map(topic => topic.stat));
if (stats.size < rules.topicCount) issue('topicPool lacks enough distinct stats');
} else if (rules.topicPool.length < rules.topicCount) issue('topicPool smaller than topicCount');
const topicIds = new Set<string>();
for (const topic of rules.topicPool) {
if (topicIds.has(topic.id)) issue(`Duplicate topic id: ${topic.id}`);
topicIds.add(topic.id);
if (topic.portal && !Object.hasOwn(PORTALS, topic.portal)) issue(`Unknown portal: ${topic.portal}`);
}
for (const key of Object.keys(rules.keywordParams)) if (!Object.hasOwn(KEYWORDS, key)) issue(`Unknown keyword: ${key}`);
for (const key of Object.keys(rules.portalParams)) if (!Object.hasOwn(PORTALS, key)) issue(`Unknown portal: ${key}`);
}); });
/** Validate untrusted ruleset JSON. Throws a ZodError with readable issues. */ /** Validate untrusted ruleset JSON. Throws a ZodError with readable issues. */
@@ -45,26 +76,36 @@ export function parseRuleset(input: unknown): Ruleset {
return RulesetSchema.parse(input) as Ruleset; return RulesetSchema.parse(input) as Ruleset;
} }
/** Placeholder base rules (Snap-style lanes) until DESIGN.md v1 lands. */ /** DESIGN §3: 9 Topics, each stat 3 times: one plain and two with Portals (portals are placeholders until §10.3). */
export const DEFAULT_RULESET: Ruleset = { export const DEFAULT_TOPIC_POOL: Ruleset['topicPool'] = [
id: 'wikideck-standard', { id: 'front-page', name: 'Front Page', stat: 'attention', portal: null },
name: 'WikiDeck Standard', { id: 'trending', name: 'Trending', stat: 'attention', portal: 'spotlight' },
version: 1, { id: 'viral', name: 'Viral', stat: 'attention', portal: 'paywall' },
lanes: 3, { id: 'deep-dive', name: 'Deep Dive', stat: 'depth', portal: null },
laneCapacity: 4, { id: 'archive', name: 'Archive', stat: 'depth', portal: 'spotlight' },
maxTurns: 6, { id: 'citation-needed', name: 'Citation Needed', stat: 'depth', portal: 'paywall' },
deck: { min: 12, max: 12, maxCopiesPerPage: 2 }, { id: 'world-tour', name: 'World Tour', stat: 'reach', portal: null },
hand: { start: 3, max: 7, drawPerTurn: 1 }, { id: 'translation', name: 'Translation', stat: 'reach', portal: 'spotlight' },
energy: { start: 1, perTurn: 1, max: 6 }, { id: 'interwiki', name: 'Interwiki', stat: 'reach', portal: 'paywall' },
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 { /** DESIGN §9 defaults. */
return Math.min(rules.energy.max, rules.energy.start + (turn - 1) * rules.energy.perTurn); export const DEFAULT_RULESET: Ruleset = {
} version: '1.0',
deckSize: 12, maxCopiesPerPage: 2, maxLoaners: 12,
openingHand: 3, handLimit: 7, mulligan: false,
turns: 6, turnSeconds: 25, afkTurns: 2,
energyByTurn: [1, 2, 3, 4, 5, 6], bonusEnergy: 0, underdog: true,
topicCount: 3, distinctStats: true, revealSchedule: [1, 2, 3], laneCapacity: 4,
topicPool: DEFAULT_TOPIC_POOL,
costThresholds: [15, 35, 55, 75, 90],
powerByCost: [0, 1, 2, 4, 5, 7, 9],
onTopicBonus: 2,
trendUp: 25, trendDown: -25,
factionSynergyCap: 3,
verifyStats: true,
percentiles: 'card-sample-2026-11-16',
starterDecks: 'default',
keywordParams: { rally: { amount: 1 }, anchor: { amount: 2 } },
portalParams: { spotlight: { amount: 1 }, paywall: { maxCost: 3 } },
};
+58
View File
@@ -0,0 +1,58 @@
/**
* PLACEHOLDER loaner cards and starter decks (DESIGN §2) so the engine, UI and
* sims can run before council-data's docs/game/starter-cards.json lands.
* Loaners are off-chain preview cards: not NFTs, never minted or moved.
* engine-b / council-data replace STARTER_POOL with derived cards (cards.ts).
*/
import { Rng } from './rng.ts';
import type { Faction, GameCard, Stat } from './types.ts';
type Spec = [pageId: number, title: string, faction: Faction, cost: number, home: Stat, keyword: string | null];
/** Power follows DESIGN §1.3 powerByCost [0,1,2,4,5,7,9]. pageIds outside shared/catalog.ts are unverified. */
const POWER_BY_COST = [0, 1, 2, 4, 5, 7, 9];
export const STARTER_POOL: readonly Spec[] = [
[22780, 'Octopus', 'Nature', 1, 'depth', null],
[19331, 'Moon', 'Space', 1, 'reach', 'anchor'],
[23053, 'Periodic table', 'Science', 1, 'depth', null],
[3383, 'Bronze Age', 'History', 1, 'depth', 'rally'],
[5843419, 'Chess', 'Culture', 2, 'attention', null],
[9228, 'Earth', 'Space', 2, 'reach', 'rally'],
[2008, 'Ada Lovelace', 'People', 2, 'attention', null],
[21830, 'Honey bee', 'Nature', 2, 'depth', 'anchor'],
[736, 'Albert Einstein', 'People', 3, 'reach', null],
[10979, 'Fungus', 'Nature', 3, 'depth', 'rally'],
[26903, 'Solar System', 'Space', 3, 'reach', null],
[30758, 'Roman Empire', 'History', 3, 'depth', 'anchor'],
[9649, 'Evolution', 'Science', 4, 'depth', null],
[8424, 'Jazz', 'Culture', 4, 'attention', 'rally'],
[12898, 'Marie Curie', 'People', 4, 'reach', null],
[14533, 'Silk Road', 'History', 4, 'reach', 'anchor'],
[19468, 'Mount Everest', 'Nature', 5, 'attention', null],
[22936, 'Photosynthesis', 'Science', 5, 'depth', 'rally'],
[18110, 'Leonardo da Vinci', 'People', 5, 'reach', null],
[14627, 'Ancient Egypt', 'History', 5, 'attention', 'anchor'],
[4177, 'Black hole', 'Space', 6, 'attention', null],
[25443, 'Quantum mechanics', 'Science', 6, 'depth', 'rally'],
[17867, 'Library of Alexandria', 'History', 6, 'depth', 'anchor'],
[20217, 'Music', 'Culture', 6, 'reach', null],
];
export function loanerCard(spec: Spec, copy = 0): GameCard {
const [pageId, title, faction, cost, home, keyword] = spec;
return { cardId: `loaner:${pageId}:${copy}`, pageId, title, faction, rarity: 'Common', cost, power: POWER_BY_COST[cost], home, trend: 0, keyword, source: 'loaner' };
}
/** Every placeholder loaner card, once each (24 cards). Draft modes can sample from this. */
export function previewPool(): GameCard[] { return STARTER_POOL.map(spec => loanerCard(spec)); }
/** A deterministic 12-card loaner deck: 2 cards of each cost 1–6, chosen by `seed`. */
export function starterDeck(seed: number | string): GameCard[] {
const rng = Rng.fromSeed(`starter:${seed}`);
const deck: GameCard[] = [];
for (let cost = 1; cost <= 6; cost++) {
deck.push(...rng.shuffle(STARTER_POOL.filter(spec => spec[3] === cost)).slice(0, 2).map(spec => loanerCard(spec)));
}
return deck;
}
+114 -62
View File
@@ -1,6 +1,7 @@
/** /**
* WikiDeck game engine types (off-chain). Everything here is plain JSON data: * WikiDeck game engine types (off-chain). Implements docs/game/DESIGN.md ("Edit War").
* MatchState round-trips through JSON.stringify/parse with no loss. * Everything here is plain JSON data: MatchState round-trips through
* JSON.stringify/parse with no loss (no Maps, classes or functions).
* Contract: docs/game/ENGINE_API.md. Announce changes on claude/wikideck#3. * Contract: docs/game/ENGINE_API.md. Announce changes on claude/wikideck#3.
*/ */
import type { RngState } from './rng.ts'; import type { RngState } from './rng.ts';
@@ -8,50 +9,86 @@ import type { RngState } from './rng.ts';
export type PlayerId = 0 | 1; export type PlayerId = 0 | 1;
export const PLAYERS: readonly PlayerId[] = [0, 1]; export const PLAYERS: readonly PlayerId[] = [0, 1];
/** Category buckets from server/wiki.ts. */ /** Category buckets from server/wiki.ts; a card's faction (DESIGN §1.5). */
export type Category = 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture'; export type Faction = 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
export const FACTIONS: readonly Faction[] = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'];
export type Stat = 'attention' | 'depth' | 'reach';
export const STATS: readonly Stat[] = ['attention', 'depth', 'reach'];
export type Rarity = 'Common' | 'Rare' | 'Epic' | 'Legendary';
/** A card as the engine sees it. Built from enrichment data by cards.ts, or a starter/loaner card. */ /**
* A card as the engine sees it: already derived (DESIGN §1) by cards.ts from a
* host-frozen CardInput. The engine never reads raw snapshot stats. Hosts/modes
* may adjust fields (e.g. power) before createMatch; the engine does not re-derive.
*/
export interface GameCard { export interface GameCard {
/** Unique within one deck (e.g. the NFT card hash, or `starter:<pageId>:<n>`). */ /** Unique within one deck (the NFT card hash, or `loaner:<pageId>:<n>`). */
id: string; cardId: string;
name: string; pageId: number;
pageId: number | null; title: string;
category: Category; faction: Faction;
/** Cosmetic in v1 (§1.7). */
rarity: Rarity;
cost: number; cost: number;
power: number; power: number;
/** Keyword id from the ruleset's keyword list, or null. */ home: Stat;
/** Live trend arrow, frozen at match start (§1.6). Adds to power in every Topic. */
trend: -1 | 0 | 1;
keyword: string | null; keyword: string | null;
/** 'owned' = an NFT the player holds (never moved or burned by a match). */ /** 'owned' = an NFT the player holds (never moved or burned by a match). */
source: 'owned' | 'starter' | 'loaner'; source: 'owned' | 'loaner';
/** Optional display/tie-break data; never used for rules unless a keyword says so. */
meta?: Record<string, string | number | boolean | null>;
} }
/** All rule numbers. Peer-hosted modes override these as data (see ruleset.ts). */ /** A Topic (lane) definition in a ruleset's topic pool (§3). */
export interface Ruleset { export interface TopicDef {
id: string; id: string;
name: string; name: string;
version: number; stat: Stat;
lanes: number; /** Portal modifier id (§10.3), or null for a plain Topic. */
/** Cards that may sit on one side of one lane. */ portal: string | null;
}
/**
* DESIGN §9 RulesConfig: every rule number as flat data so peer-hosted modes can
* override it. Use parseRuleset() for untrusted input.
* Engine additions beyond §9: topicPool holds TopicDefs inline (not a name);
* keywordParams / portalParams hold tunable numbers per keyword / portal id.
*/
export interface Ruleset {
version: string;
deckSize: number;
maxCopiesPerPage: number;
maxLoaners: number;
openingHand: number;
handLimit: number;
mulligan: boolean;
turns: number;
turnSeconds: number;
afkTurns: number;
/** energyByTurn[t-1] is the base energy on turn t. Length must be ≥ turns. */
energyByTurn: number[];
bonusEnergy: number;
underdog: boolean;
topicCount: number;
distinctStats: boolean;
/** revealSchedule[i] = turn on which Topic i is revealed. Length = topicCount. */
revealSchedule: number[];
laneCapacity: number; laneCapacity: number;
maxTurns: number; topicPool: TopicDef[];
deck: { min: number; max: number; maxCopiesPerPage: number }; costThresholds: number[];
hand: { start: number; max: number; drawPerTurn: number }; /** Index = cost (0–6). */
/** Energy available on turn t (1-based) = min(max, start + (t - 1) * perTurn). Unspent energy is lost. */ powerByCost: number[];
energy: { start: number; perTurn: number; max: number }; onTopicBonus: number;
/** Keyword ids that cards may carry in this mode, with tunable numbers per keyword. */ trendUp: number;
keywords: Record<string, Record<string, number>>; trendDown: number;
laneModifiers: { factionSynergyCap: number;
/** Pool of lane modifier ids; one is drawn (without replacement) per lane at match start. */ verifyStats: boolean;
pool: string[]; /** Id of the percentile reference table used by cards.ts. */
/** Turn on which lane i's modifier becomes visible and active (length = lanes). */ percentiles: string;
revealTurns: number[]; /** Id of the starter deck list used by cards.ts. */
params: Record<string, Record<string, number>>; starterDecks: string;
}; keywordParams: Record<string, Record<string, number>>;
/** How the match ends when lanes tie on count. */ portalParams: Record<string, Record<string, number>>;
tieBreak: 'totalPower' | 'draw';
} }
export interface CardInPlay { export interface CardInPlay {
@@ -60,48 +97,54 @@ export interface CardInPlay {
lane: number; lane: number;
/** Turn the card was revealed. */ /** Turn the card was revealed. */
turn: number; turn: number;
/** Permanent power changes from effects (onReveal buffs etc.). */ /** Permanent power changes from effects (on-reveal buffs etc.). */
bonus: number; bonus: number;
} }
export interface StagedPlay { cardId: string; lane: number } export interface QueuedPlay { cardId: string; lane: number }
export interface PlayerState { export interface PlayerState {
deck: GameCard[]; deck: GameCard[];
hand: GameCard[]; hand: GameCard[];
/** Energy left this turn (after staging). */ /** Energy available this turn (before queued plays). */
energy: number; energy: number;
/** Plays chosen this turn, hidden from the opponent until reveal. Order matters. */ /** Plays chosen this turn, hidden from the opponent until reveal. Order matters. */
staged: StagedPlay[]; queue: QueuedPlay[];
ended: boolean; committed: boolean;
discard: GameCard[]; /** Consecutive timeouts with nothing queued (§7 afkTurns). */
afk: number;
} }
export interface LaneState { export interface LaneState {
modifier: string | null; topic: TopicDef;
revealed: boolean;
cards: [CardInPlay[], CardInPlay[]]; cards: [CardInPlay[], CardInPlay[]];
} }
export type MatchPhase = 'planning' | 'over'; export type MatchPhase = 'planning' | 'over';
export type LogEvent = export type LogEvent =
| { t: 'turnStart'; turn: number; energy: [number, number] } | { t: 'turnStart'; turn: number; energy: [number, number]; initiative: PlayerId }
| { t: 'topicRevealed'; lane: number; topic: TopicDef }
| { t: 'underdog'; player: PlayerId }
| { t: 'draw'; player: PlayerId; cardId: string } | { t: 'draw'; player: PlayerId; cardId: string }
| { t: 'reveal'; player: PlayerId; cardId: string; lane: number } | { t: 'reveal'; player: PlayerId; cardId: string; lane: number }
| { t: 'laneRevealed'; lane: number; modifier: string | null } | { t: 'fizzle'; player: PlayerId; cardId: string; lane: number }
| { t: 'effect'; source: string; player: PlayerId; text: string } | { t: 'effect'; source: string; player: PlayerId; text: string }
| { t: 'concede'; player: PlayerId } | { t: 'concede'; player: PlayerId; afk: boolean }
| { t: 'matchOver'; result: MatchResult }; | { t: 'matchOver'; result: MatchResult };
export interface MatchState { export interface MatchState {
schema: 'wikideck-match/1'; schema: 'wikideck-match/1';
engineVersion: number;
ruleset: Ruleset; ruleset: Ruleset;
seed: string; seed: number;
rng: RngState; rng: RngState;
/** 1-based current turn. */
turn: number; turn: number;
phase: MatchPhase; phase: MatchPhase;
/** Player who reveals first this turn. */ /** Player who reveals first this turn (§5.4). */
firstToReveal: PlayerId; initiative: PlayerId;
players: [PlayerState, PlayerState]; players: [PlayerState, PlayerState];
lanes: LaneState[]; lanes: LaneState[];
log: LogEvent[]; log: LogEvent[];
@@ -111,44 +154,53 @@ export interface MatchState {
} }
export type Action = export type Action =
/** Queue a card from hand into a lane (§5.3). */
| { type: 'play'; player: PlayerId; cardId: string; lane: number } | { type: 'play'; player: PlayerId; cardId: string; lane: number }
/** Take back a staged (unrevealed) play this turn; refunds its energy. */ /** Take back a queued play this turn (refunds its energy). */
| { type: 'unstage'; player: PlayerId; cardId: string } | { type: 'undo'; player: PlayerId; cardId: string }
| { type: 'endTurn'; player: PlayerId } /** Commit the queue (empty = pass). When both have committed, the turn resolves. */
| { type: 'commit'; player: PlayerId }
/** The host's turn timer expired for this player: commits what's queued, counts toward afkTurns if empty. */
| { type: 'timeout'; player: PlayerId }
| { type: 'concede'; player: PlayerId }; | { type: 'concede'; player: PlayerId };
export interface MatchResult { export interface MatchResult {
/** null = draw. */ /** null = draw. */
winner: PlayerId | null; winner: PlayerId | null;
reason: 'lanes' | 'totalPower' | 'draw' | 'concede'; reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk';
lanesWon: [number, number]; topicsLed: [number, number];
/** lanePower[lane][player] at the end. */ /** lanePower[lane][player] at the end. */
lanePower: [number, number][]; lanePower: [number, number][];
totalPower: [number, number]; totalPower: [number, number];
turns: number; turns: number;
} }
/** What one player is allowed to see. Use this for UI and AI, never raw MatchState. */ /** What one player is allowed to see. UI and AI read only this, never raw MatchState. */
export interface PlayerView { export interface PlayerView {
you: PlayerId; you: PlayerId;
ruleset: Ruleset; ruleset: Ruleset;
turn: number; turn: number;
phase: MatchPhase; phase: MatchPhase;
firstToReveal: PlayerId; initiative: PlayerId;
energy: number; energy: number;
/** Energy left after your queued plays. */
energyLeft: number;
hand: GameCard[]; hand: GameCard[];
staged: StagedPlay[]; queue: QueuedPlay[];
ended: boolean; committed: boolean;
deckCount: number; deckCount: number;
opponent: { handCount: number; deckCount: number; stagedCount: number; ended: boolean }; opponent: { handCount: number; deckCount: number; queuedCount: number; committed: boolean };
lanes: { lanes: {
/** null when not yet revealed. */ /** null while face-down. */
modifier: string | null; topic: TopicDef | null;
modifierRevealed: boolean; /** cards[0] = yours, cards[1] = opponent's (revealed cards only). */
/** cards[0] = yours, cards[1] = opponent's (revealed only). */
cards: [CardInPlay[], CardInPlay[]]; cards: [CardInPlay[], CardInPlay[]];
/** Lane power of each card in `cards`, same shape. */
cardPower: [number[], number[]];
/** power[0] = yours, power[1] = opponent's. */ /** power[0] = yours, power[1] = opponent's. */
power: [number, number]; power: [number, number];
/** Who leads this Topic from your point of view. */
leader: 'you' | 'opponent' | null;
}[]; }[];
result: MatchResult | null; result: MatchResult | null;
} }
+142
View File
@@ -0,0 +1,142 @@
// Core-loop tests owned by engine-a. Keyword, property and golden tests: engine-b (tests/game-*.test.ts).
import test from 'node:test';
import assert from 'node:assert/strict';
import {
DEFAULT_RULESET, IllegalActionError, Rng, applyAction, cardPower, createMatch, deserialize, isOver, legalActions,
loanerCard, parseRuleset, placeCard, replay, result, revealTopic, serialize, starterDeck, STARTER_POOL, topicsLed, viewFor,
type Action, type GameCard, type MatchState, type PlayerId, type Ruleset,
} from '../shared/game/index.ts';
const decks = (seed = 'd'): [GameCard[], GameCard[]] => [starterDeck(`${seed}-a`), starterDeck(`${seed}-b`)];
const commitBoth = (s: MatchState) => applyAction(applyAction(s, { type: 'commit', player: 0 }), { type: 'commit', player: 1 });
const vanilla = (cost: number, overrides: Partial<GameCard> = {}): GameCard =>
({ ...loanerCard(STARTER_POOL.find(s => s[3] === cost && s[5] === null)!), keyword: null, ...overrides });
function randomPlay(seed: number, ruleset: Ruleset = DEFAULT_RULESET): MatchState {
let state = createMatch(ruleset, decks(String(seed)), seed);
const chooser = Rng.fromSeed(`bot:${seed}`);
for (let steps = 0; !isOver(state); steps++) {
assert.ok(steps < 2000, 'match must terminate');
const player = chooser.int(2) as PlayerId;
const actions = legalActions(state, player);
if (actions.length) state = applyAction(state, chooser.pick(actions));
}
return state;
}
test('mulberry32 matches the reference sequence and is seed-deterministic', () => {
// Reference: mulberry32(1) first output = 0.6270739405881613.
assert.equal(new Rng(1).next(), 0.6270739405881613);
const seq = (r: Rng) => Array.from({ length: 8 }, () => r.next());
assert.deepEqual(seq(Rng.fromSeed(42)), seq(Rng.fromSeed(42)));
assert.notDeepEqual(seq(Rng.fromSeed(42)), seq(Rng.fromSeed(43)));
assert.equal(Rng.fromSeed('lobby-1').state, Rng.fromSeed('lobby-1').state);
});
test('DEFAULT_RULESET matches DESIGN §9 and parses; bad rulesets are rejected', () => {
assert.deepEqual(parseRuleset(DEFAULT_RULESET), DEFAULT_RULESET);
assert.equal(DEFAULT_RULESET.turns, 6);
assert.deepEqual(DEFAULT_RULESET.powerByCost, [0, 1, 2, 4, 5, 7, 9]);
for (const bad of [{ turns: 13 }, { turnSeconds: 60 }, { energyByTurn: [1, 2] }, { revealSchedule: [1, 2] },
{ keywordParams: { nope: {} } }, { extra: 1 }, { mulligan: true }, { costThresholds: [90, 1, 2, 3, 4] }])
assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, ...bad }), JSON.stringify(bad));
});
test('setup: one Topic per stat, all face-down except Topic 1 on turn 1, hands of 4, energy 1', () => {
const state = createMatch(DEFAULT_RULESET, decks(), 7);
assert.equal(state.turn, 1);
assert.deepEqual(state.lanes.map(l => l.topic.stat).sort(), ['attention', 'depth', 'reach']);
assert.deepEqual(state.lanes.map(l => l.revealed), [true, false, false]);
for (const p of state.players) { assert.equal(p.hand.length, 4); assert.equal(p.deck.length, 8); assert.equal(p.energy, 1); }
assert.deepEqual(viewFor(state, 0).lanes.map(l => l.topic === null), [false, true, true]);
});
test('decks are validated: size, copies per page, unknown keyword', () => {
const [a, b] = decks();
assert.throws(() => createMatch(DEFAULT_RULESET, [a.slice(0, 11), b], 1), IllegalActionError);
const triple = [...a.slice(0, 9), ...[0, 1, 2].map(n => ({ ...a[0], cardId: `x${n}` }))];
assert.throws(() => createMatch(DEFAULT_RULESET, [triple, b], 1), /copies/);
assert.throws(() => createMatch(DEFAULT_RULESET, [[{ ...a[0], keyword: 'nope' }, ...a.slice(1)], b], 1), /unknown keyword/);
});
test('queued plays are hidden from the opponent until reveal; undo refunds', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 11);
const play = legalActions(state, 0).find(a => a.type === 'play') as Extract<Action, { type: 'play' }>;
assert.ok(play, 'turn 1 should have a 1-cost play');
state = applyAction(state, play);
assert.equal(viewFor(state, 0).energyLeft, 0);
assert.equal(viewFor(state, 1).opponent.queuedCount, 1);
assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false);
const undone = applyAction(state, { type: 'undo', player: 0, cardId: play.cardId });
assert.equal(viewFor(undone, 0).energyLeft, 1);
state = commitBoth(state);
assert.equal(state.turn, 2);
assert.equal(viewFor(state, 1).lanes[play.lane].cards[1][0].card.cardId, play.cardId);
assert.throws(() => applyAction(state, { type: 'play', player: 0, cardId: play.cardId, lane: 0 }), IllegalActionError);
});
test('energy cap and lane capacity are enforced when queuing', () => {
const state = createMatch(DEFAULT_RULESET, decks(), 3);
for (const a of legalActions(state, 0)) if (a.type === 'play') assert.ok(state.players[0].hand.find(c => c.cardId === a.cardId)!.cost <= 1);
let full = state;
for (let i = 0; i < 4; i++) full = placeCard(full, 0, 0, vanilla(1, { cardId: `f${i}` }));
assert.ok(legalActions(full, 0).every(a => a.type !== 'play' || a.lane !== 0));
});
test('lane power: base + on-topic bonus (revealed only) + trend, floored at 0', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 5);
const lane = 1; // face-down on turn 1
const stat = state.lanes[lane].topic.stat;
state = placeCard(state, 0, lane, vanilla(3, { cardId: 'on', home: stat, trend: 1 }));
const card = () => state.lanes[lane].cards[0][0];
assert.equal(cardPower(state, card()), 4 + 1);
state = revealTopic(state, lane);
assert.equal(cardPower(state, card()), 4 + 2 + 1);
state = placeCard(state, 1, lane, vanilla(1, { cardId: 'neg', home: stat === 'depth' ? 'reach' : 'depth', trend: -1, power: 0 }));
assert.equal(cardPower(state, state.lanes[lane].cards[1][0]), 0);
});
test('initiative: leader reveals first next turn; even board alternates', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 9);
const first = state.initiative;
state = commitBoth(state); // nobody played: even
assert.equal(state.initiative, first === 0 ? 1 : 0);
});
test('underdog: +1 energy for a player leading 0 Topics while the opponent leads 2+', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 13);
state = placeCard(state, 1, 0, vanilla(1, { cardId: 'u1' }));
state = placeCard(state, 1, 1, vanilla(1, { cardId: 'u2' }));
state = commitBoth(state);
assert.deepEqual(topicsLed(state), [0, 2]);
assert.equal(state.players[0].energy, 3);
assert.equal(state.players[1].energy, 2);
});
test('timeouts with nothing queued concede after afkTurns; concede ends the match', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 17);
state = applyAction(applyAction(state, { type: 'timeout', player: 0 }), { type: 'commit', player: 1 });
assert.equal(isOver(state), false);
state = applyAction(state, { type: 'timeout', player: 0 });
assert.equal(result(state)?.winner, 1);
assert.equal(result(state)?.reason, 'afk');
const conceded = applyAction(createMatch(DEFAULT_RULESET, decks(), 1), { type: 'concede', player: 1 });
assert.equal(result(conceded)?.winner, 0);
assert.deepEqual(legalActions(conceded, 0), []);
});
test('two passing players draw after 6 turns', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 21);
while (!isOver(state)) state = commitBoth(state);
assert.deepEqual({ winner: result(state)!.winner, reason: result(state)!.reason, turns: result(state)!.turns }, { winner: null, reason: 'draw', turns: 6 });
});
test('random legal play terminates, replays exactly, and survives serialisation after every action', () => {
for (let seed = 0; seed < 30; seed++) {
const end = randomPlay(seed);
assert.ok(result(end)!.turns <= DEFAULT_RULESET.turns);
assert.deepEqual(randomPlay(seed), end);
assert.deepEqual(replay(DEFAULT_RULESET, decks(String(seed)), seed, end.actions), end);
assert.deepEqual(deserialize(serialize(end)), end);
}
});
-95
View File
@@ -1,95 +0,0 @@
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<Action, { type: 'play' }>;
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<Action, { type: 'play' }>;
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);
}
});