From 7c86ed35f5a688e277b4cd590dc033254eb4bdd7 Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 22:50:45 -0500
Subject: [PATCH 01/14] Game engine scaffold: seeded RNG, types, Ruleset
schema, core loop
Pure deterministic off-chain engine in shared/game: createMatch, legalActions,
applyAction, isOver, result, viewFor, serialize/deserialize, replay. Placeholder
Snap-style lanes rules until DESIGN.md v1; keyword hook registry for engine-b.
Co-Authored-By: Claude Opus 5.5
---
shared/game/cards.ts | 92 +++++++++++
shared/game/engine.ts | 324 ++++++++++++++++++++++++++++++++++++++
shared/game/index.ts | 10 ++
shared/game/keywords.ts | 85 ++++++++++
shared/game/rng.ts | 73 +++++++++
shared/game/ruleset.ts | 70 ++++++++
shared/game/types.ts | 158 +++++++++++++++++++
tests/game-engine.test.ts | 95 +++++++++++
8 files changed, 907 insertions(+)
create mode 100644 shared/game/cards.ts
create mode 100644 shared/game/engine.ts
create mode 100644 shared/game/index.ts
create mode 100644 shared/game/keywords.ts
create mode 100644 shared/game/rng.ts
create mode 100644 shared/game/ruleset.ts
create mode 100644 shared/game/types.ts
create mode 100644 tests/game-engine.test.ts
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);
+ }
+});
--
2.54.0
From f3b60976400b94c63a290c02195d9afe8877b33f Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 22:55:51 -0500
Subject: [PATCH 02/14] Engine core: align with DESIGN.md draft (Edit War)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
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
---
shared/game/cards.ts | 92 ---------
shared/game/engine.ts | 404 ++++++++++++++++++++++----------------
shared/game/index.ts | 12 +-
shared/game/keywords.ts | 66 ++++---
shared/game/rng.ts | 67 +++----
shared/game/ruleset.ts | 145 +++++++++-----
shared/game/starter.ts | 58 ++++++
shared/game/types.ts | 176 +++++++++++------
tests/game-core.test.ts | 142 ++++++++++++++
tests/game-engine.test.ts | 95 ---------
10 files changed, 707 insertions(+), 550 deletions(-)
delete mode 100644 shared/game/cards.ts
create mode 100644 shared/game/starter.ts
create mode 100644 tests/game-core.test.ts
delete mode 100644 tests/game-engine.test.ts
diff --git a/shared/game/cards.ts b/shared/game/cards.ts
deleted file mode 100644
index 894b126..0000000
--- a/shared/game/cards.ts
+++ /dev/null
@@ -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();
- 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
index dfea21f..ae4466d 100644
--- a/shared/game/engine.ts
+++ b/shared/game/engine.ts
@@ -1,72 +1,103 @@
/**
- * 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.
+ * WikiDeck game engine core ("Edit War", docs/game/DESIGN.md): pure,
+ * deterministic, off-chain. Exported functions never mutate their inputs.
+ * All randomness comes from the match seed via state.rng (mulberry32, §4).
* Contract: docs/game/ENGINE_API.md.
*/
-import { KEYWORDS, LANE_MODIFIERS, type EffectContext } from './keywords.ts';
-import { Rng, seedRng } from './rng.ts';
-import { energyForTurn, parseRuleset } from './ruleset.ts';
+import { KEYWORDS, PORTALS, type EffectContext } from './keywords.ts';
+import { Rng, normalizeSeed } from './rng.ts';
+import { parseRuleset } from './ruleset.ts';
import {
- IllegalActionError, PLAYERS,
+ IllegalActionError, PLAYERS, STATS,
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';
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 = (value: T): T => structuredClone(value);
+const RARITIES = new Set(['Common', 'Rare', 'Epic', 'Legendary']);
+const FACTION_SET = new Set(['Space', 'Nature', 'People', 'Science', 'History', 'Culture']);
// ---------- validation ----------
+/** Problems with a deck under `rules` (empty = legal). DESIGN §2. */
export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[] {
const problems: string[] = [];
- if (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})`);
+ if (!Array.isArray(deck)) return ['Deck must be an array'];
+ if (deck.length !== rules.deckSize) problems.push(`Deck must have exactly ${rules.deckSize} cards (has ${deck.length})`);
const ids = new Set();
const copies = new Map();
+ let loaners = 0;
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}`);
- }
+ if (typeof card?.cardId !== 'string' || !card.cardId || card.cardId.length > 128) { problems.push('cardId must be a non-empty string'); continue; }
+ const label = card.cardId;
+ if (ids.has(card.cardId)) problems.push(`Duplicate cardId ${label}`);
+ ids.add(card.cardId);
+ if (!Number.isInteger(card.pageId)) problems.push(`${label}: bad pageId`);
+ if (typeof card.title !== 'string' || card.title.length > 256) problems.push(`${label}: bad title`);
+ if (!FACTION_SET.has(card.faction)) problems.push(`${label}: bad faction`);
+ if (!RARITIES.has(card.rarity)) problems.push(`${label}: bad rarity`);
+ if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 6) problems.push(`${label}: cost must be 0–6`);
+ if (!Number.isInteger(card.power) || card.power < 0 || card.power > 30) problems.push(`${label}: power must be 0–30`);
+ if (!STATS.includes(card.home)) problems.push(`${label}: bad home stat`);
+ if (card.trend !== -1 && card.trend !== 0 && card.trend !== 1) problems.push(`${label}: trend must be -1, 0 or 1`);
+ if (card.keyword !== null && !Object.hasOwn(KEYWORDS, card.keyword)) problems.push(`${label}: unknown keyword ${card.keyword}`);
+ if (card.source !== 'owned' && card.source !== 'loaner') problems.push(`${label}: bad source`);
+ if (card.source === 'loaner') loaners++;
+ const n = (copies.get(card.pageId) ?? 0) + 1;
+ copies.set(card.pageId, n);
+ if (n === rules.maxCopiesPerPage + 1) problems.push(`More than ${rules.maxCopiesPerPage} copies of page ${card.pageId}`);
}
+ if (loaners > rules.maxLoaners) problems.push(`At most ${rules.maxLoaners} loaner cards`);
return problems;
}
-// ---------- match setup ----------
+// ---------- match setup (§4) ----------
/**
- * Start a match. `decks[0]` belongs to player 0. Throws IllegalActionError for an
- * invalid deck and ZodError for an invalid ruleset.
+ * Draw the match's Topics (§4.2.3). distinctStats: for each stat in STATS order
+ * (attention, depth, reach) pick one Topic of that stat with rng.int(groupSize),
+ * then Fisher–Yates the picks, then keep the first topicCount. Otherwise
+ * Fisher–Yates the whole pool and keep the first topicCount.
*/
-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('; ')}`);
+function drawTopics(rules: Ruleset, rng: Rng): TopicDef[] {
+ if (!rules.distinctStats) return rng.shuffle(rules.topicPool).slice(0, rules.topicCount);
+ const picked: TopicDef[] = [];
+ for (const stat of STATS) {
+ const group = rules.topicPool.filter(topic => topic.stat === stat);
+ if (group.length) picked.push(group[rng.int(group.length)]);
}
- const rng = new Rng(seedRng(seed));
- const modifiers = rules.laneModifiers.pool.length ? rng.shuffle(rules.laneModifiers.pool).slice(0, rules.lanes) : [];
+ return rng.shuffle(picked).slice(0, rules.topicCount);
+}
+
+/**
+ * Start a match. `decks[0]` belongs to seat 0. Seed is a uint32 (or a string,
+ * hashed with FNV-1a). Throws ZodError for a bad ruleset, IllegalActionError for a bad deck.
+ */
+export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: number | string): MatchState {
+ const rules = parseRuleset(clone(ruleset));
+ const seedValue = normalizeSeed(seed);
+ for (const player of PLAYERS) {
+ const problems = validateDeck(rules, decks?.[player] as GameCard[]);
+ if (problems.length) throw new IllegalActionError(`Seat ${player} deck: ${problems.join('; ')}`);
+ }
+ const rng = new Rng(seedValue);
const newPlayer = (player: PlayerId): PlayerState => ({
- deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, 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 = {
- 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[]] })),
+ schema: 'wikideck-match/1', engineVersion: ENGINE_VERSION, ruleset: rules, seed: seedValue, rng: rng.state,
+ turn: 0, phase: 'planning', initiative, players: [p0, p1],
+ lanes: topics.map(topic => ({ topic: clone(topic), revealed: false, cards: [[], []] as [CardInPlay[], CardInPlay[]] })),
log: [], actions: [], result: null,
};
- for (const player of PLAYERS) for (let i = 0; i < rules.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);
state.rng = rng.state;
return state;
@@ -74,136 +105,139 @@ export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard
function draw(state: MatchState, player: PlayerId): void {
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()!;
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;
+ state.log.push({ t: 'draw', player, cardId: card.cardId });
}
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;
+function portalOf(state: MatchState, lane: number) {
+ 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 {
- 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 rules = state.ruleset;
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);
+ const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness
+ let power = target.card.power + target.bonus + target.card.trend;
+ if (lane.revealed && lane.topic.stat === target.card.home) power += rules.onTopicBonus;
+ for (const l of state.lanes) for (const side of l.cards) for (const source of side) {
+ const keyword = source.card.keyword ? KEYWORDS[source.card.keyword] : undefined;
+ if (keyword?.ongoing) power += keyword.ongoing(context(state, scratch, rules.keywordParams[keyword.id], source.lane, keyword.id, source.owner), source, target);
}
- 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] {
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 };
+/** Number of Topics each seat leads (strictly more power). */
+export function topicsLed(state: MatchState): [number, number] {
+ const led: [number, number] = [0, 0];
+ state.lanes.forEach((_, lane) => {
+ const [a, b] = lanePower(state, lane);
+ if (a > b) led[0]++; else if (b > a) led[1]++;
+ });
+ return led;
}
-// ---------- actions ----------
+// ---------- actions (§5.3) ----------
-function stagedInLane(p: PlayerState, lane: number): number {
- return p.staged.filter(play => play.lane === lane).length;
+const queuedCost = (p: PlayerState) => p.queue.reduce((sum, play) => sum + (p.hand.find(c => c.cardId === play.cardId)?.cost ?? 0), 0);
+const queuedInLane = (p: PlayerState, lane: number) => p.queue.filter(play => play.lane === lane).length;
+
+function laneRejects(state: MatchState, lane: number, card: GameCard, player: PlayerId): string | null {
+ const portal = portalOf(state, lane);
+ if (!portal?.canPlay) return null;
+ const ctx = context(state, new Rng(state.rng), state.ruleset.portalParams[portal.id], lane, portal.id, player);
+ return portal.canPlay(ctx, card, player) ? null : `${portal.name} rejects this card`;
}
function playProblem(state: MatchState, action: Extract): 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 (p.committed) return 'Already committed this turn';
+ const card = p.hand.find(c => c.cardId === action.cardId);
if (!card) return 'Card is not in your hand';
- if (p.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;
+ if (p.queue.some(play => play.cardId === action.cardId)) return 'Card is already queued';
+ if (!Number.isInteger(action.lane) || action.lane < 0 || action.lane >= state.lanes.length) return 'No such Topic';
+ if (card.cost > p.energy - queuedCost(p)) return 'Not enough energy';
+ if (state.lanes[action.lane].cards[action.player].length + queuedInLane(p, action.lane) >= state.ruleset.laneCapacity) return 'Topic is full';
+ return laneRejects(state, action.lane, card, action.player);
}
/** Why `action` is illegal in `state`, or null if it is legal. */
export function actionProblem(state: MatchState, action: Action): string | null {
if (state.phase === 'over') return 'Match is over';
if (!action || (action.player !== 0 && action.player !== 1)) return 'Unknown player';
+ const p = state.players[action.player];
switch (action.type) {
case 'play': return playProblem(state, action);
- case '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 'undo':
+ if (p.committed) return 'Already committed this turn';
+ return p.queue.some(play => play.cardId === action.cardId) ? null : 'Card is not queued';
+ case 'commit':
+ case 'timeout':
+ return p.committed ? 'Already committed this turn' : null;
case 'concede': return null;
default: return 'Unknown action';
}
}
/**
- * Every legal action for `player` except `concede` (always legal while the match
- * is running). `endTurn` is always included while the player hasn't ended.
+ * Legal actions for `player`: every `play`, every `undo`, and `commit`.
+ * `concede` (always legal while running) and `timeout` (host-only) are not listed.
+ * Empty once the player has committed or the match is over.
*/
export function legalActions(state: MatchState, player: PlayerId): Action[] {
if (state.phase === 'over') return [];
const p = state.players[player];
- if (p.ended) return [];
+ if (p.committed) return [];
const actions: Action[] = [];
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++) {
- 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);
}
}
- for (const play of p.staged) actions.push({ type: 'unstage', player, cardId: play.cardId });
- actions.push({ type: 'endTurn', player });
+ for (const play of p.queue) actions.push({ type: 'undo', player, cardId: play.cardId });
+ actions.push({ type: 'commit', player });
return actions;
}
@@ -216,67 +250,77 @@ export function applyAction(state: MatchState, action: Action): MatchState {
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;
+ case 'play': p.queue.push({ cardId: action.cardId, lane: action.lane }); break;
+ case 'undo': p.queue.splice(p.queue.findIndex(play => play.cardId === action.cardId), 1); break;
+ case 'commit': p.committed = true; p.afk = 0; break;
+ case 'timeout':
+ p.committed = true;
+ p.afk = p.queue.length ? 0 : p.afk + 1;
+ if (p.afk >= next.ruleset.afkTurns) {
+ next.log.push({ t: 'concede', player: action.player, afk: true });
+ finish(next, other(action.player), 'afk');
+ }
break;
- }
- case '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 });
+ case 'concede':
+ next.log.push({ t: 'concede', player: action.player, afk: false });
finish(next, other(action.player), 'concede');
break;
- }
}
+ if (next.phase !== 'over' && next.players.every(player => player.committed)) resolveTurn(next, rng);
next.rng = rng.state;
return next;
}
+/** §5.4 Reveal and §5.5 End. */
function resolveTurn(state: MatchState, rng: Rng): void {
- 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];
- for (const play of p.staged) {
- const index = p.hand.findIndex(c => c.id === play.cardId);
- const [card] = p.hand.splice(index, 1);
+ for (const play of p.queue) {
+ const index = p.hand.findIndex(c => c.cardId === play.cardId);
+ const card = p.hand[index];
+ if (index < 0 || state.lanes[play.lane].cards[player].length >= rules.laneCapacity || laneRejects(state, play.lane, card, player)) {
+ state.log.push({ t: 'fizzle', player, cardId: play.cardId, lane: play.lane }); // stays in hand, energy lost
+ continue;
+ }
+ p.hand.splice(index, 1);
const inPlay: CardInPlay = { card, owner: player, lane: play.lane, turn: state.turn, bonus: 0 };
state.lanes[play.lane].cards[player].push(inPlay);
- state.log.push({ t: 'reveal', player, cardId: card.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);
- }
+ state.log.push({ t: 'reveal', player, cardId: card.cardId, lane: play.lane });
+ const keyword = card.keyword ? KEYWORDS[card.keyword] : undefined;
+ keyword?.onReveal?.(context(state, rng, rules.keywordParams[keyword.id], play.lane, keyword.id, player), inPlay);
+ const portal = portalOf(state, play.lane);
+ portal?.onReveal?.(context(state, rng, rules.portalParams[portal.id], play.lane, portal.id, player), inPlay);
}
- p.staged = [];
+ p.queue = [];
}
- if (state.turn >= state.ruleset.maxTurns) finish(state, null, 'lanes');
- else startTurn(state, rng);
+ for (const player of order) for (const lane of state.lanes) for (const card of lane.cards[player].slice()) {
+ const keyword = card.card.keyword ? KEYWORDS[card.card.keyword] : undefined;
+ keyword?.endOfTurn?.(context(state, rng, rules.keywordParams[keyword.id], card.lane, keyword.id, player), card);
+ }
+ if (state.turn >= rules.turns) { finish(state, null, 'topics'); return; }
+ const led = topicsLed(state);
+ state.initiative = led[0] !== led[1] ? (led[0] > led[1] ? 0 : 1) : other(state.initiative);
+ startTurn(state, rng);
}
-function finish(state: MatchState, concedeWinner: PlayerId | null, reason: 'lanes' | 'concede'): void {
- const s = score(state);
- let winner: PlayerId | null = concedeWinner;
+/** §7. */
+function finish(state: MatchState, forcedWinner: PlayerId | null, reason: 'topics' | 'concede' | 'afk'): void {
+ const lanePowers = state.lanes.map((_, lane) => lanePower(state, lane));
+ const topicsLedNow = topicsLed(state);
+ const totalPower: [number, number] = [0, 0];
+ for (const [a, b] of lanePowers) { totalPower[0] += a; totalPower[1] += b; }
+ let winner: PlayerId | null = forcedWinner;
let why: MatchResult['reason'] = reason;
- if (reason !== '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';
+ if (reason === 'topics') {
+ if (topicsLedNow[0] !== topicsLedNow[1]) winner = topicsLedNow[0] > topicsLedNow[1] ? 0 : 1;
+ else if (totalPower[0] !== totalPower[1]) { winner = totalPower[0] > totalPower[1] ? 0 : 1; why = 'totalPower'; }
+ else why = 'draw';
}
- state.result = { winner, reason: why, ...s, turns: state.turn };
+ state.result = { winner, reason: why, topicsLed: topicsLedNow, lanePower: lanePowers, totalPower, turns: state.turn };
state.phase = 'over';
- state.log.push({ t: 'matchOver', result: state.result });
+ state.log.push({ t: 'matchOver', result: clone(state.result) });
}
// ---------- 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. */
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 {
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 },
+ you, ruleset: state.ruleset, turn: state.turn, phase: state.phase, initiative: state.initiative,
+ energy: me.energy, energyLeft: me.energy - queuedCost(me), hand: me.hand, queue: me.queue,
+ committed: me.committed, deckCount: me.deck.length,
+ opponent: { handCount: opp.hand.length - opp.queue.length, deckCount: opp.deck.length, queuedCount: opp.queue.length, committed: opp.committed },
lanes: state.lanes.map((lane, index) => {
- const revealed = modifierActive(state, index);
const power = lanePower(state, index);
+ const mine = power[you], theirs = power[them];
return {
- modifier: revealed ? lane.modifier : null, modifierRevealed: revealed,
+ topic: lane.revealed ? lane.topic : null,
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,
});
}
-// ---------- serialisation / replay ----------
+// ---------- serialisation, replay, test helpers ----------
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. */
-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));
+export function replay(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: number | string, actions: readonly Action[]): MatchState {
+ let state = createMatch(ruleset, decks, seed);
+ for (const action of actions) state = applyAction(state, action);
+ return state;
+}
+
+/**
+ * Test helper: put `card` straight into a lane (no on-reveal, no energy, no hand).
+ * Returns a new state. For unit-testing keywords against hand-built boards.
+ */
+export function placeCard(state: MatchState, player: PlayerId, lane: number, card: GameCard, bonus = 0): MatchState {
+ const next = clone(state);
+ next.lanes[lane].cards[player].push({ card: clone(card), owner: player, lane, turn: next.turn, bonus });
+ return next;
+}
+
+/** Test helper: flip a Topic face-up (runs nothing). */
+export function revealTopic(state: MatchState, lane: number): MatchState {
+ const next = clone(state);
+ next.lanes[lane].revealed = true;
+ return next;
}
diff --git a/shared/game/index.ts b/shared/game/index.ts
index 8891a8e..b21d049 100644
--- a/shared/game/index.ts
+++ b/shared/game/index.ts
@@ -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 { Rng, seedRng, type RngState } from './rng.ts';
-export { DEFAULT_RULESET, RulesetSchema, parseRuleset, energyForTurn } from './ruleset.ts';
+export { Rng, seedFromString, normalizeSeed, type RngState } from './rng.ts';
+export { DEFAULT_RULESET, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
export {
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';
-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';
+export { KEYWORDS, PORTALS, allies, type KeywordDef, type PortalDef, type EffectContext } from './keywords.ts';
+export { STARTER_POOL, loanerCard, previewPool, starterDeck } from './starter.ts';
diff --git a/shared/game/keywords.ts b/shared/game/keywords.ts
index 32c8837..d10d6c8 100644
--- a/shared/game/keywords.ts
+++ b/shared/game/keywords.ts
@@ -1,16 +1,20 @@
/**
- * 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.
+ * Keyword and Portal registry (DESIGN §10, §10.3). Effects are code here; which
+ * ones a card/topic uses and their numbers are data (GameCard.keyword,
+ * TopicDef.portal, Ruleset.keywordParams / portalParams).
+ * Owner of the effects: engine-b (claude/wikideck#3). engine-a owns the hook contract:
*
- * 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).
+ * - Hooks get an EffectContext over the engine's *working copy* of the state and may
+ * mutate it (e.g. `bonus` on cards). Mutating is safe: applyAction already cloned.
+ * Any randomness must come from ctx.rng (the match RNG, in resolution order, §4.2.5).
+ * - onReveal: once, right after the card enters its lane (§5.4).
+ * - endOfTurn: every card in play, at §5.5, initiative player's cards first, lanes left→right,
+ * in play order.
+ * - ongoing: PURE. Returns a power delta for `target` while `self` is in play. Called for every
+ * (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 { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts';
@@ -18,28 +22,33 @@ 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. */
+ /** Tunable numbers for this keyword/portal from Ruleset.keywordParams / portalParams. */
params: Record;
+ /** Lane the effect lives in. */
lane: number;
+ /** Add a line to the match log (attributed to this keyword/portal). */
log(text: string): void;
}
export interface KeywordDef {
id: string;
name: string;
- /** Short rules text with {param} placeholders, for card faces/tooltips. */
+ /** One short line of reminder text with {param} placeholders. */
text: string;
onReveal?(ctx: EffectContext, self: CardInPlay): void;
+ endOfTurn?(ctx: EffectContext, self: CardInPlay): void;
ongoing?(ctx: EffectContext, self: CardInPlay, target: CardInPlay): number;
}
-export interface LaneModifierDef {
+export interface PortalDef {
id: string;
name: 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;
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;
}
@@ -48,38 +57,31 @@ export function allies(state: MatchState, self: CardInPlay): CardInPlay[] {
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 = {
- // 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.',
+ id: 'rally', name: 'Rally', text: 'On reveal: +{amount} 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}`);
+ ctx.log(`${self.card.title}: Rally +${amount}`);
},
},
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) {
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;
- },
+export const PORTALS: Record = {
+ spotlight: {
+ id: 'spotlight', name: 'Spotlight', text: 'Cards here get +{amount}.',
+ ongoing(ctx) { return ctx.params.amount ?? 1; },
},
- narrow: {
- id: 'narrow', name: 'Narrow', text: 'Only cards costing {maxCost} or less can be played here.',
+ paywall: {
+ id: 'paywall', name: 'Paywall', text: 'Only cards costing {maxCost} or less.',
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
index 8a11ea8..d680610 100644
--- a/shared/game/rng.ts
+++ b/shared/game/rng.ts
@@ -1,67 +1,50 @@
/**
* 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.
*/
-export type RngState = [number, number, number, number];
+export type RngState = number;
-function cyrb128(text: string): RngState {
- let h1 = 1779033703, h2 = 3144134277, h3 = 1013904242, h4 = 2773480762;
+/** Hash a string seed (e.g. a lobby id) to a uint32 with FNV-1a. */
+export function seedFromString(text: string): number {
+ let h = 0x811c9dc5;
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);
+ h ^= text.charCodeAt(i);
+ h = Math.imul(h, 0x01000193);
}
- 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];
+ return h >>> 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;
+export function normalizeSeed(seed: number | string): number {
+ if (typeof seed === 'string') return seedFromString(seed);
+ if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) throw new RangeError('Seed must be a uint32 or a string');
+ return seed >>> 0;
}
/** 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)); }
+ constructor(state: RngState) { this.state = state >>> 0; }
+ static fromSeed(seed: number | string): Rng { return new Rng(normalizeSeed(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;
+ /** mulberry32: float in [0, 1). */
+ next(): number {
+ this.state = (this.state + 0x6d2b79f5) >>> 0;
+ let t = this.state;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
- /** Float in [0, 1). */
- next(): number { return this.nextUint32() / 4294967296; }
- /** Integer in [0, n). Unbiased via rejection sampling. */
+ /** Integer in [0, n): floor(next() × n), as DESIGN.md §4 specifies. */
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;
+ if (!Number.isInteger(n) || n <= 0) throw new RangeError('Rng.int needs a positive integer bound');
+ return Math.floor(this.next() * 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. */
+ /** Fisher–Yates per DESIGN.md §4: i from n−1 down to 1, j = floor(next() × (i+1)). Returns a new array. */
shuffle(items: readonly T[]): T[] {
const out = items.slice();
for (let i = out.length - 1; i > 0; i--) {
diff --git a/shared/game/ruleset.ts b/shared/game/ruleset.ts
index d7305ca..59aead6 100644
--- a/shared/game/ruleset.ts
+++ b/shared/game/ruleset.ts
@@ -1,43 +1,74 @@
/**
- * 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.
+ * Ruleset (DESIGN §9 RulesConfig): 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; its bounds keep matches short and
+ * guarantee termination.
*/
import { z } from 'zod';
-import { KEYWORDS, LANE_MODIFIERS } from './keywords.ts';
-import type { Ruleset } from './types.ts';
+import { KEYWORDS, PORTALS } from './keywords.ts';
+import { STATS, 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');
+const id = z.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/);
+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({
- 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),
+ version: z.string().min(1).max(16),
+ deckSize: int(1, 30),
+ maxCopiesPerPage: int(1, 30),
+ 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),
- 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']),
+ topicPool: z.array(TopicSchema).min(1).max(32),
+ costThresholds: z.array(int(0, 100)).length(5),
+ powerByCost: z.array(int(0, 30)).length(7),
+ onTopicBonus: int(0, 10),
+ trendUp: z.number().finite().min(-1000).max(1000),
+ trendDown: z.number().finite().min(-1000).max(1000),
+ factionSynergyCap: int(0, 12),
+ verifyStats: z.boolean(),
+ percentiles: id,
+ starterDecks: id,
+ keywordParams: paramTable,
+ portalParams: paramTable,
}).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}`);
+ if (rules.turns * rules.turnSeconds > 240) issue('turns × turnSeconds must be ≤ 240');
+ if (rules.energyByTurn.length < rules.turns) issue('energyByTurn needs one entry per turn');
+ if (rules.revealSchedule.length !== rules.topicCount) issue('revealSchedule needs one entry per Topic');
+ if (rules.openingHand > rules.handLimit) issue('openingHand > handLimit');
+ if (rules.trendDown > rules.trendUp) issue('trendDown > trendUp');
+ if (rules.costThresholds.some((value, i) => i > 0 && value < rules.costThresholds[i - 1])) issue('costThresholds must ascend');
+ if (rules.distinctStats) {
+ 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();
+ 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. */
@@ -45,26 +76,36 @@ 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',
-};
+/** DESIGN §3: 9 Topics, each stat 3 times: one plain and two with Portals (portals are placeholders until §10.3). */
+export const DEFAULT_TOPIC_POOL: Ruleset['topicPool'] = [
+ { id: 'front-page', name: 'Front Page', stat: 'attention', portal: null },
+ { id: 'trending', name: 'Trending', stat: 'attention', portal: 'spotlight' },
+ { id: 'viral', name: 'Viral', stat: 'attention', portal: 'paywall' },
+ { id: 'deep-dive', name: 'Deep Dive', stat: 'depth', portal: null },
+ { id: 'archive', name: 'Archive', stat: 'depth', portal: 'spotlight' },
+ { id: 'citation-needed', name: 'Citation Needed', stat: 'depth', portal: 'paywall' },
+ { id: 'world-tour', name: 'World Tour', stat: 'reach', portal: null },
+ { id: 'translation', name: 'Translation', stat: 'reach', portal: 'spotlight' },
+ { id: 'interwiki', name: 'Interwiki', stat: 'reach', portal: 'paywall' },
+];
-export function energyForTurn(rules: Ruleset, turn: number): number {
- return Math.min(rules.energy.max, rules.energy.start + (turn - 1) * rules.energy.perTurn);
-}
+/** DESIGN §9 defaults. */
+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 } },
+};
diff --git a/shared/game/starter.ts b/shared/game/starter.ts
new file mode 100644
index 0000000..81a45a7
--- /dev/null
+++ b/shared/game/starter.ts
@@ -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;
+}
diff --git a/shared/game/types.ts b/shared/game/types.ts
index 435d3dd..966e48a 100644
--- a/shared/game/types.ts
+++ b/shared/game/types.ts
@@ -1,6 +1,7 @@
/**
- * WikiDeck game engine types (off-chain). Everything here is plain JSON data:
- * MatchState round-trips through JSON.stringify/parse with no loss.
+ * WikiDeck game engine types (off-chain). Implements docs/game/DESIGN.md ("Edit War").
+ * 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.
*/
import type { RngState } from './rng.ts';
@@ -8,50 +9,86 @@ 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';
+/** Category buckets from server/wiki.ts; a card's faction (DESIGN §1.5). */
+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 {
- /** Unique within one deck (e.g. the NFT card hash, or `starter::`). */
- id: string;
- name: string;
- pageId: number | null;
- category: Category;
+ /** Unique within one deck (the NFT card hash, or `loaner::`). */
+ cardId: string;
+ pageId: number;
+ title: string;
+ faction: Faction;
+ /** Cosmetic in v1 (§1.7). */
+ rarity: Rarity;
cost: 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;
/** '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;
+ source: 'owned' | 'loaner';
}
-/** All rule numbers. Peer-hosted modes override these as data (see ruleset.ts). */
-export interface Ruleset {
+/** A Topic (lane) definition in a ruleset's topic pool (§3). */
+export interface TopicDef {
id: string;
name: string;
- version: number;
- lanes: number;
- /** Cards that may sit on one side of one lane. */
+ stat: Stat;
+ /** Portal modifier id (§10.3), or null for a plain Topic. */
+ 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;
- 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';
+ topicPool: TopicDef[];
+ costThresholds: number[];
+ /** Index = cost (0–6). */
+ powerByCost: number[];
+ onTopicBonus: number;
+ trendUp: number;
+ trendDown: number;
+ factionSynergyCap: number;
+ verifyStats: boolean;
+ /** Id of the percentile reference table used by cards.ts. */
+ percentiles: string;
+ /** Id of the starter deck list used by cards.ts. */
+ starterDecks: string;
+ keywordParams: Record>;
+ portalParams: Record>;
}
export interface CardInPlay {
@@ -60,48 +97,54 @@ export interface CardInPlay {
lane: number;
/** Turn the card was revealed. */
turn: number;
- /** Permanent power changes from effects (onReveal buffs etc.). */
+ /** Permanent power changes from effects (on-reveal buffs etc.). */
bonus: number;
}
-export interface StagedPlay { cardId: string; lane: number }
+export interface QueuedPlay { cardId: string; lane: number }
export interface PlayerState {
deck: GameCard[];
hand: GameCard[];
- /** Energy left this turn (after staging). */
+ /** Energy available this turn (before queued plays). */
energy: number;
/** Plays chosen this turn, hidden from the opponent until reveal. Order matters. */
- staged: StagedPlay[];
- ended: boolean;
- discard: GameCard[];
+ queue: QueuedPlay[];
+ committed: boolean;
+ /** Consecutive timeouts with nothing queued (§7 afkTurns). */
+ afk: number;
}
export interface LaneState {
- modifier: string | null;
+ topic: TopicDef;
+ revealed: boolean;
cards: [CardInPlay[], CardInPlay[]];
}
export type MatchPhase = 'planning' | 'over';
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: '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: 'concede'; player: PlayerId }
+ | { t: 'concede'; player: PlayerId; afk: boolean }
| { t: 'matchOver'; result: MatchResult };
export interface MatchState {
schema: 'wikideck-match/1';
+ engineVersion: number;
ruleset: Ruleset;
- seed: string;
+ seed: number;
rng: RngState;
+ /** 1-based current turn. */
turn: number;
phase: MatchPhase;
- /** Player who reveals first this turn. */
- firstToReveal: PlayerId;
+ /** Player who reveals first this turn (§5.4). */
+ initiative: PlayerId;
players: [PlayerState, PlayerState];
lanes: LaneState[];
log: LogEvent[];
@@ -111,44 +154,53 @@ export interface MatchState {
}
export type Action =
+ /** Queue a card from hand into a lane (§5.3). */
| { 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 }
+ /** Take back a queued play this turn (refunds its energy). */
+ | { type: 'undo'; player: PlayerId; cardId: string }
+ /** 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 };
export interface MatchResult {
/** null = draw. */
winner: PlayerId | null;
- reason: 'lanes' | 'totalPower' | 'draw' | 'concede';
- lanesWon: [number, number];
+ reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk';
+ topicsLed: [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. */
+/** What one player is allowed to see. UI and AI read only this, never raw MatchState. */
export interface PlayerView {
you: PlayerId;
ruleset: Ruleset;
turn: number;
phase: MatchPhase;
- firstToReveal: PlayerId;
+ initiative: PlayerId;
energy: number;
+ /** Energy left after your queued plays. */
+ energyLeft: number;
hand: GameCard[];
- staged: StagedPlay[];
- ended: boolean;
+ queue: QueuedPlay[];
+ committed: boolean;
deckCount: number;
- opponent: { handCount: number; deckCount: number; stagedCount: number; ended: boolean };
+ opponent: { handCount: number; deckCount: number; queuedCount: number; committed: boolean };
lanes: {
- /** null when not yet revealed. */
- modifier: string | null;
- modifierRevealed: boolean;
- /** cards[0] = yours, cards[1] = opponent's (revealed only). */
+ /** null while face-down. */
+ topic: TopicDef | null;
+ /** cards[0] = yours, cards[1] = opponent's (revealed cards only). */
cards: [CardInPlay[], CardInPlay[]];
+ /** Lane power of each card in `cards`, same shape. */
+ cardPower: [number[], number[]];
/** power[0] = yours, power[1] = opponent's. */
power: [number, number];
+ /** Who leads this Topic from your point of view. */
+ leader: 'you' | 'opponent' | null;
}[];
result: MatchResult | null;
}
diff --git a/tests/game-core.test.ts b/tests/game-core.test.ts
new file mode 100644
index 0000000..87e5fb3
--- /dev/null
+++ b/tests/game-core.test.ts
@@ -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 =>
+ ({ ...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;
+ 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);
+ }
+});
diff --git a/tests/game-engine.test.ts b/tests/game-engine.test.ts
deleted file mode 100644
index c4255b2..0000000
--- a/tests/game-engine.test.ts
+++ /dev/null
@@ -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;
- 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);
- }
-});
--
2.54.0
From ec244378384f7a1d34c53b2dbefbdaaa2bac3802 Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:13:14 -0500
Subject: [PATCH 03/14] Engine core: implement frozen DESIGN v1 (PR #17) and
publish ENGINE_API.md
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Interleaved reveal, alternating initiative, energy carry, onTopicBonus by cost,
consensus tie-break, hidden Portals with visible stats, laneCapacity 3, Portal
capacity/canPlay/atScoring/allOnTopic hooks, keywordsEnabled dispatch, §10.3
default Topic pool, global reveal seq. KEYWORDS/PORTALS left to engine-b.
Co-Authored-By: Claude Opus 5.5
---
docs/game/ENGINE_API.md | 223 ++++++++++++++++++++++++++++++++++++++++
shared/game/engine.ts | 199 ++++++++++++++++++++++-------------
shared/game/index.ts | 4 +-
shared/game/keywords.ts | 90 ++++++++--------
shared/game/ruleset.ts | 74 +++++++------
shared/game/starter.ts | 66 ++++++------
shared/game/types.ts | 51 ++++++---
tests/game-core.test.ts | 182 +++++++++++++++++++++-----------
8 files changed, 641 insertions(+), 248 deletions(-)
create mode 100644 docs/game/ENGINE_API.md
diff --git a/docs/game/ENGINE_API.md b/docs/game/ENGINE_API.md
new file mode 100644
index 0000000..55cb030
--- /dev/null
+++ b/docs/game/ENGINE_API.md
@@ -0,0 +1,223 @@
+# WikiDeck game engine API (v1)
+
+**Owner:** engine-a (core and API) and engine-b (keywords, card derivation, tests). Issue: claude/wikideck#3.
+**Rules:** `docs/game/DESIGN.md` v1 ("Edit War", as frozen in PR #17 @ cf2fceb). Where this file and DESIGN.md disagree, raise it on #3.
+**Stability:** UI, simulation and modes build against this file. Any change to a name or shape below is
+announced on #3 before it merges.
+
+The engine is a pure TypeScript library in `shared/game/`:
+- It does no I/O and has no clocks: no `Date.now()`, no `Math.random()`.
+- It imports nothing from `server/` or `src/`.
+- It runs entirely **off-chain**. A match never reads, moves, locks or burns an NFT.
+- It is deterministic: the same `(ruleset, decks, seed, actions)` always gives the same state, byte for byte.
+
+**Import only from `shared/game/index.ts`.**
+
+```ts
+import { createMatch, legalActions, applyAction, isOver, result, viewFor,
+ serialize, deserialize, replay, DEFAULT_RULESET, parseRuleset, validateDeck,
+ starterDeck, previewPool, type MatchState, type Action, type GameCard } from '../shared/game/index.ts';
+```
+
+## 1. Lifecycle
+
+```ts
+let state = createMatch(DEFAULT_RULESET, [deck0, deck1], seed); // turn 1, planning
+while (!isOver(state)) {
+ // Each seat (in any order, any interleaving) queues plays, then commits.
+ const actions = legalActions(state, seat); // play / undo / commit
+ state = applyAction(state, chosen); // returns a NEW state
+ // When both seats have committed, the turn resolves inside applyAction.
+}
+const r = result(state); // { winner: 0 | 1 | null, reason, topicsLed, lanePower, totalPower, turns }
+```
+
+| Function | Description |
+|---|---|
+| `createMatch(ruleset, [deck0, deck1], seed: number \| string): MatchState` | Validates the ruleset (`parseRuleset`) and both decks (`validateDeck`), then performs DESIGN §4 setup and turn-1 start. A `seed` is a uint32. A string is hashed with FNV-1a (`seedFromString`). Throws `ZodError` for a bad ruleset and `IllegalActionError` for a bad deck. |
+| `legalActions(state, seat): Action[]` | Lists every `play` (each card × each lane it can legally go into), every `undo`, and `commit`. Returns `[]` once the seat has committed or the match is over. It never lists `concede` (always legal while the match is running) or `timeout` (host only). |
+| `applyAction(state, action): MatchState` | Pure: the input is never mutated. Throws `IllegalActionError` if the action is illegal. |
+| `actionProblem(state, action): string \| null` | Explains why an action is illegal, without throwing. Use it for UI hints and for validating client input on a host. |
+| `isOver(state)` / `result(state)` | `result` is `null` while the match is running. |
+| `viewFor(state, seat): PlayerView` | The **hidden-information view**. Send only this to clients and AIs, never `MatchState`, because a `MatchState` contains both deck orders and the RNG state. |
+| `serialize(state): string` / `deserialize(json): MatchState` | Lossless JSON. `MatchState` is plain data. |
+| `replay(ruleset, decks, seed, actions): MatchState` | Rebuilds a match from its inputs. `state.actions` records every action applied, so a host can store `(ruleset, decks, seed, actions)` and verify a result later. |
+| `validateDeck(ruleset, cards): string[]` | Returns the list of problems; empty means the deck is legal. |
+| `cardPower(state, cardInPlay)`, `lanePower(state, lane)`, `laneLeader(state, lane)`, `topicsLed(state)` | Power queries (DESIGN §6). `laneLeader` and `topicsLed` apply the consensus tie-break. |
+| `scoringPower(state, lane)` | Lane power plus revealed "at scoring" Portals (§7). `result().lanePower` uses this. |
+| `laneCapacity(state, lane)` | Per-seat capacity of a lane. A Portal such as Stub may override it. |
+| `isOnTopic(state, cardInPlay)` | §1.4/§6 on-topic test, including Disambiguation. |
+| `starterDeck(seed): GameCard[]` | A 12-card loaner deck (DESIGN §2). **Placeholder** cards until starter-cards.json lands. |
+| `previewPool(): GameCard[]` | Every loaner card once. For draft modes. |
+| `placeCard(state, seat, lane, card)`, `revealPortal(state, lane)` | Test helpers for building boards by hand. |
+
+## 2. Actions
+
+```ts
+type Action =
+ | { type: 'play'; player: 0 | 1; cardId: string; lane: number } // queue a card from hand (hidden)
+ | { type: 'undo'; player: 0 | 1; cardId: string } // un-queue it (refunds energy)
+ | { type: 'commit'; player: 0 | 1 } // lock in this turn (empty = pass)
+ | { type: 'timeout'; player: 0 | 1 } // HOST ONLY: turn timer expired
+ | { type: 'concede'; player: 0 | 1 };
+```
+
+**Queuing a play**
+- `play` reserves the card's cost from this turn's energy. It checks the energy, the lane's room (cards already in the lane plus queued plays must stay under `laneCapacity(state, lane)`), and, once the Portal is revealed, whether it accepts the card (`canPlay`).
+- Your plays reveal in **your queue order**, interleaved with the opponent's (see below).
+- `undo` and new plays are allowed until the seat sends `commit`.
+
+**Resolving a turn**
+- When both seats have committed, `applyAction` resolves the turn (DESIGN §5.4–5.5):
+ 1. Carry is set: min(`energyCarryMax`, energy not reserved by queued plays). Energy spent on a play that later fizzles is still spent.
+ 2. **Interleaved reveal:** the initiative seat's 1st play, then the other seat's 1st, then the initiative seat's 2nd, and so on. When one seat runs out, the other's remaining plays reveal in order. Each card gets the next global `seq` number, and its on-reveal effects (keyword, then Portal) run at once.
+ 3. End-of-turn effects run: the initiative seat's cards first, then lanes left→right, then `seq` order.
+ 4. On the last turn, scoring follows (§7). Otherwise the next turn starts:
+ - initiative **alternates**
+ - any Portal scheduled by `portalReveal` is revealed
+ - energy = `energyByTurn[t-1]` + carry + `bonusEnergy`
+ - each seat draws
+ - the underdog bonus applies (only if `underdog` is on)
+- **A play that is illegal at reveal** (the lane filled up, or a Portal rejects the card) fizzles. The card stays in hand and its energy is lost. A `fizzle` log event records it.
+
+**Timeouts.** `timeout` is how a host enforces `turnSeconds`. It commits whatever is queued. A timeout with an empty queue counts toward `afkTurns`. When that count is reached, the seat concedes and the result has `reason: 'afk'`. An ordinary `commit` resets the count.
+
+**Seat ownership.** The engine does not authenticate anyone. The host must check that the seat in `action.player` is the caller's.
+
+## 3. Cards
+
+```ts
+interface GameCard {
+ cardId: string; // unique within a deck: the NFT card hash, or `loaner::`
+ pageId: number; // at most ruleset.maxCopiesPerPage cards share a pageId
+ title: string;
+ faction: 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
+ rarity: 'Common' | 'Rare' | 'Epic' | 'Legendary'; // cosmetic in v1
+ cost: number; // 0–6 (uncheckedCostCap already applied by derivation)
+ power: number; // 0–30, base power
+ home: 'attention' | 'depth' | 'reach';
+ trend: -1 | 0 | 1; // frozen at match start
+ keyword: string | null; // an id in KEYWORDS
+ source: 'owned' | 'loaner';
+ check?: 'verified' | 'unverified' | 'unchecked' | 'loaner'; // host plausibility result (§1.10), for logs
+}
+```
+
+- **The engine takes already-derived cards and never reads raw stats.** The council asked for this, because snapshot stats are self-reported (#1, critic brief A.1).
+- Derivation (DESIGN §1 and §10.1: percentile → fame → cost → power, home, trend, keyword and vanillaBonus) lives in `shared/game/derive.ts`, which engine-b owns. Hosts run it on host-frozen, plausibility-checked inputs before calling `createMatch`.
+- Modes may adjust `GameCard` fields such as `power` before `createMatch`. The engine does not re-derive them.
+- A keyword that isn't in `ruleset.keywordsEnabled` never runs. Derivation is responsible for not giving that card `vanillaBonus`.
+- Lane power = `power` + `bonus` + `trend` + `onTopicBonus[cost]` if on-topic + ongoing keyword and Portal effects, floored at 0.
+
+## 4. Ruleset
+
+`Ruleset` holds the DESIGN §9 keys, **flat** (nothing deeper than one level, apart from `topicPool` entries and the param tables).
+- `parseRuleset(unknown)` is a **strict** zod parse: unknown keys are rejected and every number is bounded, so any ruleset that passes terminates within `turns` turns.
+- Modes merge overrides onto `DEFAULT_RULESET` and then call `parseRuleset`.
+
+Notes on the §9 keys:
+- `topicPool` is inline `TopicDef[] = { id, name, stat, portal: PortalId | null }[]`. `DEFAULT_TOPIC_POOL` is the 9 Topics of §10.3. A Portal id is one of `PORTAL_IDS` (`main-page, trending, featured-article, stub, interwiki, disambiguation`).
+- `keywordParams[keywordId]` holds keyword numbers; keys must be in `KEYWORD_IDS`. `portalParams[topicId]` holds Portal numbers, and falls back to `portalParams[portalId]`, so a mode can add a Topic that reuses a Portal kind with new numbers.
+- `keywordsEnabled` ⊆ `KEYWORD_IDS` (the 6 v1 ids plus `edition`, `obscure` and `wildcard`).
+- `mulligan` must be `false`. Mulligans are not implemented in v1.
+- `percentiles`, `starterDecks`, `trendUp/Down`, `trendMinDaily`, `uncheckedCostCap`, `vanillaBonus`, `costThresholds`, `powerByCost`, `verifyStats` and `factionSynergyCap` are for derivation and the host. The core loop doesn't read them.
+
+Validation also enforces:
+- `turns × turnSeconds ≤ 240`
+- `energyByTurn.length ≥ turns`
+- `portalReveal.length = topicCount`
+- `openingHand ≤ handLimit`
+- `costThresholds` in ascending order
+- with `distinctStats`, `topicCount == 3` and the pool has all 3 stats
+- the ranges in DESIGN §11 are **stricter** and are enforced by modes (`shared/game/modes.ts`). The engine's bounds only guarantee safety and termination.
+
+## 5. Determinism and the RNG
+
+- The RNG is **mulberry32(seed: uint32)**, as in DESIGN §4. Its state is a single uint32 in `state.rng`.
+- Draw order:
+ 1. p0's deck is shuffled.
+ 2. p1's deck is shuffled.
+ 3. **The Topics are drawn.** With `distinctStats`: for each stat in the order `attention, depth, reach`, take `group[floor(next() × group.length)]`, where `group` is that stat's Topics in `topicPool` order. Then the picks are shuffled, and that is the lane order. Without `distinctStats`: the whole pool is shuffled and the first `topicCount` are taken.
+ 4. The initiative coin is flipped: p0 has initiative on turn 1 (and every odd turn) if `next() < 0.5`; otherwise p1 does. After that, initiative strictly alternates.
+ 5. Keyword and Portal hooks draw in resolution order.
+- Shuffles are Fisher–Yates with `i` from n−1 down to 1 and `j = floor(next() × (i+1))`.
+- `ongoing` power hooks get a throwaway RNG copy, so computing power never changes the match RNG.
+
+## 6. State and views
+
+The full `MatchState` (plain JSON) is for the **host only**:
+
+```ts
+interface MatchState {
+ schema: 'wikideck-match/1'; engineVersion: number; ruleset: Ruleset; seed: number; rng: number;
+ turn: number /* 1-based */; phase: 'planning' | 'over'; initiative: 0 | 1;
+ players: [PlayerState, PlayerState]; // deck, hand, energy, queue, committed, afk
+ lanes: { topic: TopicDef; portalRevealed: boolean; cards: [CardInPlay[], CardInPlay[]] }[];
+ revealSeq: number; log: LogEvent[]; actions: Action[]; result: MatchResult | null;
+}
+interface PlayerState { deck; hand; energy; queue: { cardId; lane }[]; committed; afk; carry }
+interface CardInPlay { card: GameCard; owner: 0 | 1; lane: number; turn: number; seq: number; bonus: number }
+```
+
+`PlayerView`, returned by `viewFor(state, seat)`, is what a seat may see. In it, "you" is always index 0 and the opponent is index 1:
+
+```ts
+interface PlayerView {
+ you: 0 | 1; ruleset; turn; phase; initiative;
+ energy: number; energyLeft: number; hand: GameCard[]; queue: { cardId; lane }[]; committed; deckCount;
+ opponent: { handCount; deckCount; queuedCount; committed }; // never their cards or queue
+ lanes: { topic: TopicDef /* stat always; id/name/portal masked until portalRevealed */, portalRevealed, cards: [mine, theirs],
+ cardPower: [number[], number[]], power: [mine, theirs], leader: 'you' | 'opponent' | null }[];
+ result: MatchResult | null;
+}
+```
+
+`state.log` is an append-only event list for animation and replays. Event types: `turnStart`, `portalRevealed`, `underdog`, `draw`, `reveal`, `fizzle`, `effect`, `concede` and `matchOver`. It contains both seats' draws, so a host must filter it per seat before sending it.
+
+## 7. Results
+
+```ts
+interface MatchResult {
+ winner: 0 | 1 | null; // null = draw
+ reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk';
+ topicsLed: [number, number]; lanePower: [number, number][]; totalPower: [number, number]; turns: number;
+}
+```
+
+Scoring runs after the last turn's End phase. Lane powers include revealed "at scoring" Portals, and each lane's leader uses the consensus tie-break (§6). Winner, per DESIGN §7:
+1. The seat that leads more Topics.
+2. If tied on Topics, the seat with more total power.
+3. If that is also tied, a draw.
+
+## 8. Keywords and Portals (extension contract)
+
+`KEYWORDS` and `PORTALS` in `shared/game/keywords.ts` (engine-b) are registries of hook objects. The header of that file is normative. Every hook gets `ctx = { state, rng, params, lane, log, power(card) }`.
+
+**Keywords**
+- `onReveal(ctx, self)` and `endOfTurn(ctx, self)` may change `bonus` on cards in `ctx.state`.
+- `ongoing(ctx, self, target) → number` must be **pure**, and must not call `ctx.power`.
+- Keyword hooks run only if the keyword is in `keywordsEnabled`.
+
+**Portals** have the same hooks, plus:
+- `onPortalReveal(ctx)`
+- `canPlay(ctx, card, seat) → boolean`, checked when a play is queued and again at reveal
+- `capacity(ctx) → number`
+- `allOnTopic: true`
+- `atScoring(ctx) → [delta0, delta1]`
+
+Portal hooks act only once the Portal is revealed.
+
+**Rules for all hooks**
+- Hooks must not move or remove cards (DESIGN §10).
+- Any randomness must come from `ctx.rng`. No v1 keyword uses it.
+
+## 9. Testing
+
+- `tests/game-core.test.ts` (engine-a) covers the core loop:
+ - the RNG reference value, ruleset bounds and setup
+ - hidden information and hidden Portals
+ - energy carry, interleaved reveal and alternating initiative
+ - on-topic power, the consensus tie-break, and Portal capacity, fizzle and at-scoring hooks
+ - disabled keywords, AFK and concede, and draws
+ - the random-play property: matches terminate, replay exactly, and serialise after every action
+- `tests/game-*.test.ts` (engine-b): keywords, card derivation, property tests and the DESIGN §12 golden match.
diff --git a/shared/game/engine.ts b/shared/game/engine.ts
index ae4466d..b5c7476 100644
--- a/shared/game/engine.ts
+++ b/shared/game/engine.ts
@@ -4,7 +4,7 @@
* All randomness comes from the match seed via state.rng (mulberry32, §4).
* Contract: docs/game/ENGINE_API.md.
*/
-import { KEYWORDS, PORTALS, type EffectContext } from './keywords.ts';
+import { KEYWORDS, KEYWORD_IDS, activePortal, isOnTopic, type EffectContext, type KeywordDef, type PortalDef } from './keywords.ts';
import { Rng, normalizeSeed } from './rng.ts';
import { parseRuleset } from './ruleset.ts';
import {
@@ -19,6 +19,7 @@ export const other = (player: PlayerId): PlayerId => (player === 0 ? 1 : 0);
const clone = (value: T): T => structuredClone(value);
const RARITIES = new Set(['Common', 'Rare', 'Epic', 'Legendary']);
const FACTION_SET = new Set(['Space', 'Nature', 'People', 'Science', 'History', 'Culture']);
+const CHECKS = new Set(['verified', 'unverified', 'unchecked', 'loaner']);
// ---------- validation ----------
@@ -43,9 +44,11 @@ export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[
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.keyword !== null && !(KEYWORD_IDS as readonly string[]).includes(card.keyword)) problems.push(`${label}: unknown keyword ${card.keyword}`);
if (card.source !== 'owned' && card.source !== 'loaner') problems.push(`${label}: bad source`);
+ if (card.check !== undefined && !CHECKS.has(card.check)) problems.push(`${label}: bad check`);
if (card.source === 'loaner') loaners++;
+ if (card.source === 'owned' && !rules.ownedCards) problems.push(`${label}: owned cards are not allowed in this mode`);
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}`);
@@ -85,7 +88,7 @@ export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard
}
const rng = new Rng(seedValue);
const newPlayer = (player: PlayerId): PlayerState => ({
- deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, queue: [], committed: false, afk: 0,
+ deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, queue: [], committed: false, afk: 0, carry: 0,
});
const p0 = newPlayer(0);
const p1 = newPlayer(1);
@@ -93,8 +96,8 @@ export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard
const initiative: PlayerId = rng.next() < 0.5 ? 0 : 1;
const state: MatchState = {
schema: 'wikideck-match/1', engineVersion: ENGINE_VERSION, ruleset: rules, seed: seedValue, rng: rng.state,
- turn: 0, phase: 'planning', initiative, players: [p0, p1],
- lanes: topics.map(topic => ({ topic: clone(topic), revealed: false, cards: [[], []] as [CardInPlay[], CardInPlay[]] })),
+ turn: 0, phase: 'planning', initiative, revealSeq: 0, players: [p0, p1],
+ lanes: topics.map(topic => ({ topic: clone(topic), portalRevealed: false, cards: [[], []] as [CardInPlay[], CardInPlay[]] })),
log: [], actions: [], result: null,
};
for (const player of PLAYERS) for (let i = 0; i < rules.openingHand; i++) draw(state, player);
@@ -112,27 +115,51 @@ function draw(state: MatchState, player: PlayerId): void {
}
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 }) };
+ return {
+ state, rng, params: params ?? {}, lane,
+ log: text => state.log.push({ t: 'effect', source, player, text }),
+ power: card => cardPower(state, card),
+ };
}
-function portalOf(state: MatchState, lane: number) {
- const l = state.lanes[lane];
- return l?.revealed && l.topic.portal ? PORTALS[l.topic.portal] : undefined;
+/** Enabled keyword definition for a card, if any. */
+function keywordOf(state: MatchState, card: GameCard): KeywordDef | undefined {
+ return card.keyword && state.ruleset.keywordsEnabled.includes(card.keyword) ? KEYWORDS[card.keyword] : undefined;
}
-/** §5.1 Start, then §5.2 Underdog. */
+function keywordCtx(state: MatchState, rng: Rng, keyword: KeywordDef, card: CardInPlay): EffectContext {
+ return context(state, rng, state.ruleset.keywordParams[keyword.id], card.lane, keyword.id, card.owner);
+}
+
+function portalCtx(state: MatchState, rng: Rng, lane: number, portal: PortalDef, player: PlayerId): EffectContext {
+ const topic = state.lanes[lane].topic;
+ const params = state.ruleset.portalParams[topic.id] ?? state.ruleset.portalParams[portal.id];
+ return context(state, rng, params, lane, portal.id, player);
+}
+
+/** Per-seat card capacity of a lane (a Portal may override it, e.g. Stub). */
+export function laneCapacity(state: MatchState, lane: number): number {
+ const portal = activePortal(state, lane);
+ return portal?.capacity ? portal.capacity(portalCtx(state, new Rng(state.rng), lane, portal, state.initiative)) : state.ruleset.laneCapacity;
+}
+
+/** §5.1 Start (Portal reveal, energy, draw), then §5.2 Underdog. Initiative alternates (§5.5). */
function startTurn(state: MatchState, rng: Rng): void {
state.turn += 1;
+ if (state.turn > 1) state.initiative = other(state.initiative);
const rules = state.ruleset;
state.lanes.forEach((lane, index) => {
- if (lane.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));
+ if (lane.portalRevealed || (rules.portalReveal[index] ?? 1) > state.turn) return;
+ lane.portalRevealed = true;
+ state.log.push({ t: 'portalRevealed', lane: index, topic: clone(lane.topic) });
+ const portal = activePortal(state, index);
+ portal?.onPortalReveal?.(portalCtx(state, rng, index, portal, state.initiative));
});
const base = (rules.energyByTurn[state.turn - 1] ?? rules.energyByTurn.at(-1)!) + rules.bonusEnergy;
- for (const player of PLAYERS) Object.assign(state.players[player], { energy: base, queue: [], committed: false });
+ for (const player of PLAYERS) {
+ const p = state.players[player];
+ Object.assign(p, { energy: base + p.carry, queue: [], committed: false });
+ }
for (const player of PLAYERS) draw(state, player);
if (rules.underdog && state.turn >= 2) {
const led = topicsLed(state);
@@ -146,47 +173,63 @@ function startTurn(state: MatchState, rng: Rng): void {
// ---------- power (§6) ----------
-/** A card's current lane power (never below 0). */
+/** A card's current lane power (§6, never below 0). */
export function cardPower(state: MatchState, target: CardInPlay): number {
const rules = state.ruleset;
- const lane = state.lanes[target.lane];
const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness
let power = target.card.power + target.bonus + target.card.trend;
- if (lane.revealed && lane.topic.stat === target.card.home) power += rules.onTopicBonus;
- for (const l of state.lanes) for (const side of l.cards) for (const source of side) {
- const keyword = source.card.keyword ? KEYWORDS[source.card.keyword] : undefined;
- if (keyword?.ongoing) power += keyword.ongoing(context(state, scratch, rules.keywordParams[keyword.id], source.lane, keyword.id, source.owner), source, target);
+ if (isOnTopic(state, target)) power += rules.onTopicBonus[target.card.cost] ?? 0;
+ for (const lane of state.lanes) for (const side of lane.cards) for (const source of side) {
+ const keyword = keywordOf(state, source.card);
+ if (keyword?.ongoing) power += keyword.ongoing(keywordCtx(state, scratch, keyword, source), source, target);
}
- const portal = portalOf(state, target.lane);
- if (portal?.ongoing) power += portal.ongoing(context(state, scratch, rules.portalParams[portal.id], target.lane, portal.id, target.owner), target);
+ const portal = activePortal(state, target.lane);
+ if (portal?.ongoing) power += portal.ongoing(portalCtx(state, scratch, target.lane, portal, target.owner), target);
return Math.max(0, power);
}
-/** [seat 0 power, seat 1 power] in one lane. */
+/** [seat 0 power, seat 1 power] in one lane (during play; excludes "at scoring" Portals). */
export function lanePower(state: MatchState, lane: number): [number, number] {
return PLAYERS.map(player => state.lanes[lane].cards[player].reduce((sum, card) => sum + cardPower(state, card), 0)) as [number, number];
}
-/** Number of Topics each seat leads (strictly more power). */
+/** §6: who leads a lane given its powers. Equal and > 0 → more on-topic cards leads (consensus). */
+export function laneLeader(state: MatchState, lane: number, power: [number, number] = lanePower(state, lane)): PlayerId | null {
+ const [a, b] = power;
+ if (a !== b) return a > b ? 0 : 1;
+ if (a === 0) return null;
+ const onTopic = PLAYERS.map(player => state.lanes[lane].cards[player].filter(card => isOnTopic(state, card)).length);
+ return onTopic[0] === onTopic[1] ? null : onTopic[0] > onTopic[1] ? 0 : 1;
+}
+
+/** Number of Topics each seat leads right now (with the consensus tie-break). */
export function topicsLed(state: MatchState): [number, number] {
const led: [number, number] = [0, 0];
state.lanes.forEach((_, lane) => {
- const [a, b] = lanePower(state, lane);
- if (a > b) led[0]++; else if (b > a) led[1]++;
+ const leader = laneLeader(state, lane);
+ if (leader !== null) led[leader]++;
});
return led;
}
+/** Final lane powers: lanePower plus revealed "at scoring" Portals (§7, §10.3). */
+export function scoringPower(state: MatchState, lane: number): [number, number] {
+ const power = lanePower(state, lane);
+ const portal = activePortal(state, lane);
+ if (!portal?.atScoring) return power;
+ const [d0, d1] = portal.atScoring(portalCtx(state, new Rng(state.rng), lane, portal, state.initiative));
+ return [power[0] + d0, power[1] + d1];
+}
+
// ---------- actions (§5.3) ----------
const queuedCost = (p: PlayerState) => p.queue.reduce((sum, play) => sum + (p.hand.find(c => c.cardId === play.cardId)?.cost ?? 0), 0);
const queuedInLane = (p: PlayerState, lane: number) => p.queue.filter(play => play.lane === lane).length;
function laneRejects(state: MatchState, lane: number, card: GameCard, player: PlayerId): string | null {
- const portal = portalOf(state, lane);
+ const portal = activePortal(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`;
+ return portal.canPlay(portalCtx(state, new Rng(state.rng), lane, portal, player), card, player) ? null : `${portal.name} rejects this card`;
}
function playProblem(state: MatchState, action: Extract): string | null {
@@ -197,7 +240,7 @@ function playProblem(state: MatchState, action: Extract play.cardId === action.cardId)) return 'Card is already queued';
if (!Number.isInteger(action.lane) || action.lane < 0 || action.lane >= state.lanes.length) return 'No such Topic';
if (card.cost > p.energy - queuedCost(p)) return 'Not enough energy';
- if (state.lanes[action.lane].cards[action.player].length + queuedInLane(p, action.lane) >= state.ruleset.laneCapacity) return 'Topic is full';
+ if (state.lanes[action.lane].cards[action.player].length + queuedInLane(p, action.lane) >= laneCapacity(state, action.lane)) return 'Topic is full';
return laneRejects(state, action.lane, card, action.player);
}
@@ -271,54 +314,69 @@ export function applyAction(state: MatchState, action: Action): MatchState {
return next;
}
-/** §5.4 Reveal and §5.5 End. */
+/** §5.4 Reveal (interleaved) and §5.5 End. */
function resolveTurn(state: MatchState, rng: Rng): void {
const rules = state.ruleset;
const order: PlayerId[] = [state.initiative, other(state.initiative)];
- for (const player of order) {
+ // Carry (§5.1): energy not reserved by a queued play. Fizzled plays still spent theirs.
+ for (const player of PLAYERS) {
const p = state.players[player];
- for (const play of p.queue) {
- const index = p.hand.findIndex(c => c.cardId === play.cardId);
- const card = p.hand[index];
- if (index < 0 || state.lanes[play.lane].cards[player].length >= rules.laneCapacity || laneRejects(state, play.lane, card, player)) {
- state.log.push({ t: 'fizzle', player, cardId: play.cardId, lane: play.lane }); // stays in hand, energy lost
- continue;
- }
- p.hand.splice(index, 1);
- const inPlay: CardInPlay = { card, owner: player, lane: play.lane, turn: state.turn, bonus: 0 };
- state.lanes[play.lane].cards[player].push(inPlay);
- state.log.push({ t: 'reveal', player, cardId: card.cardId, lane: play.lane });
- const keyword = card.keyword ? KEYWORDS[card.keyword] : undefined;
- keyword?.onReveal?.(context(state, rng, rules.keywordParams[keyword.id], play.lane, keyword.id, player), inPlay);
- const portal = portalOf(state, play.lane);
- portal?.onReveal?.(context(state, rng, rules.portalParams[portal.id], play.lane, portal.id, player), inPlay);
+ p.carry = Math.min(rules.energyCarryMax, Math.max(0, p.energy - queuedCost(p)));
+ }
+ const queues = order.map(player => state.players[player].queue.slice());
+ for (let i = 0; i < Math.max(queues[0].length, queues[1].length); i++) {
+ for (const [k, player] of order.entries()) {
+ const play = queues[k][i];
+ if (play) reveal(state, rng, player, play.cardId, play.lane);
}
- p.queue = [];
}
- for (const player of order) for (const lane of state.lanes) for (const card of lane.cards[player].slice()) {
- const keyword = card.card.keyword ? KEYWORDS[card.card.keyword] : undefined;
- keyword?.endOfTurn?.(context(state, rng, rules.keywordParams[keyword.id], card.lane, keyword.id, player), card);
+ for (const player of PLAYERS) state.players[player].queue = [];
+ for (const player of order) for (const lane of state.lanes) {
+ for (const card of lane.cards[player].slice().sort((x, y) => x.seq - y.seq)) {
+ const keyword = keywordOf(state, card.card);
+ keyword?.endOfTurn?.(keywordCtx(state, rng, keyword, card), card);
+ }
}
- if (state.turn >= rules.turns) { finish(state, null, 'topics'); return; }
- const led = topicsLed(state);
- state.initiative = led[0] !== led[1] ? (led[0] > led[1] ? 0 : 1) : other(state.initiative);
- startTurn(state, rng);
+ if (state.turn >= rules.turns) finish(state, null, 'topics');
+ else startTurn(state, rng);
}
-/** §7. */
+function reveal(state: MatchState, rng: Rng, player: PlayerId, cardId: string, lane: number): void {
+ const p = state.players[player];
+ const index = p.hand.findIndex(c => c.cardId === cardId);
+ const card = p.hand[index];
+ if (index < 0 || state.lanes[lane].cards[player].length >= laneCapacity(state, lane) || laneRejects(state, lane, card, player)) {
+ state.log.push({ t: 'fizzle', player, cardId, lane }); // stays in hand, energy lost
+ return;
+ }
+ p.hand.splice(index, 1);
+ const inPlay: CardInPlay = { card, owner: player, lane, turn: state.turn, seq: ++state.revealSeq, bonus: 0 };
+ state.lanes[lane].cards[player].push(inPlay);
+ state.log.push({ t: 'reveal', player, cardId, lane });
+ const keyword = keywordOf(state, card);
+ keyword?.onReveal?.(keywordCtx(state, rng, keyword, inPlay), inPlay);
+ const portal = activePortal(state, lane);
+ portal?.onReveal?.(portalCtx(state, rng, lane, portal, player), inPlay);
+}
+
+/** §7 scoring (after the last End phase, with "at scoring" Portals), or a concede. */
function finish(state: MatchState, forcedWinner: PlayerId | null, reason: 'topics' | 'concede' | 'afk'): void {
- const lanePowers = state.lanes.map((_, lane) => lanePower(state, lane));
- const topicsLedNow = topicsLed(state);
+ const lanePowers = state.lanes.map((_, lane) => scoringPower(state, lane));
+ const led: [number, number] = [0, 0];
const totalPower: [number, number] = [0, 0];
- for (const [a, b] of lanePowers) { totalPower[0] += a; totalPower[1] += b; }
+ lanePowers.forEach((power, lane) => {
+ const leader = laneLeader(state, lane, power);
+ if (leader !== null) led[leader]++;
+ totalPower[0] += power[0]; totalPower[1] += power[1];
+ });
let winner: PlayerId | null = forcedWinner;
let why: MatchResult['reason'] = reason;
if (reason === 'topics') {
- if (topicsLedNow[0] !== topicsLedNow[1]) winner = topicsLedNow[0] > topicsLedNow[1] ? 0 : 1;
+ if (led[0] !== led[1]) winner = led[0] > led[1] ? 0 : 1;
else if (totalPower[0] !== totalPower[1]) { winner = totalPower[0] > totalPower[1] ? 0 : 1; why = 'totalPower'; }
else why = 'draw';
}
- state.result = { winner, reason: why, topicsLed: topicsLedNow, lanePower: lanePowers, totalPower, turns: state.turn };
+ state.result = { winner, reason: why, topicsLed: led, lanePower: lanePowers, totalPower, turns: state.turn };
state.phase = 'over';
state.log.push({ t: 'matchOver', result: clone(state.result) });
}
@@ -342,12 +400,15 @@ export function viewFor(state: MatchState, you: PlayerId): PlayerView {
lanes: state.lanes.map((lane, index) => {
const power = lanePower(state, index);
const mine = power[you], theirs = power[them];
+ const leader = laneLeader(state, index, power);
return {
- topic: lane.revealed ? lane.topic : null,
+ // Until its Portal is revealed only the stat is visible (the id/name would give the Portal away).
+ topic: lane.portalRevealed ? lane.topic : { id: `lane-${index + 1}`, name: '?', stat: lane.topic.stat, portal: null },
+ portalRevealed: lane.portalRevealed,
cards: [lane.cards[you], lane.cards[them]] as [CardInPlay[], CardInPlay[]],
cardPower: [lane.cards[you].map(c => cardPower(state, c)), lane.cards[them].map(c => cardPower(state, c))] as [number[], number[]],
power: [mine, theirs] as [number, number],
- leader: mine > theirs ? 'you' as const : theirs > mine ? 'opponent' as const : null,
+ leader: leader === null ? null : leader === you ? 'you' as const : 'opponent' as const,
};
}),
result: state.result,
@@ -378,13 +439,13 @@ export function replay(ruleset: Ruleset, decks: readonly [readonly GameCard[], r
*/
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 });
+ next.lanes[lane].cards[player].push({ card: clone(card), owner: player, lane, turn: next.turn, seq: ++next.revealSeq, bonus });
return next;
}
-/** Test helper: flip a Topic face-up (runs nothing). */
-export function revealTopic(state: MatchState, lane: number): MatchState {
+/** Test helper: reveal a Topic's Portal now (runs nothing). */
+export function revealPortal(state: MatchState, lane: number): MatchState {
const next = clone(state);
- next.lanes[lane].revealed = true;
+ next.lanes[lane].portalRevealed = true;
return next;
}
diff --git a/shared/game/index.ts b/shared/game/index.ts
index b21d049..14f7703 100644
--- a/shared/game/index.ts
+++ b/shared/game/index.ts
@@ -4,7 +4,7 @@ export { Rng, seedFromString, normalizeSeed, type RngState } from './rng.ts';
export { DEFAULT_RULESET, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
export {
ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor,
- serialize, deserialize, replay, validateDeck, cardPower, lanePower, topicsLed, other, placeCard, revealTopic,
+ serialize, deserialize, replay, validateDeck, cardPower, lanePower, laneLeader, laneCapacity, scoringPower, topicsLed, other, placeCard, revealPortal,
} from './engine.ts';
-export { KEYWORDS, PORTALS, allies, type KeywordDef, type PortalDef, type EffectContext } from './keywords.ts';
+export { KEYWORDS, PORTALS, KEYWORD_IDS, PORTAL_IDS, allies, activePortal, isOnTopic, type KeywordDef, type PortalDef, type EffectContext } from './keywords.ts';
export { STARTER_POOL, loanerCard, previewPool, starterDeck } from './starter.ts';
diff --git a/shared/game/keywords.ts b/shared/game/keywords.ts
index d10d6c8..ea3a621 100644
--- a/shared/game/keywords.ts
+++ b/shared/game/keywords.ts
@@ -1,33 +1,46 @@
/**
- * Keyword and Portal registry (DESIGN §10, §10.3). Effects are code here; which
+ * Keyword and Portal registry (DESIGN §10.2, §10.3). Effects are code here; which
* ones a card/topic uses and their numbers are data (GameCard.keyword,
- * TopicDef.portal, Ruleset.keywordParams / portalParams).
+ * TopicDef.portal, Ruleset.keywordsEnabled / keywordParams / portalParams).
* Owner of the effects: engine-b (claude/wikideck#3). engine-a owns the hook contract:
*
* - Hooks get an EffectContext over the engine's *working copy* of the state and may
- * mutate it (e.g. `bonus` on cards). Mutating is safe: applyAction already cloned.
- * Any randomness must come from ctx.rng (the match RNG, in resolution order, §4.2.5).
- * - onReveal: once, right after the card enters its lane (§5.4).
- * - endOfTurn: every card in play, at §5.5, initiative player's cards first, lanes left→right,
- * in play order.
- * - ongoing: PURE. Returns a power delta for `target` while `self` is in play. Called for every
- * (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).
+ * mutate it (e.g. `bonus` on cards). Safe: applyAction already cloned.
+ * Any randomness must come from ctx.rng (match RNG, resolution order, §4.2.5).
+ * - A keyword's hooks run only if its id is in ruleset.keywordsEnabled.
+ * - onReveal(ctx, self): right after `self` is pushed into its lane (§5.4). Cards revealed
+ * earlier (any seat, any turn) are on the board; later ones are not. self.seq is its global
+ * reveal number; cards revealed this turn have `turn === ctx.state.turn`.
+ * - endOfTurn(ctx, self): §5.5 order: initiative seat's cards first, then lanes 1→N, then seq.
+ * Also runs on the last turn, before scoring (§7).
+ * - ongoing(ctx, self, target) → delta: PURE. Called for every (self, target) pair in play,
+ * including self === target. ctx.rng is a throwaway copy. Don't call ctx.power on a card from
+ * inside ongoing (infinite recursion); read base fields instead.
+ * - Portals: same, plus onPortalReveal(ctx), canPlay(ctx, card, seat), capacity(ctx) → number
+ * (lane capacity override), allOnTopic (Disambiguation) and atScoring(ctx) → [delta0, delta1]
+ * (Topic power added at scoring, §7). All Portal hooks apply only once the Portal is revealed.
+ * Params: ruleset.portalParams[topic.id], falling back to portalParams[portal id].
+ * - Hooks must not throw and must not move or remove cards (§10, v1).
*/
import type { Rng } from './rng.ts';
import type { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts';
+/** The 9 implemented keyword ids (§10.2; edition, obscure and wildcard are disabled by default). */
+export const KEYWORD_IDS = ['viral', 'rising', 'local', 'encyclopedic', 'nostalgic', 'translated', 'edition', 'obscure', 'wildcard'] as const;
+/** The 6 Portal kinds (§10.3), named after their default Topic. */
+export const PORTAL_IDS = ['main-page', 'trending', 'featured-article', 'stub', 'interwiki', 'disambiguation'] as const;
+
export interface EffectContext {
state: MatchState;
rng: Rng;
- /** Tunable numbers for this keyword/portal from Ruleset.keywordParams / portalParams. */
+ /** Tunable numbers for this keyword/portal from the ruleset. */
params: Record;
/** Lane the effect lives in. */
lane: number;
/** Add a line to the match log (attributed to this keyword/portal). */
log(text: string): void;
+ /** Current lane power of a card in play (the engine's cardPower). Not for use inside `ongoing`. */
+ power(card: CardInPlay): number;
}
export interface KeywordDef {
@@ -44,12 +57,18 @@ export interface PortalDef {
id: string;
name: string;
text: string;
- onTopicReveal?(ctx: EffectContext): void;
+ onPortalReveal?(ctx: EffectContext): void;
/** Runs when any card is revealed in this Topic (after the card's own onReveal). */
onReveal?(ctx: EffectContext, card: CardInPlay): void;
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;
+ /** Per-player lane capacity in this Topic (replaces ruleset.laneCapacity). */
+ capacity?(ctx: EffectContext): number;
+ /** Every card here counts as on-topic. */
+ allOnTopic?: boolean;
+ /** Topic power added to [seat 0, seat 1] here at scoring. */
+ atScoring?(ctx: EffectContext): [number, number];
}
/** Cards on the same side of the same lane, excluding `self`. */
@@ -57,31 +76,20 @@ export function allies(state: MatchState, self: CardInPlay): CardInPlay[] {
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 = {
- rally: {
- id: 'rally', name: 'Rally', text: 'On reveal: +{amount} 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(`${self.card.title}: Rally +${amount}`);
- },
- },
- anchor: {
- id: 'anchor', name: 'Anchor', text: 'Ongoing: +{amount} if alone here.',
- ongoing(ctx, self, target) {
- return target === self && allies(ctx.state, self).length === 0 ? ctx.params.amount ?? 2 : 0;
- },
- },
-};
+/** The lane's Portal, if it has one and it is revealed. */
+export function activePortal(state: MatchState, lane: number): PortalDef | undefined {
+ const l = state.lanes[lane];
+ return l?.portalRevealed && l.topic.portal ? PORTALS[l.topic.portal] : undefined;
+}
-export const PORTALS: Record = {
- spotlight: {
- id: 'spotlight', name: 'Spotlight', text: 'Cards here get +{amount}.',
- ongoing(ctx) { return ctx.params.amount ?? 1; },
- },
- paywall: {
- id: 'paywall', name: 'Paywall', text: 'Only cards costing {maxCost} or less.',
- canPlay(ctx, card) { return card.cost <= (ctx.params.maxCost ?? 3); },
- },
-};
+/** §1.4/§6 on-topic: home stat matches the Topic's stat, or an active Disambiguation-style Portal. */
+export function isOnTopic(state: MatchState, card: CardInPlay): boolean {
+ const lane = state.lanes[card.lane];
+ return lane.topic.stat === card.card.home || activePortal(state, card.lane)?.allOnTopic === true;
+}
+
+/** Filled in by engine-b (§10.2). Ids must be in KEYWORD_IDS. */
+export const KEYWORDS: Record = {};
+
+/** Filled in by engine-b (§10.3). Ids must be in PORTAL_IDS. */
+export const PORTALS: Record = {};
diff --git a/shared/game/ruleset.ts b/shared/game/ruleset.ts
index 59aead6..4f5a57a 100644
--- a/shared/game/ruleset.ts
+++ b/shared/game/ruleset.ts
@@ -5,7 +5,7 @@
* guarantee termination.
*/
import { z } from 'zod';
-import { KEYWORDS, PORTALS } from './keywords.ts';
+import { KEYWORD_IDS, PORTAL_IDS } from './keywords.ts';
import { STATS, type Ruleset } from './types.ts';
const int = (min: number, max: number) => z.number().int().min(min).max(max);
@@ -15,7 +15,7 @@ const params = z.record(z.string().regex(/^[A-Za-z0-9]{1,24}$/), z.number().fini
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(),
+ id, name: z.string().min(1).max(32), stat: z.enum(STATS as [string, ...string[]]), portal: z.enum(PORTAL_IDS).nullable(),
}).strict();
export const RulesetSchema = z.object({
@@ -30,34 +30,40 @@ export const RulesetSchema = z.object({
turnSeconds: int(5, 120),
afkTurns: int(1, 12),
energyByTurn: z.array(int(0, 20)).min(1).max(12),
+ energyCarryMax: int(0, 10),
bonusEnergy: int(0, 10),
underdog: z.boolean(),
topicCount: int(1, 5),
distinctStats: z.boolean(),
- revealSchedule: z.array(int(1, 12)).max(5),
+ portalReveal: z.array(int(1, 12)).max(5),
laneCapacity: int(1, 8),
topicPool: z.array(TopicSchema).min(1).max(32),
+ keywordParams: paramTable,
+ portalParams: paramTable,
costThresholds: z.array(int(0, 100)).length(5),
powerByCost: z.array(int(0, 30)).length(7),
- onTopicBonus: int(0, 10),
+ onTopicBonus: z.array(int(0, 10)).length(7),
+ vanillaBonus: int(0, 10),
+ keywordsEnabled: z.array(z.enum(KEYWORD_IDS)).max(KEYWORD_IDS.length),
+ ownedCards: z.boolean(),
trendUp: z.number().finite().min(-1000).max(1000),
trendDown: z.number().finite().min(-1000).max(1000),
+ trendMinDaily: z.number().finite().min(0).max(1e9),
+ uncheckedCostCap: int(1, 6),
factionSynergyCap: int(0, 12),
verifyStats: z.boolean(),
percentiles: id,
starterDecks: id,
- keywordParams: paramTable,
- portalParams: paramTable,
}).strict().superRefine((rules, ctx) => {
const issue = (message: string) => ctx.addIssue({ code: 'custom', message });
if (rules.turns * rules.turnSeconds > 240) issue('turns × turnSeconds must be ≤ 240');
if (rules.energyByTurn.length < rules.turns) issue('energyByTurn needs one entry per turn');
- if (rules.revealSchedule.length !== rules.topicCount) issue('revealSchedule needs one entry per Topic');
+ if (rules.portalReveal.length !== rules.topicCount) issue('portalReveal needs one entry per Topic');
if (rules.openingHand > rules.handLimit) issue('openingHand > handLimit');
if (rules.trendDown > rules.trendUp) issue('trendDown > trendUp');
if (rules.costThresholds.some((value, i) => i > 0 && value < rules.costThresholds[i - 1])) issue('costThresholds must ascend');
if (rules.distinctStats) {
- if (rules.topicCount > STATS.length) issue('distinctStats allows at most 3 Topics');
+ if (rules.topicCount !== STATS.length) issue('distinctStats needs topicCount == 3');
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');
@@ -65,10 +71,11 @@ export const RulesetSchema = z.object({
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}`);
+ if (new Set(rules.keywordsEnabled).size !== rules.keywordsEnabled.length) issue('Duplicate keywordsEnabled entry');
+ for (const key of Object.keys(rules.keywordParams)) if (!(KEYWORD_IDS as readonly string[]).includes(key)) issue(`Unknown keyword: ${key}`);
+ for (const key of Object.keys(rules.portalParams))
+ if (!topicIds.has(key) && !(PORTAL_IDS as readonly string[]).includes(key)) issue(`portalParams key is neither a Topic id nor a Portal id: ${key}`);
});
/** Validate untrusted ruleset JSON. Throws a ZodError with readable issues. */
@@ -76,36 +83,45 @@ export function parseRuleset(input: unknown): Ruleset {
return RulesetSchema.parse(input) as Ruleset;
}
-/** DESIGN §3: 9 Topics, each stat 3 times: one plain and two with Portals (portals are placeholders until §10.3). */
+/** DESIGN §10.3 default Topic pool: per stat one plain Topic and two with Portals. Portal kind = Topic id. */
export const DEFAULT_TOPIC_POOL: Ruleset['topicPool'] = [
- { id: 'front-page', name: 'Front Page', stat: 'attention', portal: null },
- { id: 'trending', name: 'Trending', stat: 'attention', portal: 'spotlight' },
- { id: 'viral', name: 'Viral', stat: 'attention', portal: 'paywall' },
- { id: 'deep-dive', name: 'Deep Dive', stat: 'depth', portal: null },
- { id: 'archive', name: 'Archive', stat: 'depth', portal: 'spotlight' },
- { id: 'citation-needed', name: 'Citation Needed', stat: 'depth', portal: 'paywall' },
- { id: 'world-tour', name: 'World Tour', stat: 'reach', portal: null },
- { id: 'translation', name: 'Translation', stat: 'reach', portal: 'spotlight' },
- { id: 'interwiki', name: 'Interwiki', stat: 'reach', portal: 'paywall' },
+ { id: 'current-events', name: 'Current Events', stat: 'attention', portal: null },
+ { id: 'main-page', name: 'Main Page', stat: 'attention', portal: 'main-page' },
+ { id: 'trending', name: 'Trending', stat: 'attention', portal: 'trending' },
+ { id: 'archive', name: 'Archive', stat: 'depth', portal: null },
+ { id: 'featured-article', name: 'Featured Article', stat: 'depth', portal: 'featured-article' },
+ { id: 'stub', name: 'Stub', stat: 'depth', portal: 'stub' },
+ { id: 'translations', name: 'Translations', stat: 'reach', portal: null },
+ { id: 'interwiki', name: 'Interwiki', stat: 'reach', portal: 'interwiki' },
+ { id: 'disambiguation', name: 'Disambiguation', stat: 'reach', portal: 'disambiguation' },
];
-/** DESIGN §9 defaults. */
+/** DESIGN §9 defaults (v1). */
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,
+ energyByTurn: [1, 2, 3, 4, 5, 6], energyCarryMax: 1, bonusEnergy: 0, underdog: false,
+ topicCount: 3, distinctStats: true, portalReveal: [2, 3, 4], laneCapacity: 3,
topicPool: DEFAULT_TOPIC_POOL,
+ keywordParams: {
+ viral: { amount: 1, cap: 2, powerDelta: 0 }, rising: { amount: 1, cap: 2, powerDelta: 0 },
+ local: { amount: 1, powerDelta: 0 }, encyclopedic: { amount: 2, powerDelta: 0 },
+ nostalgic: { amount: 2, powerDelta: 0 }, translated: { amount: 1, powerDelta: 0 },
+ edition: { amount: 2, powerDelta: 0 }, obscure: { powerDelta: 0 }, wildcard: { powerDelta: 0 },
+ },
+ portalParams: {
+ 'main-page': { amount: 1 }, trending: { factor: 2 }, 'featured-article': { amount: 2 },
+ stub: { value: 2 }, interwiki: { amount: 1 },
+ },
costThresholds: [15, 35, 55, 75, 90],
- powerByCost: [0, 1, 2, 4, 5, 7, 9],
- onTopicBonus: 2,
- trendUp: 25, trendDown: -25,
+ powerByCost: [0, 1, 2, 4, 6, 8, 10],
+ onTopicBonus: [0, 1, 1, 2, 2, 3, 3], vanillaBonus: 1,
+ keywordsEnabled: ['viral', 'rising', 'local', 'encyclopedic', 'nostalgic', 'translated'], ownedCards: true,
+ trendUp: 25, trendDown: -25, trendMinDaily: 20, uncheckedCostCap: 4,
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 } },
};
diff --git a/shared/game/starter.ts b/shared/game/starter.ts
index 81a45a7..a5b16b1 100644
--- a/shared/game/starter.ts
+++ b/shared/game/starter.ts
@@ -7,41 +7,49 @@
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];
+type Spec = [pageId: number, title: string, faction: Faction, cost: number, home: Stat];
-/** 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];
+/** DESIGN §1.3 powerByCost and §10.1 keyword choice (cost 1 = vanilla +vanillaBonus). pageIds outside shared/catalog.ts are unverified. */
+const POWER_BY_COST = [0, 1, 2, 4, 6, 8, 10];
+const VANILLA_BONUS = 1;
+const FACTION_KEYWORD: Record = {
+ Culture: 'viral', Nature: 'rising', People: 'local', Science: 'encyclopedic', History: 'nostalgic', Space: 'translated',
+};
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],
+ [22780, 'Octopus', 'Nature', 1, 'depth'],
+ [19331, 'Moon', 'Space', 1, 'reach'],
+ [23053, 'Periodic table', 'Science', 1, 'depth'],
+ [3383, 'Bronze Age', 'History', 1, 'depth'],
+ [5843419, 'Chess', 'Culture', 2, 'attention'],
+ [9228, 'Earth', 'Space', 2, 'reach'],
+ [2008, 'Ada Lovelace', 'People', 2, 'attention'],
+ [21830, 'Honey bee', 'Nature', 2, 'depth'],
+ [736, 'Albert Einstein', 'People', 3, 'reach'],
+ [10979, 'Fungus', 'Nature', 3, 'depth'],
+ [26903, 'Solar System', 'Space', 3, 'reach'],
+ [30758, 'Roman Empire', 'History', 3, 'depth'],
+ [9649, 'Evolution', 'Science', 4, 'depth'],
+ [8424, 'Jazz', 'Culture', 4, 'attention'],
+ [12898, 'Marie Curie', 'People', 4, 'reach'],
+ [14533, 'Silk Road', 'History', 4, 'reach'],
+ [19468, 'Mount Everest', 'Nature', 5, 'attention'],
+ [22936, 'Photosynthesis', 'Science', 5, 'depth'],
+ [18110, 'Leonardo da Vinci', 'People', 5, 'reach'],
+ [14627, 'Ancient Egypt', 'History', 5, 'attention'],
+ [4177, 'Black hole', 'Space', 6, 'attention'],
+ [25443, 'Quantum mechanics', 'Science', 6, 'depth'],
+ [17867, 'Library of Alexandria', 'History', 6, 'depth'],
+ [20217, 'Music', 'Culture', 6, 'reach'],
];
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' };
+ const [pageId, title, faction, cost, home] = spec;
+ const keyword = cost === 1 ? null : FACTION_KEYWORD[faction];
+ return {
+ cardId: `loaner:${pageId}:${copy}`, pageId, title, faction, rarity: 'Common', cost,
+ power: POWER_BY_COST[cost] + (keyword ? 0 : VANILLA_BONUS), home, trend: 0, keyword, source: 'loaner', check: 'loaner',
+ };
}
/** Every placeholder loaner card, once each (24 cards). Draft modes can sample from this. */
diff --git a/shared/game/types.ts b/shared/game/types.ts
index 966e48a..7096756 100644
--- a/shared/game/types.ts
+++ b/shared/game/types.ts
@@ -37,6 +37,8 @@ export interface GameCard {
keyword: string | null;
/** 'owned' = an NFT the player holds (never moved or burned by a match). */
source: 'owned' | 'loaner';
+ /** Host plausibility result (§1.10). Derivation already applied uncheckedCostCap. Default: 'loaner' for loaners, 'verified' for owned. */
+ check?: 'verified' | 'unverified' | 'unchecked' | 'loaner';
}
/** A Topic (lane) definition in a ruleset's topic pool (§3). */
@@ -44,15 +46,13 @@ export interface TopicDef {
id: string;
name: string;
stat: Stat;
- /** Portal modifier id (§10.3), or null for a plain Topic. */
+ /** Portal kind id in PORTALS (§10.3), or null for a plain Topic. Numbers: Ruleset.portalParams[topic id] (falls back to [portal id]). */
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;
@@ -67,28 +67,39 @@ export interface Ruleset {
afkTurns: number;
/** energyByTurn[t-1] is the base energy on turn t. Length must be ≥ turns. */
energyByTurn: number[];
+ /** Unspent energy carried to next turn, capped at this. */
+ energyCarryMax: number;
bonusEnergy: number;
underdog: boolean;
topicCount: number;
distinctStats: boolean;
- /** revealSchedule[i] = turn on which Topic i is revealed. Length = topicCount. */
- revealSchedule: number[];
+ /** portalReveal[i] = turn on which Topic i's Portal is revealed (stats are always visible). Length = topicCount. */
+ portalReveal: number[];
laneCapacity: number;
topicPool: TopicDef[];
+ /** Per-keyword numbers, keyed by keyword id. */
+ keywordParams: Record>;
+ /** Per-Portal numbers, keyed by Topic id (or Portal kind id as a fallback). */
+ portalParams: Record>;
costThresholds: number[];
/** Index = cost (0–6). */
powerByCost: number[];
- onTopicBonus: number;
+ /** Index = cost (0–6): on-topic bonus. */
+ onTopicBonus: number[];
+ vanillaBonus: number;
+ /** Keyword ids whose hooks run. Cards with a disabled keyword are vanilla (derivation handles power). */
+ keywordsEnabled: string[];
+ ownedCards: boolean;
trendUp: number;
trendDown: number;
+ trendMinDaily: number;
+ uncheckedCostCap: number;
factionSynergyCap: number;
verifyStats: boolean;
- /** Id of the percentile reference table used by cards.ts. */
+ /** Id of the percentile reference table used by derive.ts. */
percentiles: string;
- /** Id of the starter deck list used by cards.ts. */
+ /** Id of the starter deck list. */
starterDecks: string;
- keywordParams: Record>;
- portalParams: Record>;
}
export interface CardInPlay {
@@ -97,6 +108,8 @@ export interface CardInPlay {
lane: number;
/** Turn the card was revealed. */
turn: number;
+ /** Global reveal sequence number (1, 2, 3 … across both seats and all turns). */
+ seq: number;
/** Permanent power changes from effects (on-reveal buffs etc.). */
bonus: number;
}
@@ -113,11 +126,14 @@ export interface PlayerState {
committed: boolean;
/** Consecutive timeouts with nothing queued (§7 afkTurns). */
afk: number;
+ /** Energy carried into this turn (already included in `energy`). */
+ carry: number;
}
export interface LaneState {
+ /** Stat and name are always visible; the Portal only once portalRevealed. */
topic: TopicDef;
- revealed: boolean;
+ portalRevealed: boolean;
cards: [CardInPlay[], CardInPlay[]];
}
@@ -125,7 +141,7 @@ export type MatchPhase = 'planning' | 'over';
export type LogEvent =
| { t: 'turnStart'; turn: number; energy: [number, number]; initiative: PlayerId }
- | { t: 'topicRevealed'; lane: number; topic: TopicDef }
+ | { t: 'portalRevealed'; lane: number; topic: TopicDef }
| { t: 'underdog'; player: PlayerId }
| { t: 'draw'; player: PlayerId; cardId: string }
| { t: 'reveal'; player: PlayerId; cardId: string; lane: number }
@@ -143,8 +159,10 @@ export interface MatchState {
/** 1-based current turn. */
turn: number;
phase: MatchPhase;
- /** Player who reveals first this turn (§5.4). */
+ /** Player who reveals first this turn (§5.4). Alternates every turn. */
initiative: PlayerId;
+ /** Last reveal sequence number handed out (CardInPlay.seq). */
+ revealSeq: number;
players: [PlayerState, PlayerState];
lanes: LaneState[];
log: LogEvent[];
@@ -169,7 +187,7 @@ export interface MatchResult {
winner: PlayerId | null;
reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk';
topicsLed: [number, number];
- /** lanePower[lane][player] at the end. */
+ /** lanePower[lane][player] at the end, including "at scoring" Portals. */
lanePower: [number, number][];
totalPower: [number, number];
turns: number;
@@ -191,8 +209,9 @@ export interface PlayerView {
deckCount: number;
opponent: { handCount: number; deckCount: number; queuedCount: number; committed: boolean };
lanes: {
- /** null while face-down. */
- topic: TopicDef | null;
+ /** Always visible; `portal` is null until the Portal is revealed. */
+ topic: TopicDef;
+ portalRevealed: boolean;
/** cards[0] = yours, cards[1] = opponent's (revealed cards only). */
cards: [CardInPlay[], CardInPlay[]];
/** Lane power of each card in `cards`, same shape. */
diff --git a/tests/game-core.test.ts b/tests/game-core.test.ts
index 87e5fb3..30b4d60 100644
--- a/tests/game-core.test.ts
+++ b/tests/game-core.test.ts
@@ -1,16 +1,27 @@
-// Core-loop tests owned by engine-a. Keyword, property and golden tests: engine-b (tests/game-*.test.ts).
+// Core-loop tests owned by engine-a. Keyword/Portal, derivation, 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,
+ DEFAULT_RULESET, IllegalActionError, KEYWORDS, PORTALS, Rng, applyAction, cardPower, createMatch, deserialize, isOver,
+ laneLeader, legalActions, loanerCard, parseRuleset, placeCard, replay, result, revealPortal, serialize, starterDeck,
+ STARTER_POOL, viewFor, type Action, type GameCard, type KeywordDef, type MatchState, type PlayerId, type PortalDef, 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 =>
- ({ ...loanerCard(STARTER_POOL.find(s => s[3] === cost && s[5] === null)!), keyword: null, ...overrides });
+const commit = (s: MatchState, player: PlayerId) => applyAction(s, { type: 'commit', player });
+const commitBoth = (s: MatchState) => commit(commit(s, 0), 1);
+const card = (cost: number, overrides: Partial = {}): GameCard =>
+ ({ ...loanerCard(STARTER_POOL.find(s => s[3] === cost)!), keyword: null, trend: 0, ...overrides });
+/** A deck whose every card costs `cost`, so the first plays are predictable. */
+const flatDeck = (cost: number, prefix: string, home: GameCard['home'] = 'depth'): GameCard[] =>
+ Array.from({ length: 12 }, (_, i) => card(cost, { cardId: `${prefix}${i}`, pageId: 1000 + Math.floor(i / 2), home }));
+
+/** Temporarily register a keyword/portal implementation under a v1 id. */
+function withHook(registry: Record, id: string, def: T, run: () => void) {
+ const saved = registry[id];
+ registry[id] = def;
+ try { run(); } finally { if (saved === undefined) delete registry[id]; else registry[id] = saved; }
+}
function randomPlay(seed: number, ruleset: Ruleset = DEFAULT_RULESET): MatchState {
let state = createMatch(ruleset, decks(String(seed)), seed);
@@ -20,12 +31,12 @@ function randomPlay(seed: number, ruleset: Ruleset = DEFAULT_RULESET): MatchStat
const player = chooser.int(2) as PlayerId;
const actions = legalActions(state, player);
if (actions.length) state = applyAction(state, chooser.pick(actions));
+ assert.deepEqual(deserialize(serialize(state)), state);
}
return state;
}
-test('mulberry32 matches the reference sequence and is seed-deterministic', () => {
- // Reference: mulberry32(1) first output = 0.6270739405881613.
+test('mulberry32 matches the reference value and is seed-deterministic', () => {
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)));
@@ -35,31 +46,43 @@ test('mulberry32 matches the reference sequence and is seed-deterministic', () =
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.equal(DEFAULT_RULESET.laneCapacity, 3);
+ assert.deepEqual(DEFAULT_RULESET.powerByCost, [0, 1, 2, 4, 6, 8, 10]);
+ assert.deepEqual(DEFAULT_RULESET.onTopicBonus, [0, 1, 1, 2, 2, 3, 3]);
+ assert.equal(DEFAULT_RULESET.topicPool.length, 9);
+ for (const bad of [{ turns: 13 }, { turnSeconds: 60 }, { energyByTurn: [1, 2] }, { portalReveal: [1, 2] },
+ { keywordParams: { nope: {} } }, { keywordsEnabled: ['nope'] }, { extra: 1 }, { mulligan: true },
+ { costThresholds: [90, 1, 2, 3, 4] }, { onTopicBonus: 2 }, { topicCount: 2 }, { portalParams: { nope: {} } }])
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', () => {
+test('setup: one Topic per stat, stats visible, Portals hidden until portalReveal, 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]);
+ assert.deepEqual(state.lanes.map(l => l.portalRevealed), [false, 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]);
+ const view = viewFor(state, 0);
+ assert.deepEqual(view.lanes.map(l => l.topic.stat), state.lanes.map(l => l.topic.stat));
+ assert.ok(view.lanes.every(l => l.topic.portal === null && l.topic.name === '?'));
+ let next = commitBoth(state);
+ assert.deepEqual(next.lanes.map(l => l.portalRevealed), [true, false, false]);
+ next = commitBoth(commitBoth(next));
+ assert.deepEqual(next.lanes.map(l => l.portalRevealed), [true, true, true]);
});
-test('decks are validated: size, copies per page, unknown keyword', () => {
+test('decks are validated: size, copies per page, keyword ids, ownedCards', () => {
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/);
+ const owned = [{ ...a[0], source: 'owned' as const }, ...a.slice(1)];
+ assert.doesNotThrow(() => createMatch(DEFAULT_RULESET, [owned, b], 1));
+ assert.throws(() => createMatch({ ...DEFAULT_RULESET, ownedCards: false }, [owned, b], 1), /owned/);
});
-test('queued plays are hidden from the opponent until reveal; undo refunds', () => {
+test('queued plays are hidden until reveal; undo refunds; committed seats get no actions', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 11);
const play = legalActions(state, 0).find(a => a.type === 'play') as Extract;
assert.ok(play, 'turn 1 should have a 1-cost play');
@@ -67,59 +90,94 @@ test('queued plays are hidden from the opponent until reveal; undo refunds', ()
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(viewFor(applyAction(state, { type: 'undo', player: 0, cardId: play.cardId }), 0).energyLeft, 1);
+ state = commit(state, 0);
+ assert.deepEqual(legalActions(state, 0), []);
+ state = commit(state, 1);
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' }));
+test('energy: energyByTurn + carry (max 1) of unspent energy', () => {
+ let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 3);
+ const first = state.players[0].hand[0].cardId;
+ state = applyAction(state, { type: 'play', player: 0, cardId: first, lane: 0 }); // p0 spends 1, p1 saves 1
state = commitBoth(state);
- assert.deepEqual(topicsLed(state), [0, 2]);
- assert.equal(state.players[0].energy, 3);
- assert.equal(state.players[1].energy, 2);
+ assert.deepEqual(state.players.map(p => p.energy), [2, 3]);
+ state = commitBoth(state); // both save everything; carry is capped at 1
+ assert.deepEqual(state.players.map(p => p.energy), [4, 4]);
+});
+
+test('reveal is interleaved: initiative 1st, other 1st, initiative 2nd, …; initiative alternates', () => {
+ let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 5);
+ state = commitBoth(state); // turn 2: 3 energy each (2 + carry 1)
+ const init = state.initiative;
+ const ids = (p: PlayerId) => state.players[p].hand.slice(0, 3).map(c => c.cardId);
+ const [mine, theirs] = [ids(init), ids(init === 0 ? 1 : 0)];
+ for (const [player, cards] of [[init, mine], [init === 0 ? 1 : 0, theirs.slice(0, 2)]] as const)
+ cards.forEach((cardId, lane) => { state = applyAction(state, { type: 'play', player, cardId, lane }); });
+ const before = state.log.length;
+ state = commitBoth(state);
+ const order = state.log.slice(before).filter(e => e.t === 'reveal').map(e => (e as { cardId: string }).cardId);
+ assert.deepEqual(order, [mine[0], theirs[0], mine[1], theirs[1], mine[2]]);
+ assert.equal(state.initiative, init === 0 ? 1 : 0);
+ assert.deepEqual(state.lanes.flatMap(l => [...l.cards[0], ...l.cards[1]]).map(c => c.seq).sort((x, y) => x - y), [1, 2, 3, 4, 5]);
+});
+
+test('lane power: base + onTopicBonus[cost] + trend, floored at 0', () => {
+ let state = createMatch(DEFAULT_RULESET, decks(), 5);
+ const stat = state.lanes[1].topic.stat;
+ const off = stat === 'depth' ? 'reach' : 'depth';
+ state = placeCard(state, 0, 1, card(5, { cardId: 'on', home: stat, trend: 1 }));
+ assert.equal(cardPower(state, state.lanes[1].cards[0][0]), 8 + 3 + 1);
+ state = placeCard(state, 0, 1, card(2, { cardId: 'off', home: off }));
+ assert.equal(cardPower(state, state.lanes[1].cards[0][1]), 2);
+ state = placeCard(state, 1, 1, card(1, { cardId: 'neg', home: off, trend: -1, power: 0 }));
+ assert.equal(cardPower(state, state.lanes[1].cards[1][0]), 0);
+});
+
+test('consensus tie-break: equal power > 0 goes to more on-topic cards; 0–0 has no leader', () => {
+ let state = createMatch(DEFAULT_RULESET, decks(), 8);
+ const stat = state.lanes[0].topic.stat;
+ const off = stat === 'depth' ? 'reach' : 'depth';
+ assert.equal(laneLeader(state, 0), null);
+ state = placeCard(state, 0, 0, card(2, { cardId: 'a', home: stat, power: 1 })); // 1 + 1 on-topic = 2
+ state = placeCard(state, 1, 0, card(2, { cardId: 'b', home: off, power: 2 })); // 2 off-topic
+ assert.equal(laneLeader(state, 0), 0);
+ state = placeCard(state, 1, 0, card(1, { cardId: 'c', home: stat, power: 0 })); // +1 on-topic: 3 vs 2
+ assert.equal(laneLeader(state, 0), 1);
+});
+
+test('Portals: capacity override and fizzle at reveal, at-scoring bonus, disabled keywords do not run', () => {
+ const stub: PortalDef = { id: 'stub', name: 'Stub', text: '', capacity: ctx => ctx.params.value ?? 2 };
+ const mainPage: PortalDef = { id: 'main-page', name: 'Main Page', text: '', atScoring: ctx => [0, 1].map(p => ctx.state.lanes[ctx.lane].cards[p].length * (ctx.params.amount ?? 1)) as [number, number] };
+ const bump: KeywordDef = { id: 'rising', name: 'Rising', text: '', onReveal: (_ctx, self) => { self.bonus += 5; } };
+ withHook(PORTALS, 'stub', stub, () => withHook(PORTALS, 'main-page', mainPage, () => withHook(KEYWORDS, 'rising', bump, () => {
+ let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 2);
+ state.lanes[0].topic = { id: 'stub', name: 'Stub', stat: 'depth', portal: 'stub' };
+ state.lanes[1].topic = { id: 'main-page', name: 'Main Page', stat: 'attention', portal: 'main-page' };
+ state = revealPortal(revealPortal(state, 0), 1);
+ state = placeCard(placeCard(state, 0, 0, card(1, { cardId: 'p1' })), 0, 0, card(1, { cardId: 'p2' }));
+ assert.ok(legalActions(state, 0).every(a => a.type !== 'play' || a.lane !== 0), 'Stub holds 2');
+ state = placeCard(state, 1, 1, card(2, { cardId: 'r', keyword: 'rising' }));
+ state.ruleset.keywordsEnabled = [];
+ const hand = state.players[1].hand[0];
+ state = applyAction(state, { type: 'play', player: 1, cardId: hand.cardId, lane: 1 });
+ state.players[1].hand[0] = { ...hand, keyword: 'rising' }; // disabled: no +5
+ while (!isOver(state)) state = commitBoth(state);
+ const r = result(state)!;
+ assert.equal(r.lanePower[1][1], cardPower(state, state.lanes[1].cards[1][0]) + cardPower(state, state.lanes[1].cards[1][1]) + 2);
+ assert.ok(state.lanes[1].cards[1].every(c => c.bonus === 0));
+ })));
});
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 });
+ state = commit(applyAction(state, { type: 'timeout', player: 0 }), 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');
+ assert.deepEqual([result(state)?.winner, result(state)?.reason], [1, 'afk']);
const conceded = applyAction(createMatch(DEFAULT_RULESET, decks(), 1), { type: 'concede', player: 1 });
assert.equal(result(conceded)?.winner, 0);
assert.deepEqual(legalActions(conceded, 0), []);
@@ -128,15 +186,15 @@ test('timeouts with nothing queued concede after afkTurns; concede ends the matc
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 });
+ const r = result(state)!;
+ assert.deepEqual([r.winner, r.reason, r.turns], [null, 'draw', 6]);
});
test('random legal play terminates, replays exactly, and survives serialisation after every action', () => {
- for (let seed = 0; seed < 30; seed++) {
+ for (let seed = 0; seed < 20; 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);
}
});
--
2.54.0
From e0ac157ee1306324a79ce9601646fe2336337f57 Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:14:51 -0500
Subject: [PATCH 04/14] Engine: trendDown -200 default; nullable loaner pageId
counts copies per cardId (DESIGN #23/#24)
Co-Authored-By: Claude Opus 5.5
---
docs/game/ENGINE_API.md | 2 +-
shared/game/engine.ts | 13 ++++++++-----
shared/game/ruleset.ts | 2 +-
shared/game/types.ts | 3 ++-
4 files changed, 12 insertions(+), 8 deletions(-)
diff --git a/docs/game/ENGINE_API.md b/docs/game/ENGINE_API.md
index 55cb030..e4aedd7 100644
--- a/docs/game/ENGINE_API.md
+++ b/docs/game/ENGINE_API.md
@@ -89,7 +89,7 @@ type Action =
```ts
interface GameCard {
cardId: string; // unique within a deck: the NFT card hash, or `loaner::`
- pageId: number; // at most ruleset.maxCopiesPerPage cards share a pageId
+ pageId: number | null; // at most maxCopiesPerPage cards share a pageId; null (unpinned loaners) → counted per cardId
title: string;
faction: 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
rarity: 'Common' | 'Rare' | 'Epic' | 'Legendary'; // cosmetic in v1
diff --git a/shared/game/engine.ts b/shared/game/engine.ts
index b5c7476..67d8616 100644
--- a/shared/game/engine.ts
+++ b/shared/game/engine.ts
@@ -29,14 +29,15 @@ export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[
if (!Array.isArray(deck)) return ['Deck must be an array'];
if (deck.length !== rules.deckSize) problems.push(`Deck must have exactly ${rules.deckSize} cards (has ${deck.length})`);
const ids = new Set();
- const copies = new Map();
+ const copies = new Map();
let loaners = 0;
for (const card of deck) {
if (typeof card?.cardId !== 'string' || !card.cardId || card.cardId.length > 128) { problems.push('cardId must be a non-empty string'); continue; }
const label = card.cardId;
if (ids.has(card.cardId)) problems.push(`Duplicate cardId ${label}`);
ids.add(card.cardId);
- if (!Number.isInteger(card.pageId)) problems.push(`${label}: bad pageId`);
+ if (card.pageId !== null && !Number.isInteger(card.pageId)) problems.push(`${label}: bad pageId`);
+ if (card.pageId === null && card.source !== 'loaner') problems.push(`${label}: owned cards need a pageId`);
if (typeof card.title !== 'string' || card.title.length > 256) problems.push(`${label}: bad title`);
if (!FACTION_SET.has(card.faction)) problems.push(`${label}: bad faction`);
if (!RARITIES.has(card.rarity)) problems.push(`${label}: bad rarity`);
@@ -49,9 +50,11 @@ export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[
if (card.check !== undefined && !CHECKS.has(card.check)) problems.push(`${label}: bad check`);
if (card.source === 'loaner') loaners++;
if (card.source === 'owned' && !rules.ownedCards) problems.push(`${label}: owned cards are not allowed in this mode`);
- 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}`);
+ // §2 / §2.1: owned and loaner copies count together by pageId; unpinned loaners (pageId null) by cardId.
+ const key = card.pageId !== null ? `page:${card.pageId}` : `card:${card.cardId}`;
+ const n = (copies.get(key) ?? 0) + 1;
+ copies.set(key, n);
+ if (n === rules.maxCopiesPerPage + 1) problems.push(`More than ${rules.maxCopiesPerPage} copies of ${card.pageId !== null ? `page ${card.pageId}` : card.cardId}`);
}
if (loaners > rules.maxLoaners) problems.push(`At most ${rules.maxLoaners} loaner cards`);
return problems;
diff --git a/shared/game/ruleset.ts b/shared/game/ruleset.ts
index 4f5a57a..8297ead 100644
--- a/shared/game/ruleset.ts
+++ b/shared/game/ruleset.ts
@@ -119,7 +119,7 @@ export const DEFAULT_RULESET: Ruleset = {
powerByCost: [0, 1, 2, 4, 6, 8, 10],
onTopicBonus: [0, 1, 1, 2, 2, 3, 3], vanillaBonus: 1,
keywordsEnabled: ['viral', 'rising', 'local', 'encyclopedic', 'nostalgic', 'translated'], ownedCards: true,
- trendUp: 25, trendDown: -25, trendMinDaily: 20, uncheckedCostCap: 4,
+ trendUp: 25, trendDown: -200, trendMinDaily: 20, uncheckedCostCap: 4,
factionSynergyCap: 3,
verifyStats: true,
percentiles: 'card-sample-2026-11-16',
diff --git a/shared/game/types.ts b/shared/game/types.ts
index 7096756..1fe5994 100644
--- a/shared/game/types.ts
+++ b/shared/game/types.ts
@@ -24,7 +24,8 @@ export type Rarity = 'Common' | 'Rare' | 'Epic' | 'Legendary';
export interface GameCard {
/** Unique within one deck (the NFT card hash, or `loaner::`). */
cardId: string;
- pageId: number;
+ /** null for unpinned loaners (DESIGN §2.1): copies then count per cardId. */
+ pageId: number | null;
title: string;
faction: Faction;
/** Cosmetic in v1 (§1.7). */
--
2.54.0
From b6dcd74cc3e296ffb2de1d816005de2a96f047e9 Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:16:18 -0500
Subject: [PATCH 05/14] Play section: lobby, deck builder, match, results,
tutorial
Mobile-first game UI in src/game/, built against a UI-side EngineAdapter.
A temporary mock 3-lane engine (src/game/mock/) stands in until
shared/game lands. Tap a card, then tap a lane; bottom thumb dock; bottom
sheets instead of hover; full-screen match on phones. Lobby lists local
and peer modes (GET /api/game/modes, parsed defensively) and shows the
eom.dev login state through a stub hook for the SSO team.
Co-Authored-By: Claude Opus 5.5
---
src/App.tsx | 11 +--
src/game/DeckBuilder.tsx | 68 ++++++++++++++++
src/game/GameCard.tsx | 30 +++++++
src/game/MatchScreen.tsx | 153 ++++++++++++++++++++++++++++++++++
src/game/PlaySection.tsx | 97 ++++++++++++++++++++++
src/game/Results.tsx | 24 ++++++
src/game/Tutorial.tsx | 45 ++++++++++
src/game/adapter.ts | 13 +++
src/game/bots.ts | 16 ++++
src/game/cards.ts | 54 ++++++++++++
src/game/mock/engine.ts | 156 +++++++++++++++++++++++++++++++++++
src/game/play.css | 172 +++++++++++++++++++++++++++++++++++++++
src/game/types.ts | 94 +++++++++++++++++++++
src/game/useAccount.ts | 6 ++
src/game/useModes.ts | 42 ++++++++++
tests/ui-play.test.ts | 79 ++++++++++++++++++
16 files changed, 1055 insertions(+), 5 deletions(-)
create mode 100644 src/game/DeckBuilder.tsx
create mode 100644 src/game/GameCard.tsx
create mode 100644 src/game/MatchScreen.tsx
create mode 100644 src/game/PlaySection.tsx
create mode 100644 src/game/Results.tsx
create mode 100644 src/game/Tutorial.tsx
create mode 100644 src/game/adapter.ts
create mode 100644 src/game/bots.ts
create mode 100644 src/game/cards.ts
create mode 100644 src/game/mock/engine.ts
create mode 100644 src/game/play.css
create mode 100644 src/game/types.ts
create mode 100644 src/game/useAccount.ts
create mode 100644 src/game/useModes.ts
create mode 100644 tests/ui-play.test.ts
diff --git a/src/App.tsx b/src/App.tsx
index ca9d178..412ca7b 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowDownLeft, ArrowLeftRight, ArrowRight, ArrowUpRight, BookOpen, Check, ChevronRight, CircleHelp,
Copy, Cpu, Download, ExternalLink, Globe2, Layers3, LayoutDashboard, LoaderCircle,
- Pickaxe, Search, Shield, Sparkles, Wallet as WalletIcon, X } from 'lucide-react';
+ Pickaxe, Search, Shield, Sparkles, Swords, Wallet as WalletIcon, X } from 'lucide-react';
import { rarity } from '../shared/protocol.ts';
import { CONSENSUS, NETWORK, isNftTrade, nftTransferMessage, testnetOwnerOf, transactionCardIds,
type TestnetBlock, type TestnetSnapshot } from '../shared/testnet.ts';
@@ -13,10 +13,11 @@ import { ThemePicker } from './ThemePicker.tsx';
import { TradeDesk } from './TradeDesk.tsx';
import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/network.ts';
import { StateClient } from '../shared/rpc-client.ts';
+import { PlaySection } from './game/PlaySection.tsx';
import './App.css';
import './testnet.css';
-type View = 'Discover' | 'My collection' | 'Block explorer' | 'Trade cards';
+type View = 'Discover' | 'Play' | 'My collection' | 'Block explorer' | 'Trade cards';
const short = (s: string) => s ? `${s.slice(0, 6)}…${s.slice(-4)}` : '—';
const asCard = (block: TestnetBlock): CardData => ({ article: block.article, hash: block.powHash, block });
const message = (error: unknown) => error instanceof Error ? error.message : 'Request failed. Please try again.';
@@ -161,8 +162,8 @@ export default function App() {
{ e.preventDefault(); setView('Discover'); }}>W✦ wikideck.
YOUR NEXT DISCOVERY
- {(['Discover', 'My collection', 'Block explorer', 'Trade cards'] as View[]).map((item, i) => {
- const Icon = [LayoutDashboard, Layers3, Globe2, ArrowLeftRight][i];
+ {(['Discover', 'Play', 'My collection', 'Block explorer', 'Trade cards'] as View[]).map((item, i) => {
+ const Icon = [LayoutDashboard, Swords, Layers3, Globe2, ArrowLeftRight][i];
return { setView(item); setQuery(''); setCategory('All cards'); }}> {item}{item === 'My collection' && {owned.length} } ;
})}
✦ Mine together. Trade your way. Discover illustrated Wikipedia cards, build a deck around what you love, and find your collector community.
setDialog('guide')}>How it works
@@ -195,7 +196,7 @@ export default function App() {
TRADE · PLAYER TO PLAYER
Swap cards directly. Prepare a signed offer for another collector and exchange card bundles atomically when the trade is mined. No prices or checkout.
setView('Trade cards')}>Trade cards
>}
- {view === 'Trade cards' ? : view !== 'Block explorer' ?
+ {view === 'Play' ? : view === 'Trade cards' ? : view !== 'Block explorer' ?
{view === 'My collection' ? 'YOUR PERSONAL ENCYCLOPEDIA' : 'AN ENCYCLOPEDIA, REIMAGINED'}
{view === 'My collection' ? 'Your cabinet of curiosities' : 'A world of possible discoveries'}{visibleCards.length} {view === 'My collection' ? 'Confirmed native NFT ownership. Pending transfers stay here until mined.' : snapshot?.blocks.length ? 'Recent native NFTs on this node’s canonical chain.' : 'Sample previews only; mined NFTs use random Wikipedia pages with pictures. The same page may be minted more than once.'}
{view === 'Discover' &&
setView('My collection')}>My collection }
{filtered.length ? {filtered.map(c =>
{ setSelected(c); setTransferError(''); }} />{c.block ? `Block #${c.block.height}` : 'Example discovery'} {c.block && snapshot ? short(testnetOwnerOf(snapshot, c.block.tokenId) ?? '') : 'Not owned'}
{c.block && snapshot?.pendingTransfers.some(tx => transactionCardIds(tx).includes(c.block!.tokenId)) && Transfer or trade pending mining } )}
: {query || category !== 'All cards' ? 'No discoveries here. Yet.' : 'Your first discovery is waiting.'} {query || category !== 'All cards' ? 'Try another search or explore a different category.' : 'Use the native miner or receive a mined transfer on this chain. Restore a backup to access an existing wallet.'}
Explore native mining }
diff --git a/src/game/DeckBuilder.tsx b/src/game/DeckBuilder.tsx
new file mode 100644
index 0000000..fb170c4
--- /dev/null
+++ b/src/game/DeckBuilder.tsx
@@ -0,0 +1,68 @@
+import { useMemo, useState } from 'react';
+import { Check, RotateCcw, Trash2 } from 'lucide-react';
+import { GameCard } from './GameCard.tsx';
+import { starterDeck } from './cards.ts';
+import type { Ruleset, UICard } from './types.ts';
+
+export function deckProblem(deck: UICard[], ruleset: Ruleset): string {
+ if (deck.length !== ruleset.deckSize) return `A deck needs exactly ${ruleset.deckSize} cards (${deck.length} now).`;
+ const counts = new Map();
+ for (const c of deck) counts.set(c.pageId, (counts.get(c.pageId) ?? 0) + 1);
+ const over = [...counts].find(([, n]) => n > ruleset.maxCopies);
+ if (over) return `At most ${ruleset.maxCopies} copies of the same article.`;
+ return '';
+}
+
+/** Soft advice (DESIGN.md s8): warn, never block, when the early curve is thin. */
+export function deckWarning(deck: UICard[]): string {
+ const cheap = deck.filter(c => c.cost <= 2).length;
+ return cheap < 4 ? `Only ${cheap} card${cheap === 1 ? '' : 's'} cost 2 or less. Aim for at least 4 so you have early plays.` : '';
+}
+
+export function DeckBuilder({ pool, deck, ruleset, onSave, onCancel }: {
+ pool: UICard[]; deck: UICard[]; ruleset: Ruleset; onSave: (deck: UICard[]) => void; onCancel: () => void;
+}) {
+ const [draft, setDraft] = useState(deck);
+ const [filter, setFilter] = useState<'all' | 'starter' | 'nft'>('all');
+ const inDeck = new Set(draft.map(c => c.id));
+ const shown = pool.filter(c => filter === 'all' || c.source === filter).sort((a, b) => a.cost - b.cost || a.title.localeCompare(b.title));
+ const curve = useMemo(() => [1, 2, 3, 4, 5, 6].map(n => draft.filter(c => Math.min(c.cost, 6) === n).length), [draft]);
+ const nftCount = pool.filter(c => c.source === 'nft').length;
+ const problem = deckProblem(draft, ruleset);
+ const warning = deckWarning(draft);
+ const toggle = (card: UICard) => {
+ if (inDeck.has(card.id)) setDraft(d => d.filter(c => c.id !== card.id));
+ else if (draft.length < ruleset.deckSize) setDraft(d => [...d, card]);
+ };
+ const full = draft.length >= ruleset.deckSize;
+
+ return
+ DECK BUILDER · {ruleset.name.toUpperCase()}
+ Your deck {draft.length} / {ruleset.deckSize}
+ Tap a card to add it or take it out. Loaner cards are free previews, not NFTs; nothing you do here moves a card on-chain.
+ {curve.map((n, i) =>
{i + 1}{i === 5 ? '+' : ''} {n}
)}
+
+ {draft.length ? [...draft].sort((a, b) => a.cost - b.cost).map(c =>
toggle(c)} label={`Remove ${c.title} from deck`} />)
+ : Empty. Add cards below or use the starter deck.
}
+
+
+ {([['all', 'All'], ['starter', 'Loaner'], ['nft', `My NFTs (${nftCount})`]] as const).map(([k, label]) =>
+ setFilter(k)}>{label} )}
+
+ {filter === 'nft' && !nftCount && You don’t own any cards on this network yet. Mine a block or receive a transfer, and it shows up here.
}
+
+ {shown.map(c => toggle(c)} label={`${inDeck.has(c.id) ? 'Remove' : 'Add'} ${c.title}, cost ${c.cost}, power ${c.power}${c.keyword ? `, ${c.keyword.name}` : ''}`} />)}
+
+
+ {problem ?
{problem}
+ : warning &&
{warning}
}
+
+ setDraft(starterDeck())}> Starter
+ setDraft([])} aria-label="Clear deck">
+ Cancel
+ onSave(draft)}> Save deck
+
+
+ ;
+}
diff --git a/src/game/GameCard.tsx b/src/game/GameCard.tsx
new file mode 100644
index 0000000..03410b8
--- /dev/null
+++ b/src/game/GameCard.tsx
@@ -0,0 +1,30 @@
+import { BookOpen, Landmark, Leaf, Orbit, Palette, Users, Zap } from 'lucide-react';
+import type { UICard } from './types.ts';
+
+const ICONS: Record = { Space: Orbit, Nature: Leaf, People: Users, Science: BookOpen, History: Landmark, Culture: Palette };
+export const CategoryIcon = ({ category, size = 14 }: { category: string; size?: number }) => {
+ const Icon = ICONS[category] ?? Palette;
+ return ;
+};
+
+/** Phone-readable card face: cost, power, one keyword, title. Nothing needs hover. */
+export function GameCard({ card, size = 'hand', selected, dim, onClick, label, fresh }: {
+ card: UICard; size?: 'hand' | 'board' | 'deck'; selected?: boolean; dim?: boolean; fresh?: boolean;
+ onClick?: () => void; label?: string;
+}) {
+ const buffed = card.power > card.basePower, nerfed = card.power < card.basePower;
+ const Tag = onClick ? 'button' : 'div';
+ return
+ {card.cost}
+ {card.power}
+
+ {card.image ? { e.currentTarget.style.display = 'none'; }} /> : null}
+
+
+ {card.title}
+ {card.keyword && size !== 'board' && {card.keyword.name} }
+ {card.source === 'nft' && size !== 'board' && NFT }
+ ;
+}
diff --git a/src/game/MatchScreen.tsx b/src/game/MatchScreen.tsx
new file mode 100644
index 0000000..fb3f120
--- /dev/null
+++ b/src/game/MatchScreen.tsx
@@ -0,0 +1,153 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Flag, Hourglass, Layers3, LoaderCircle, X, Zap } from 'lucide-react';
+import { engine } from './adapter.ts';
+import type { Bot } from './bots.ts';
+import { GameCard } from './GameCard.tsx';
+import type { GameMode, LaneView, ResultView, UIAction, UICard } from './types.ts';
+
+const BOT_DELAY_MS = 450;
+
+function seededRand(seed: string) {
+ let h = 1779033703 ^ seed.length;
+ for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 3432918353);
+ return () => { h = Math.imul(h ^ (h >>> 16), 2246822507); h = Math.imul(h ^ (h >>> 13), 3266489909); return ((h ^= h >>> 16) >>> 0) / 4294967296; };
+}
+
+type Sheet = { kind: 'card'; card: UICard; side: 'mine' | 'theirs' } | { kind: 'lane'; lane: LaneView } | { kind: 'concede' } | null;
+
+export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
+ mode: GameMode; deck: UICard[]; opponentDeck: UICard[]; bot: Bot; seed: string; onFinish: (r: ResultView) => void;
+}) {
+ const [state, setState] = useState(() => engine.createMatch(mode.ruleset, [deck, opponentDeck], seed));
+ const [selected, setSelected] = useState();
+ const [sheet, setSheet] = useState(null);
+ const [error, setError] = useState('');
+ const [banner, setBanner] = useState('');
+ const rand = useRef(seededRand(`${seed}:bot`));
+ const view = engine.view(state, 0);
+ const legal = useMemo(() => engine.legal(state, 0), [state]);
+ const prevBoard = useRef(new Set());
+ const [fresh, setFresh] = useState(new Set());
+
+ // Turn feedback: banner on turn change, and a short highlight on newly revealed cards.
+ const lastTurn = useRef(view.turn);
+ useEffect(() => {
+ const ids = new Set(view.lanes.flatMap(l => [...l.mine, ...l.theirs].map(c => c.id)));
+ const added = new Set([...ids].filter(id => !prevBoard.current.has(id)));
+ prevBoard.current = ids;
+ if (added.size) { setFresh(added); const t = setTimeout(() => setFresh(new Set()), 900); return () => clearTimeout(t); }
+ }, [state]); // eslint-disable-line react-hooks/exhaustive-deps
+ useEffect(() => {
+ if (view.turn !== lastTurn.current && !view.over) {
+ lastTurn.current = view.turn;
+ setBanner(view.turn === view.maxTurns ? `Final turn · ${view.maxEnergy} energy` : `Turn ${view.turn} · ${view.maxEnergy} energy`);
+ const t = setTimeout(() => setBanner(''), 1400);
+ return () => clearTimeout(t);
+ }
+ }, [view.turn, view.over, view.maxTurns, view.maxEnergy]);
+ useEffect(() => { if (engine.isOver(state)) { const t = setTimeout(() => onFinish(engine.result(state, 0)), 900); return () => clearTimeout(t); } }, [state, onFinish]);
+
+ // The bot moves once the player has ended the turn (it never sees staged plays).
+ useEffect(() => {
+ if (!view.waitingForOpponent) return;
+ const t = setTimeout(() => {
+ setState((s: unknown) => {
+ let cur = s;
+ for (let guard = 0; guard < 40 && !engine.isOver(cur); guard++) {
+ const acts = engine.legal(cur, 1);
+ if (!acts.length) break;
+ const choice = bot.choose(engine.view(cur, 1), acts.filter(a => a.type !== 'concede'), rand.current);
+ try { cur = engine.apply(cur, 1, choice); } catch { cur = engine.apply(cur, 1, { type: 'endTurn' }); }
+ if (choice.type === 'endTurn') break;
+ }
+ return cur;
+ });
+ }, BOT_DELAY_MS);
+ return () => clearTimeout(t);
+ }, [view.waitingForOpponent, state, bot]);
+
+ const act = (a: UIAction) => {
+ try { setState((s: unknown) => engine.apply(s, 0, a)); setError(''); }
+ catch (e) { setError(e instanceof Error ? e.message : 'That move isn’t allowed.'); }
+ };
+ const canPlay = (cardId: string, lane: number) => legal.some(a => a.type === 'play' && a.cardId === cardId && a.lane === lane);
+ const playable = (cardId: string) => legal.some(a => a.type === 'play' && a.cardId === cardId);
+ const sel = view.hand.find(c => c.id === selected);
+ const tapLane = (lane: LaneView) => {
+ if (sel && canPlay(sel.id, lane.index)) { act({ type: 'play', cardId: sel.id, lane: lane.index }); setSelected(undefined); }
+ else setSheet({ kind: 'lane', lane });
+ };
+ const ending = view.waitingForOpponent;
+ const lastEvent = view.log.at(-1);
+
+ return
+
+ Turn {view.turn} /{view.maxTurns}
+ {bot.name} bot · {view.oppHandCount} in hand
+ setSheet({ kind: 'concede' })} aria-label="Concede match">
+
+ {banner && {banner}
}
+
+
+ {view.lanes.map(lane => {
+ const target = !!sel && canPlay(sel.id, lane.index);
+ const lead = lane.myPower > lane.theirPower ? 'ahead' : lane.myPower < lane.theirPower ? 'behind' : 'even';
+ return
+
+ {lane.theirs.map(c => setSheet({ kind: 'card', card: c, side: 'theirs' })} />)}
+
+
tapLane(lane)}
+ aria-label={target ? `Play ${sel!.title} to ${lane.name}` : `${lane.name} lane: you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? ''}`}>
+ {lane.theirPower}
+ {lane.modifier?.name ?? lane.name}
+ {lane.myPower}
+
+
+ {lane.mine.map(c => setSheet({ kind: 'card', card: c, side: 'mine' })} />)}
+ {lane.staged.map(c => act({ type: 'unstage', cardId: c.id })} selected />)}
+ {target && Play here }
+
+
;
+ })}
+
+
+
+
+ {error ? {error}
+ : ending ? <> Opponent is choosing…>
+ : sel ? <> {sel.title} {sel.keyword ? ` · ${sel.keyword.name}: ${sel.keyword.text}` : ''} Tap a lane.>
+ : lastEvent}
+
+
+ {view.hand.length ? view.hand.map(c => setSelected(selected === c.id ? undefined : c.id)} />)
+ : No cards in hand. }
+
+
+
+ {Array.from({ length: view.maxEnergy }, (_, i) => )}
+ {view.energy}
+
+ {view.deckCount}
+ { setSelected(undefined); act({ type: 'endTurn' }); }}>
+ {ending ? 'Waiting…' : view.turn === view.maxTurns ? 'End match' : 'End turn'}
+
+
+
+
+ {sheet && { if (e.target === e.currentTarget) setSheet(null); }}>
+
+
setSheet(null)} aria-label="Close">
+ {sheet.kind === 'card' && <>
+
{sheet.card.title} {sheet.side === 'mine' ? 'Your card' : 'Opponent card'} · {sheet.card.category} · cost {sheet.card.cost} · power {sheet.card.power}{sheet.card.power !== sheet.card.basePower ? ` (base ${sheet.card.basePower})` : ''}
+ {sheet.card.keyword &&
{sheet.card.keyword.name}. {sheet.card.keyword.text}
}>}
+ {sheet.kind === 'lane' && <>
{sheet.lane.name} lane {sheet.lane.modifier &&
{sheet.lane.modifier.name}. {sheet.lane.modifier.text}
}
+
You {sheet.lane.myPower} · Opponent {sheet.lane.theirPower} · up to {sheet.lane.capacity} cards each.
+ {sel && !canPlay(sel.id, sheet.lane.index) &&
{sel.title} can’t go here: {sel.cost > view.energy ? 'not enough energy' : 'this lane is full'}.
}>}
+ {sheet.kind === 'concede' && <>
Concede this match? It counts as a loss. Nothing on-chain changes.
+
setSheet(null)}>Keep playing
+ { setSheet(null); act({ type: 'concede' }); }}> Concede
>}
+
+
}
+ ;
+}
diff --git a/src/game/PlaySection.tsx b/src/game/PlaySection.tsx
new file mode 100644
index 0000000..e275fad
--- /dev/null
+++ b/src/game/PlaySection.tsx
@@ -0,0 +1,97 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { CircleHelp, Globe2, Layers3, Play, Server, Swords, UserRound } from 'lucide-react';
+import type { TestnetBlock } from '../../shared/testnet.ts';
+import { engine } from './adapter.ts';
+import { BOTS, type Bot } from './bots.ts';
+import { cardFromBlock, loanerPool, starterDeck } from './cards.ts';
+import { DeckBuilder, deckProblem } from './DeckBuilder.tsx';
+import { CategoryIcon } from './GameCard.tsx';
+import { MatchScreen } from './MatchScreen.tsx';
+import { Results } from './Results.tsx';
+import { Tutorial } from './Tutorial.tsx';
+import type { GameMode, ResultView, UICard } from './types.ts';
+import { useAccount } from './useAccount.ts';
+import { useModes } from './useModes.ts';
+import './play.css';
+
+type Screen = 'lobby' | 'deck' | 'match' | 'results' | 'tutorial';
+const DECK_KEY = 'wikideck-play-deck';
+const TUTORIAL_KEY = 'wikideck-play-tutorial-seen';
+const store = {
+ get: (k: string) => { try { return localStorage.getItem(k); } catch { return null; } },
+ set: (k: string, v: string) => { try { localStorage.setItem(k, v); } catch { /* storage unavailable */ } },
+};
+
+export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
+ const pool = useMemo(() => [...loanerPool(), ...owned.map(cardFromBlock)], [owned]);
+ const { modes, status } = useModes();
+ const { account, available: ssoAvailable, login, logout } = useAccount();
+ const [screen, setScreen] = useState(() => store.get(TUTORIAL_KEY) ? 'lobby' : 'tutorial');
+ const [modeId, setModeId] = useState('standard');
+ const [bot, setBot] = useState(BOTS[0]);
+ const [savedIds, setSavedIds] = useState(() => { try { return JSON.parse(store.get(DECK_KEY) ?? 'null'); } catch { return null; } });
+ const [seed, setSeed] = useState('');
+ const [result, setResult] = useState();
+ const mode = modes.find(m => m.id === modeId) ?? modes[0];
+
+ // Rebuild the saved deck from current cards; NFTs you no longer own simply drop out.
+ const deck = useMemo(() => {
+ if (!savedIds) return starterDeck();
+ const byId = new Map(pool.map(c => [c.id, c]));
+ return savedIds.flatMap(id => byId.get(id) ?? []);
+ }, [savedIds, pool]);
+ const problem = deckProblem(deck, mode.ruleset);
+ const opponentDeck = useMemo(() => starterDeck(), []);
+
+ const start = () => { setSeed(`${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`); setScreen('match'); };
+ const finish = useCallback((r: ResultView) => { setResult(r); setScreen('results'); }, []);
+ useEffect(() => { window.scrollTo?.({ top: 0 }); }, [screen]);
+
+ if (screen === 'tutorial') return { store.set(TUTORIAL_KEY, '1'); setScreen('lobby'); }} />;
+ if (screen === 'deck') return setScreen('lobby')}
+ onSave={d => { const ids = d.map(c => c.id); store.set(DECK_KEY, JSON.stringify(ids)); setSavedIds(ids); setScreen('lobby'); }} />;
+ if (screen === 'match') return ;
+ if (screen === 'results' && result) return setScreen('lobby')} />;
+
+ return
+
+
PLAY · OFF-CHAIN MATCHES
Play WikiDeck
+
{account
+ ? <>{account.avatar ?
:
}
{account.name} {logout &&
Log out }>
+ : <>
Guest {ssoAvailable ? 'Sign in with eom.dev' : 'eom.dev sign-in soon'} >}
+
+
+ Three lanes, six turns, win two lanes. New here? You already have a loaner starter deck. Matches never move or burn your cards.
+
+ Mode
+
+ {modes.map(m =>
setModeId(m.id)}>
+ {m.host.kind === 'local' ? : }
+ {m.name} {m.description}
+ {m.host.kind === 'local' ? 'Built in · plays in your browser' : `Hosted by ${m.host.name}`}{m.players !== undefined ? ` · ${m.players} playing` : ''}
+ )}
+ {status === 'loading' &&
Looking for peer-hosted modes…
}
+ {status === 'unavailable' &&
No peer-hosted modes on this node yet.
}
+
+ {mode.host.kind === 'peer' && Peer modes use their host’s rules. For now the match runs in your browser{engine.mock ? ' on the preview engine' : ''}.
}
+
+ Opponent
+ {BOTS.map(b => setBot(b)}>{b.name} bot )}
+
+ Deck {deck.length}
+ setScreen('deck')} aria-label="Edit deck">
+ {deck.slice(0, 4).map(c => )}
+ {savedIds ? 'Your deck' : 'Starter deck'} {deck.filter(c => c.source === 'nft').length} NFTs · {deck.filter(c => c.source === 'starter').length} loaners
+
+
+ {problem && {problem} Edit your deck to play {mode.name}.
}
+
+
+
+
setScreen('tutorial')}> How to play
+
Play vs {bot.name}
+
+
+ {engine.mock && Preview rules engine. The final rules arrive with the game engine.
}
+ ;
+}
diff --git a/src/game/Results.tsx b/src/game/Results.tsx
new file mode 100644
index 0000000..1d74cdf
--- /dev/null
+++ b/src/game/Results.tsx
@@ -0,0 +1,24 @@
+import { ArrowLeft, RotateCcw, Trophy } from 'lucide-react';
+import type { ResultView } from './types.ts';
+
+export function Results({ result, modeName, onRematch, onLobby }: { result: ResultView; modeName: string; onRematch: () => void; onLobby: () => void }) {
+ const outcome = result.winner === null ? 'draw' : result.winner === 0 ? 'win' : 'loss';
+ const won = result.lanes.filter(l => l.winner === 0).length;
+ return
+
+ {modeName.toUpperCase()} · {result.turns} TURNS
+ {outcome === 'win' ? 'Victory!' : outcome === 'loss' ? 'Defeat' : 'Draw'}
+ {result.reason === 'concede' ? (outcome === 'win' ? 'Your opponent conceded.' : 'You conceded.')
+ : `You won ${won} of ${result.lanes.length} lanes.`}
+
+ {result.lanes.map(l =>
+ {l.name} {l.myPower} – {l.theirPower} {l.winner === 0 ? 'Won' : l.winner === 1 ? 'Lost' : 'Tied'}
+ )}
+
+ Matches are off-chain. No card was moved or burned.
+
+ ;
+}
diff --git a/src/game/Tutorial.tsx b/src/game/Tutorial.tsx
new file mode 100644
index 0000000..a988cca
--- /dev/null
+++ b/src/game/Tutorial.tsx
@@ -0,0 +1,45 @@
+import { useState } from 'react';
+import { ArrowLeft, ArrowRight, Check } from 'lucide-react';
+import { GameCard } from './GameCard.tsx';
+import { starterDeck } from './cards.ts';
+
+const demo = starterDeck();
+const STEPS = [
+ { title: 'Win two of three lanes', body: 'The board has three lanes. When the last turn ends, whoever has more power in a lane wins it. Win two lanes to win the match.',
+ show: 'lanes' },
+ { title: 'Every card shows three things', body: 'The top-left number is cost: the energy it takes to play. The top-right number is power. The label at the bottom is its keyword: tap any card on the board to read what it does.',
+ show: 'card' },
+ { title: 'Energy grows each turn', body: 'You get 1 energy on turn 1, 2 on turn 2, and so on up to 6. Energy you don’t spend is lost. Big famous articles cost more, so weigh them against cheaper cards.',
+ show: 'energy' },
+ { title: 'Tap a card, then tap a lane', body: 'Tap a card in your hand to pick it up, then tap a lane to play it there. Tap a played card again before ending the turn to take it back. Each lane holds up to 4 of your cards.',
+ show: 'play' },
+ { title: 'Both players reveal together', body: 'Plays stay face down until both players press End turn. Then everything is revealed and keywords trigger. Your opponent can’t see what you planned, so bluff!',
+ show: 'reveal' },
+ { title: 'Lanes have portals', body: 'Each lane has a Wiki portal that changes the rules there, for example “Science cards here get +2 power.” Read the portal under each lane name.',
+ show: 'portal' },
+];
+
+export function Tutorial({ onDone }: { onDone: () => void }) {
+ const [i, setI] = useState(0);
+ const step = STEPS[i];
+ return
+ HOW TO PLAY · {i + 1} / {STEPS.length}
+ {step.title}
+
+ {step.show === 'lanes' &&
{['Left', 'Middle', 'Right'].map((n, k) =>
{n} {k === 1 ? '4 – 7' : k === 0 ? '9 – 5' : '6 – 3'}
)}
}
+ {step.show === 'card' &&
2 cost3 powerRally keyword}
+ {step.show === 'energy' &&
{[1, 2, 3, 4, 5, 6].map(n => {n} )}
}
+ {step.show === 'play' &&
}
+ {step.show === 'reveal' &&
}
+ {step.show === 'portal' &&
Portal: ScienceScience cards here get +2 power.
}
+
+ {step.body}
+
+
setI(i - 1)} disabled={i === 0}> Back
+ {i < STEPS.length - 1
+ ?
setI(i + 1)}>Next
+ :
Got it}
+
+ Skip tutorial
+ ;
+}
diff --git a/src/game/adapter.ts b/src/game/adapter.ts
new file mode 100644
index 0000000..665115a
--- /dev/null
+++ b/src/game/adapter.ts
@@ -0,0 +1,13 @@
+// The single place the Play UI touches an engine. Swap mockEngine for the shared/game adapter here.
+import { mockEngine } from './mock/engine.ts';
+import type { EngineAdapter, GameMode, Ruleset } from './types.ts';
+
+export const engine: EngineAdapter = mockEngine;
+
+export const STANDARD_RULESET: Ruleset = {
+ id: 'standard', name: 'Standard', description: 'Three lanes, six turns. Win two lanes.',
+ maxTurns: 6, deckSize: 12, handSize: 3, laneCount: 3, laneCapacity: 4, maxCopies: 2,
+};
+export const LOCAL_MODES: GameMode[] = [
+ { id: 'standard', name: 'Standard', description: STANDARD_RULESET.description, host: { kind: 'local' }, ruleset: STANDARD_RULESET },
+];
diff --git a/src/game/bots.ts b/src/game/bots.ts
new file mode 100644
index 0000000..0249561
--- /dev/null
+++ b/src/game/bots.ts
@@ -0,0 +1,16 @@
+// AI opponents. ui-b owns the real easy/normal bots; this file is the plug-in point.
+import type { MatchView, UIAction } from './types.ts';
+
+export type Bot = { id: string; name: string; choose(view: MatchView, legal: UIAction[], rand: () => number): UIAction };
+
+/** Placeholder: plays random affordable cards into random open lanes, then ends the turn. */
+export const randomBot: Bot = {
+ id: 'random', name: 'Random',
+ choose(_view, legal, rand) {
+ const plays = legal.filter(a => a.type === 'play');
+ if (plays.length && rand() < 0.85) return plays[Math.floor(rand() * plays.length)];
+ return { type: 'endTurn' };
+ },
+};
+
+export const BOTS: Bot[] = [randomBot];
diff --git a/src/game/cards.ts b/src/game/cards.ts
new file mode 100644
index 0000000..3b9a24c
--- /dev/null
+++ b/src/game/cards.ts
@@ -0,0 +1,54 @@
+import { rarity } from '../../shared/protocol.ts';
+import type { TestnetBlock } from '../../shared/testnet.ts';
+import type { UICard } from './types.ts';
+
+export const CATEGORIES = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const;
+
+/** Mock keywords, one per category. The real list comes from shared/game (DESIGN.md). */
+export const MOCK_KEYWORDS: Record = {
+ Space: { id: 'orbit', name: 'Orbit', text: 'On reveal: +1 power to your other cards in this lane.' },
+ Nature: { id: 'grow', name: 'Grow', text: 'At the end of each turn: +1 power.' },
+ People: { id: 'rally', name: 'Rally', text: 'On reveal: +2 power if you already have a card here.' },
+ Science: { id: 'cite', name: 'Cite', text: 'On reveal: draw a card.' },
+ History: { id: 'legacy', name: 'Legacy', text: 'On reveal: +2 power if played on turn 1–3.' },
+ Culture: { id: 'viral', name: 'Viral', text: 'On reveal: +3 power if you are behind in this lane.' },
+};
+
+// Curated loaner cards: offline previews, not NFTs. Same power budget as an average owned deck.
+const LOANERS: [number, string, string, number, number][] = [
+ [19331, 'Moon', 'Space', 1, 2], [22780, 'Octopus', 'Nature', 1, 2], [23053, 'Periodic table', 'Science', 1, 1],
+ [736, 'Albert Einstein', 'People', 2, 3], [13692, 'History of writing', 'History', 2, 2], [18978754, 'Jazz', 'Culture', 2, 3],
+ [26751, 'Saturn', 'Space', 3, 4], [9228, 'Earth', 'Nature', 3, 4], [5180, 'Chemistry', 'Science', 3, 3],
+ [14532, 'Isaac Newton', 'People', 4, 6], [13275, 'Roman Empire', 'History', 4, 5], [20484, 'Music', 'Culture', 5, 8],
+ [1966, 'Ancient Egypt', 'History', 5, 7], [33083, 'Volcano', 'Nature', 6, 10],
+];
+
+
+export function starterDeck(): UICard[] {
+ return LOANERS.slice(0, 12).map(([pageId, title, category, cost, power], i) => ({
+ id: `starter-${i}`, pageId, title, category, cost, power, basePower: power,
+ keyword: MOCK_KEYWORDS[category], source: 'starter',
+ }));
+}
+export function loanerPool(): UICard[] {
+ return LOANERS.map(([pageId, title, category, cost, power], i) => ({
+ id: `starter-${i}`, pageId, title, category, cost, power, basePower: power,
+ keyword: MOCK_KEYWORDS[category], source: 'starter',
+ }));
+}
+
+/**
+ * Mock NFT → card mapping (cost from overall stat level, power scales with cost: a sidegrade).
+ * Replaced by the engine's cardFromNft() once it lands; never trust raw snapshot stats for power.
+ */
+export function cardFromBlock(block: TestnetBlock): UICard {
+ const s = block.statsSnapshot?.stats;
+ const avg = s ? ((s.attention ?? 30) + s.depth + s.reach) / 3 : 50;
+ const cost = Math.max(1, Math.min(6, Math.round((avg - 20) / 12)));
+ const tier = rarity(block.powHash);
+ const power = cost * 2 - (cost > 3 ? 1 : 0) + (tier === 'Legendary' ? 1 : 0);
+ const category = CATEGORIES.includes(block.article.category as never) ? block.article.category : 'Culture';
+ return { id: `nft-${block.tokenId}`, pageId: block.article.pageId, title: block.article.title, category,
+ image: block.article.image, cost, power, basePower: power, keyword: MOCK_KEYWORDS[category],
+ source: 'nft', tokenId: block.tokenId, rarity: tier };
+}
diff --git a/src/game/mock/engine.ts b/src/game/mock/engine.ts
new file mode 100644
index 0000000..f0fb108
--- /dev/null
+++ b/src/game/mock/engine.ts
@@ -0,0 +1,156 @@
+// Stand-in 3-lane engine so the UI can be built before shared/game lands. Deterministic from a seed.
+// Not the real rules: DESIGN.md / shared/game are authoritative.
+import type { EngineAdapter, LaneView, MatchView, PlayerIndex, ResultView, Ruleset, UIAction, UICard } from '../types.ts';
+
+type Player = { deck: UICard[]; hand: UICard[]; energy: number; staged: { card: UICard; lane: number }[]; ended: boolean };
+type Modifier = { name: string; text: string; category?: string; bonus: number };
+type Lane = { name: string; modifier: Modifier; cards: [UICard[], UICard[]]; playedTurn: Record };
+export type MockState = {
+ ruleset: Ruleset; rng: number; turn: number; first: PlayerIndex;
+ players: [Player, Player]; lanes: Lane[]; log: string[]; over: boolean; conceded?: PlayerIndex;
+};
+
+const LANE_POOL: Modifier[] = [
+ { name: 'Portal: Science', text: 'Science cards here get +2 power.', category: 'Science', bonus: 2 },
+ { name: 'Portal: Space', text: 'Space cards here get +2 power.', category: 'Space', bonus: 2 },
+ { name: 'Portal: Nature', text: 'Nature cards here get +2 power.', category: 'Nature', bonus: 2 },
+ { name: 'Portal: People', text: 'People cards here get +2 power.', category: 'People', bonus: 2 },
+ { name: 'Portal: History', text: 'History cards here get +2 power.', category: 'History', bonus: 2 },
+ { name: 'Featured article', text: 'Every card here gets +1 power.', bonus: 1 },
+ { name: 'Stub', text: 'No effect. A blank page.', bonus: 0 },
+];
+const LANE_NAMES = ['Left', 'Middle', 'Right'];
+
+function hashSeed(seed: string): number {
+ let h = 2166136261;
+ for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 16777619);
+ return h >>> 0;
+}
+function next(state: { rng: number }): number { // mulberry32
+ let t = (state.rng = (state.rng + 0x6d2b79f5) >>> 0);
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+}
+function shuffle(state: { rng: number }, items: T[]): T[] {
+ const a = [...items];
+ for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(next(state) * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
+ return a;
+}
+const bonusFor = (lane: Lane, card: UICard) => !lane.modifier.category || lane.modifier.category === card.category ? lane.modifier.bonus : 0;
+const lanePower = (lane: Lane, p: PlayerIndex) => lane.cards[p].reduce((sum, c) => sum + c.power + bonusFor(lane, c), 0);
+const other = (p: PlayerIndex): PlayerIndex => (p === 0 ? 1 : 0);
+
+function draw(player: Player) { const card = player.deck.shift(); if (card) player.hand.push(card); }
+
+function reveal(s: MockState) {
+ const order: PlayerIndex[] = [s.first, other(s.first)];
+ for (const p of order) {
+ for (const { card, lane: li } of s.players[p].staged) {
+ const lane = s.lanes[li];
+ const hadCard = lane.cards[p].length > 0;
+ lane.cards[p].push(card);
+ lane.playedTurn[card.id] = s.turn;
+ const k = card.keyword?.id;
+ if (k === 'orbit') lane.cards[p].forEach(c => { if (c !== card) c.power += 1; });
+ if (k === 'rally' && hadCard) card.power += 2;
+ if (k === 'cite') draw(s.players[p]);
+ if (k === 'legacy' && s.turn <= 3) card.power += 2;
+ if (k === 'viral' && lanePower(lane, p) < lanePower(lane, other(p))) card.power += 3;
+ s.log.push(`${p === 0 ? 'P1' : 'P2'} played ${card.title} → ${lane.name}${card.power !== card.basePower ? ` (${card.keyword?.name} ${card.power - card.basePower >= 0 ? '+' : ''}${card.power - card.basePower})` : ''}`);
+ }
+ s.players[p].staged = [];
+ }
+ for (const lane of s.lanes) for (const p of [0, 1] as PlayerIndex[])
+ for (const c of lane.cards[p]) if (c.keyword?.id === 'grow') c.power += 1;
+}
+
+function endRound(s: MockState) {
+ reveal(s);
+ if (s.turn >= s.ruleset.maxTurns) { s.over = true; s.log.push('Final turn complete.'); return; }
+ s.turn += 1;
+ s.first = other(s.first);
+ for (const p of s.players) { draw(p); p.energy = Math.min(s.turn, 6); p.ended = false; }
+ s.log.push(`Turn ${s.turn}.`);
+}
+
+export const mockEngine: EngineAdapter = {
+ name: 'mock lanes v0', mock: true,
+ createMatch(ruleset, decks, seed) {
+ const rng = { rng: hashSeed(seed) };
+ const tag = (deck: UICard[], p: number) => deck.map((c, i) => ({ ...c, id: `p${p}-${i}-${c.id}`, power: c.basePower }));
+ const players = decks.map((d, p) => {
+ const deck = shuffle(rng, tag(d, p));
+ return { deck: deck.slice(ruleset.handSize), hand: deck.slice(0, ruleset.handSize), energy: 1, staged: [], ended: false };
+ }) as unknown as [Player, Player];
+ const mods = shuffle(rng, LANE_POOL).slice(0, ruleset.laneCount);
+ const lanes = mods.map((modifier, i) => ({ name: LANE_NAMES[i] ?? `Lane ${i + 1}`, modifier, cards: [[], []] as [UICard[], UICard[]], playedTurn: {} }));
+ const first = (next(rng) < 0.5 ? 0 : 1) as PlayerIndex;
+ return { ruleset, rng: rng.rng, turn: 1, first, players, lanes, log: ['Turn 1.'], over: false };
+ },
+ legal(s, p) {
+ if (s.over) return [];
+ const me = s.players[p];
+ if (me.ended) return [];
+ const acts: UIAction[] = [{ type: 'endTurn' }, { type: 'concede' }];
+ for (const { card } of me.staged) acts.push({ type: 'unstage', cardId: card.id });
+ for (const card of me.hand) if (card.cost <= me.energy)
+ s.lanes.forEach((lane, li) => {
+ const used = lane.cards[p].length + me.staged.filter(x => x.lane === li).length;
+ if (used < s.ruleset.laneCapacity) acts.push({ type: 'play', cardId: card.id, lane: li });
+ });
+ return acts;
+ },
+ apply(prev, p, action) {
+ const s: MockState = structuredClone(prev);
+ const me = s.players[p];
+ if (s.over || me.ended) throw new Error('Not your turn');
+ if (action.type === 'concede') { s.over = true; s.conceded = p; s.log.push(`${p === 0 ? 'P1' : 'P2'} conceded.`); return s; }
+ if (action.type === 'play') {
+ const ok = mockEngine.legal(prev, p).some(a => a.type === 'play' && a.cardId === action.cardId && a.lane === action.lane);
+ if (!ok) throw new Error('Illegal play');
+ const i = me.hand.findIndex(c => c.id === action.cardId);
+ const [card] = me.hand.splice(i, 1);
+ me.energy -= card.cost;
+ me.staged.push({ card, lane: action.lane });
+ } else if (action.type === 'unstage') {
+ const i = me.staged.findIndex(x => x.card.id === action.cardId);
+ if (i < 0) throw new Error('Not staged');
+ const [{ card }] = me.staged.splice(i, 1);
+ me.energy += card.cost;
+ me.hand.push(card);
+ } else if (action.type === 'endTurn') {
+ me.ended = true;
+ if (s.players.every(x => x.ended)) endRound(s);
+ }
+ return s;
+ },
+ view(s, p): MatchView {
+ const me = s.players[p], them = s.players[other(p)];
+ const lanes: LaneView[] = s.lanes.map((lane, i) => {
+ const withBonus = (c: UICard) => ({ ...c, power: c.power + bonusFor(lane, c) });
+ return { index: i, name: lane.name, modifier: { name: lane.modifier.name, text: lane.modifier.text }, revealed: true,
+ mine: lane.cards[p].map(withBonus), theirs: lane.cards[other(p)].map(withBonus),
+ staged: me.staged.filter(x => x.lane === i).map(x => withBonus(x.card)),
+ myPower: lanePower(lane, p), theirPower: lanePower(lane, other(p)), capacity: s.ruleset.laneCapacity };
+ });
+ return { me: p, turn: s.turn, maxTurns: s.ruleset.maxTurns, energy: me.energy, maxEnergy: Math.min(s.turn, 6),
+ hand: me.hand, deckCount: me.deck.length, oppHandCount: them.hand.length, oppDeckCount: them.deck.length,
+ lanes, log: s.log.slice(-30), waitingForOpponent: me.ended && !s.over, over: s.over };
+ },
+ isOver: s => s.over,
+ result(s, p): ResultView {
+ const lanes = s.lanes.map(l => {
+ const a = lanePower(l, p), b = lanePower(l, other(p));
+ return { name: l.name, myPower: a, theirPower: b, winner: a === b ? null : a > b ? p : other(p) };
+ });
+ if (s.conceded !== undefined) return { winner: other(s.conceded), lanes, turns: s.turn, reason: 'concede' };
+ const mine = lanes.filter(l => l.winner === p).length, theirs = lanes.filter(l => l.winner === other(p)).length;
+ let winner: PlayerIndex | null = mine > theirs ? p : theirs > mine ? other(p) : null;
+ if (winner === null) { // tiebreak: total power
+ const ta = lanes.reduce((x, l) => x + l.myPower, 0), tb = lanes.reduce((x, l) => x + l.theirPower, 0);
+ winner = ta === tb ? null : ta > tb ? p : other(p);
+ }
+ return { winner, lanes, turns: s.turn, reason: 'lanes' };
+ },
+};
diff --git a/src/game/play.css b/src/game/play.css
new file mode 100644
index 0000000..2efd1bb
--- /dev/null
+++ b/src/game/play.css
@@ -0,0 +1,172 @@
+/* Play section. Mobile-first: 360px minimum, thumb-reachable bottom dock, no hover-only states. */
+.play-panel{max-width:760px;margin:0 auto 32px;padding:20px 16px 0;border:1px solid var(--theme-border);background:var(--ctp-mantle);border-radius:14px;color:var(--ctp-text)}
+.play-panel h2{font-size:26px;letter-spacing:-.6px;margin:4px 0 8px;display:flex;align-items:center;flex-wrap:wrap;gap:8px}
+.play-panel .count-badge{margin-left:0}
+.play-panel .count-badge.ok{color:var(--ctp-green);border-color:var(--ctp-green)}
+.play-panel .muted{font-size:13px;line-height:1.6;color:var(--ctp-subtext0)}
+.play-panel .muted.small,.small{font-size:11px}
+.play-panel .section-eyebrow{font-size:10px}
+.play-actions{display:flex;gap:10px;flex-wrap:wrap;justify-content:flex-end}
+.play-actions .button{min-height:48px;font-size:13px;padding:12px 16px;flex:1 1 auto}
+.play-actions .button.outline{flex:0 1 auto}
+.play-actions .button:disabled{opacity:.45;cursor:not-allowed}
+.play-dock{position:sticky;bottom:0;z-index:5;margin:18px -16px 0;padding:10px 16px calc(12px + env(safe-area-inset-bottom));background:var(--ctp-mantle);border-top:1px solid var(--theme-border);border-radius:0 0 14px 14px}
+.dock-note{min-height:20px;margin:0 0 8px;font-size:12px;color:var(--ctp-subtext1);display:flex;align-items:center;gap:6px;line-height:1.35}
+.dock-error{color:var(--ctp-red)}
+.icon-button{display:inline-flex;align-items:center;justify-content:center;min-width:40px;min-height:40px;border-radius:8px;background:var(--ctp-surface0);color:var(--ctp-subtext1)}
+
+/* Card faces */
+.gcard{position:relative;display:flex;flex-direction:column;align-items:stretch;text-align:left;background:var(--ctp-base);color:var(--ctp-text);border:1.5px solid var(--ctp-surface1);border-radius:10px;padding:0;overflow:hidden;transition:transform .15s ease,border-color .15s ease,box-shadow .15s ease;--cat:var(--ctp-overlay1)}
+.gcard:disabled{cursor:default;opacity:1}
+.gcard.cat-space{--cat:var(--ctp-lavender)}.gcard.cat-nature{--cat:var(--ctp-green)}.gcard.cat-people{--cat:var(--ctp-peach)}
+.gcard.cat-science{--cat:var(--ctp-sky)}.gcard.cat-history{--cat:var(--ctp-yellow)}.gcard.cat-culture{--cat:var(--ctp-pink)}
+.gcard-art{display:flex;align-items:center;justify-content:center;height:46px;background:color-mix(in srgb,var(--cat) 28%,var(--ctp-surface0));color:var(--cat);position:relative;overflow:hidden}
+.gcard-art img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
+.gcard-art svg{position:relative}
+.gcard-cost,.gcard-power{position:absolute;top:4px;z-index:2;min-width:24px;height:24px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:14px;box-shadow:0 1px 3px rgb(0 0 0/.35)}
+.gcard-cost{left:4px;background:var(--ctp-blue);color:var(--ctp-crust)}
+.gcard-power{right:4px;background:var(--ctp-peach);color:var(--ctp-crust);border-radius:6px}
+.gcard-power.up{background:var(--ctp-green)}.gcard-power.down{background:var(--ctp-red)}
+.gcard-title{font-size:12px;font-weight:700;line-height:1.2;padding:6px 7px 2px;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;min-height:2.4em}
+.gcard-keyword{display:flex;align-items:center;gap:3px;margin:auto 6px 6px;font-size:10px;font-weight:700;color:var(--cat);text-transform:uppercase;letter-spacing:.4px}
+.gcard-nft{position:absolute;top:32px;right:4px;font-size:8px;font-weight:800;padding:1px 4px;border-radius:3px;background:var(--ctp-mauve);color:var(--ctp-crust)}
+.gcard-hand,.gcard-deck{width:88px;min-height:118px;flex:0 0 auto}
+.gcard-deck{width:auto}
+.gcard-board{width:100%;min-height:0;border-radius:7px;border-width:1px;flex-direction:row;align-items:center}
+.gcard-board .gcard-art{width:22px;height:30px;flex:0 0 22px}
+.gcard-board .gcard-art img{display:none}
+.gcard-board .gcard-cost{display:none}
+.gcard-board .gcard-power{position:static;margin:0 3px 0 auto;min-width:22px;height:22px;font-size:12px;flex:0 0 auto;box-shadow:none}
+.gcard-board .gcard-title{font-size:10px;padding:2px 4px;min-height:0;-webkit-line-clamp:1;display:block;white-space:nowrap;text-overflow:ellipsis;flex:1 1 auto;min-width:0}
+.gcard.is-selected{border-color:var(--theme-accent);box-shadow:0 0 0 2px var(--theme-accent);transform:translateY(-6px)}
+.gcard-board.is-selected{transform:none;border-style:dashed;box-shadow:none;opacity:.85}
+.gcard.is-dim{opacity:.45}
+.gcard.is-fresh{animation:gcard-reveal .45s ease-out}
+@keyframes gcard-reveal{0%{transform:scale(.6) rotateY(90deg);opacity:0}100%{transform:none;opacity:1}}
+.gcard:focus-visible{outline:2px solid var(--theme-accent);outline-offset:2px}
+
+/* Lobby */
+.lobby-head{display:flex;justify-content:space-between;align-items:flex-start;gap:10px;flex-wrap:wrap}
+.account-chip{display:flex;align-items:center;gap:8px;padding:6px 10px;border-radius:999px;background:var(--ctp-surface0);font-size:12px;color:var(--ctp-subtext1)}
+.account-chip img{width:22px;height:22px;border-radius:50%}
+.account-chip .text-button{font-size:11px;padding:4px 0;color:var(--theme-accent)}
+.account-chip .text-button:disabled{color:var(--ctp-overlay1);cursor:default}
+.lobby-label{font-size:12px;letter-spacing:1px;text-transform:uppercase;color:var(--ctp-subtext0);margin:20px 0 8px;display:flex;gap:8px;align-items:center}
+.mode-list{display:grid;gap:8px}
+.mode{display:flex;gap:12px;align-items:flex-start;text-align:left;padding:12px;border-radius:10px;border:1.5px solid var(--theme-border);background:var(--ctp-base);color:var(--ctp-text);min-height:56px}
+.mode.selected{border-color:var(--theme-accent);background:color-mix(in srgb,var(--theme-accent) 10%,var(--ctp-base))}
+.mode-icon{flex:0 0 36px;height:36px;border-radius:8px;display:flex;align-items:center;justify-content:center;background:var(--ctp-surface0);color:var(--theme-accent)}
+.mode-copy{display:flex;flex-direction:column;gap:2px;min-width:0}
+.mode-copy b{font-size:14px}.mode-copy small{font-size:12px;color:var(--ctp-subtext0);line-height:1.4}
+.mode-copy .mode-host{color:var(--ctp-overlay2);font-size:11px}
+.play-panel .category-tabs{display:flex;gap:6px;flex-wrap:wrap}
+.play-panel .category-tabs button{font-size:13px;padding:10px 14px;min-height:40px;border:1px solid var(--theme-border)}
+.deck-summary{width:100%;display:flex;align-items:center;gap:14px;padding:12px;border-radius:10px;border:1.5px solid var(--theme-border);background:var(--ctp-base);color:var(--ctp-text);text-align:left}
+.deck-summary>span:nth-child(2){display:flex;flex-direction:column;flex:1;font-size:14px}
+.deck-summary small{color:var(--ctp-subtext0);font-size:12px}
+.deck-fan{display:flex;flex:0 0 auto}
+.fan-chip{width:30px;height:42px;border-radius:6px;margin-left:-12px;display:flex;align-items:center;justify-content:center;border:1.5px solid var(--ctp-surface1);background:color-mix(in srgb,var(--cat) 30%,var(--ctp-surface0));color:var(--cat);transform:rotate(calc(var(--i,0)*4deg - 6deg));--cat:var(--ctp-overlay1)}
+.fan-chip:first-child{margin-left:0}
+.fan-chip.cat-space{--cat:var(--ctp-lavender)}.fan-chip.cat-nature{--cat:var(--ctp-green)}.fan-chip.cat-people{--cat:var(--ctp-peach)}.fan-chip.cat-science{--cat:var(--ctp-sky)}.fan-chip.cat-history{--cat:var(--ctp-yellow)}.fan-chip.cat-culture{--cat:var(--ctp-pink)}
+.play-cta{font-size:15px!important}
+.engine-note{text-align:center;padding-bottom:10px}
+
+/* Deck builder */
+.deck-curve{display:flex;gap:6px;align-items:flex-end;height:70px;margin:10px 0}
+.deck-curve>div{flex:1;display:flex;flex-direction:column;align-items:center;height:100%;justify-content:flex-end;gap:2px;font-size:10px;color:var(--ctp-subtext0)}
+.deck-curve span{width:100%;max-width:34px;background:var(--theme-accent);border-radius:4px 4px 0 0;min-height:2px;transition:height .2s}
+.deck-strip{display:grid;grid-template-columns:repeat(auto-fill,minmax(104px,1fr));gap:5px;margin-bottom:14px}
+.pool-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(96px,1fr));gap:10px;margin-top:12px}
+.pool-grid .gcard.is-selected{transform:none}
+
+/* Match */
+.match{max-width:760px;margin:0 auto 24px;display:flex;flex-direction:column;border:1px solid var(--theme-border);border-radius:14px;background:var(--ctp-mantle);color:var(--ctp-text);position:relative}
+.match-bar{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:8px 10px;border-bottom:1px solid var(--theme-border);font-size:12px;color:var(--ctp-subtext1)}
+.match-bar>span{display:inline-flex;align-items:center;gap:5px}
+.match-turn b{font-size:16px;color:var(--ctp-text)}
+.turn-banner{position:absolute;top:56px;left:50%;transform:translateX(-50%);z-index:8;background:var(--theme-accent);color:var(--ctp-crust);padding:8px 18px;border-radius:999px;font-weight:800;font-size:14px;white-space:nowrap;animation:banner-in 1.4s ease both;pointer-events:none}
+@keyframes banner-in{0%{opacity:0;transform:translate(-50%,-8px)}15%,80%{opacity:1;transform:translate(-50%,0)}100%{opacity:0}}
+.lanes{display:grid;gap:6px;padding:8px}
+.lane{display:flex;flex-direction:column;gap:4px;min-width:0;border-radius:10px;padding:4px;background:var(--ctp-base);border:1.5px solid transparent;transition:border-color .15s,background .15s}
+.lane.is-target{border-color:var(--theme-accent);background:color-mix(in srgb,var(--theme-accent) 12%,var(--ctp-base))}
+.lane.is-blocked{opacity:.6}
+.lane-side{display:flex;flex-direction:column;gap:3px;min-height:120px}
+.lane-side.theirs{justify-content:flex-end}
+.lane-plate{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:4px;padding:8px 4px;border-radius:8px;background:var(--ctp-surface0);color:var(--ctp-text);min-height:52px}
+.lane-name{font-size:10px;line-height:1.2;text-align:center;color:var(--ctp-subtext1);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
+.lane-score{font-weight:800;font-size:17px;min-width:24px;text-align:center}
+.lane-score.theirs{color:var(--ctp-red)}.lane-score.mine{color:var(--ctp-green)}
+.lane-plate.ahead{box-shadow:inset 0 -3px 0 var(--ctp-green)}.lane-plate.behind{box-shadow:inset 0 3px 0 var(--ctp-red)}
+.lane-drop{border:1.5px dashed var(--theme-accent);border-radius:7px;color:var(--theme-accent);font-size:11px;font-weight:700;text-align:center;padding:6px 2px}
+.match-dock{margin:0;border-radius:0 0 14px 14px;padding-inline:10px}
+.hand{display:flex;gap:8px;overflow-x:auto;padding:8px 2px 6px;scroll-snap-type:x proximity;-webkit-overflow-scrolling:touch}
+.hand .gcard{scroll-snap-align:start}
+.dock-row{display:flex;align-items:center;gap:12px;margin-top:4px}
+.energy{display:flex;align-items:center;gap:3px}
+.energy i{width:10px;height:18px;border-radius:3px;background:var(--ctp-surface1)}
+.energy i.on{background:var(--ctp-blue)}
+.energy b{font-size:18px;margin-left:5px;color:var(--ctp-blue)}
+.deck-count{display:inline-flex;gap:4px;align-items:center;font-size:12px;color:var(--ctp-subtext0)}
+.end-turn{margin-left:auto;min-height:52px!important;min-width:132px;font-size:15px!important}
+.end-turn:disabled{opacity:.55}
+
+/* Bottom sheet (details instead of hover tooltips) */
+.sheet-backdrop{position:fixed;inset:0;z-index:40;background:var(--theme-scrim,rgb(0 0 0/.5));display:flex;align-items:flex-end;justify-content:center}
+.sheet{position:relative;width:100%;max-width:520px;background:var(--ctp-mantle);color:var(--ctp-text);border-radius:16px 16px 0 0;padding:22px 18px calc(18px + env(safe-area-inset-bottom));animation:sheet-up .18s ease-out;max-height:80vh;overflow:auto}
+.sheet h3{font-size:20px;margin:6px 0}
+.sheet p{font-size:14px;line-height:1.55}
+.sheet-card{display:flex;justify-content:center}
+.sheet-card .gcard{width:120px;min-height:150px}
+@keyframes sheet-up{from{transform:translateY(40px);opacity:0}to{transform:none;opacity:1}}
+
+/* Results */
+.results{text-align:center}
+.results h2{justify-content:center;font-size:34px}
+.results .section-eyebrow{justify-content:center}
+.result-mark{margin:8px auto 14px;width:64px;height:64px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:var(--ctp-surface0);color:var(--ctp-overlay2)}
+.results.win .result-mark{background:var(--ctp-yellow);color:var(--ctp-crust);animation:pop .4s ease-out}
+.results.loss .result-mark{color:var(--ctp-red)}
+@keyframes pop{0%{transform:scale(.4)}70%{transform:scale(1.1)}100%{transform:none}}
+.result-lanes{list-style:none;padding:0;display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:18px 0}
+.result-lanes li{display:flex;flex-direction:column;gap:2px;padding:12px 4px;border-radius:10px;background:var(--ctp-base);border:1.5px solid var(--theme-border)}
+.result-lanes li.won{border-color:var(--ctp-green)}.result-lanes li.lost{border-color:var(--ctp-red)}
+.result-lanes b{font-size:20px}.result-lanes small,.result-lanes span{font-size:11px;color:var(--ctp-subtext0)}
+
+/* Tutorial */
+.tutorial p{font-size:14px;line-height:1.6}
+.tutorial-visual{min-height:150px;display:flex;align-items:center;justify-content:center;margin:12px 0;padding:12px;border-radius:12px;background:var(--ctp-base)}
+.tut-lanes{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;width:100%}
+.tut-lanes div{display:flex;flex-direction:column;align-items:center;padding:16px 4px;border-radius:8px;background:var(--ctp-surface0);font-size:12px}
+.tut-lanes b{font-size:18px}.tut-lanes .won{box-shadow:inset 0 -3px 0 var(--ctp-green)}.tut-lanes .lost{box-shadow:inset 0 3px 0 var(--ctp-red)}
+.tut-card{display:flex;align-items:center;gap:14px;flex-wrap:wrap;justify-content:center}
+.tut-card ul{list-style:none;padding:0;margin:0;font-size:13px;line-height:1.9}
+.tut-energy{display:flex;align-items:flex-end;gap:8px;height:90px}
+.tut-energy span{width:26px;border-radius:4px 4px 0 0;background:var(--ctp-blue);color:var(--ctp-crust);font-weight:800;display:flex;justify-content:center;align-items:flex-start;font-size:12px}
+.tut-lane-target{padding:22px 16px;border:2px dashed var(--theme-accent);border-radius:10px;color:var(--theme-accent);font-weight:700;display:flex;flex-direction:column;gap:4px;text-align:center}
+.tut-lane-target small{font-weight:400;color:var(--ctp-subtext0)}
+.tut-facedown{width:60px;height:84px;border-radius:8px;background:repeating-linear-gradient(45deg,var(--ctp-surface0) 0 6px,var(--ctp-surface1) 6px 12px);display:flex;align-items:center;justify-content:center;font-size:22px;font-weight:800;color:var(--ctp-overlay2)}
+.tutorial .skip{display:block;margin:6px auto 12px}
+
+@media(min-width:700px){
+ .gcard-hand{width:104px;min-height:136px}
+ .gcard-art{height:58px}
+ .lane-side{min-height:150px}
+ .gcard-board .gcard-title{font-size:11px}
+ .play-panel{padding:26px 26px 0}.play-dock{margin-inline:-26px;padding-inline:26px}
+}
+@media(max-width:400px){
+ .lanes{gap:4px;padding:6px 4px}
+ .lane{padding:3px}
+ .lane-score{font-size:15px;min-width:18px}
+ .gcard-board .gcard-art{display:none}
+ .end-turn{min-width:112px}
+}
+.gcard-board .gcard-power{order:3}
+/* Phones: the match takes the whole screen so the board and the thumb dock both fit. */
+@media(max-width:760px){
+ .match{position:fixed;inset:0;z-index:30;margin:0;max-width:none;border:0;border-radius:0;padding-top:env(safe-area-inset-top);overflow:hidden}
+ .match .lanes{flex:1 1 auto;overflow-y:auto;align-content:start}
+ .match-dock{position:static;border-radius:0}
+ .lane-side{min-height:84px}
+}
+.deck-warning{color:var(--ctp-yellow)}
diff --git a/src/game/types.ts b/src/game/types.ts
new file mode 100644
index 0000000..03d88cb
--- /dev/null
+++ b/src/game/types.ts
@@ -0,0 +1,94 @@
+// UI-side contract for the Play section. Screens consume only these view models, so swapping the
+// mock engine for shared/game touches adapter.ts alone.
+
+export type PlayerIndex = 0 | 1;
+
+/** A card as the deck builder and match screen display it: at most 3 numbers and 1 keyword. */
+export type UICard = {
+ id: string; // unique within a match/deck (instance id)
+ pageId: number;
+ title: string;
+ category: string;
+ image?: string;
+ cost: number;
+ power: number; // current power (including modifiers on board)
+ basePower: number;
+ keyword?: { id: string; name: string; text: string };
+ source: 'starter' | 'nft';
+ tokenId?: string;
+ rarity?: string;
+};
+
+export type LaneView = {
+ index: number;
+ name: string;
+ modifier?: { name: string; text: string };
+ revealed: boolean;
+ mine: UICard[];
+ theirs: UICard[];
+ staged: UICard[]; // my plays this turn, not yet revealed
+ myPower: number;
+ theirPower: number;
+ capacity: number;
+};
+
+export type MatchView = {
+ me: PlayerIndex;
+ turn: number;
+ maxTurns: number;
+ energy: number; // remaining this turn
+ maxEnergy: number;
+ hand: UICard[];
+ deckCount: number;
+ oppHandCount: number;
+ oppDeckCount: number;
+ lanes: LaneView[];
+ log: string[]; // newest last
+ waitingForOpponent: boolean;
+ over: boolean;
+};
+
+export type UIAction =
+ | { type: 'play'; cardId: string; lane: number }
+ | { type: 'unstage'; cardId: string }
+ | { type: 'endTurn' }
+ | { type: 'concede' };
+
+export type ResultView = {
+ winner: PlayerIndex | null; // null = draw
+ lanes: { name: string; myPower: number; theirPower: number; winner: PlayerIndex | null }[];
+ turns: number;
+ reason: 'lanes' | 'concede' | 'turnCap';
+};
+
+export type Ruleset = {
+ id: string;
+ name: string;
+ description: string;
+ maxTurns: number;
+ deckSize: number;
+ handSize: number;
+ laneCount: number;
+ laneCapacity: number;
+ maxCopies: number;
+};
+
+export type GameMode = {
+ id: string;
+ name: string;
+ description: string;
+ host: { kind: 'local' } | { kind: 'peer'; name: string; url: string };
+ ruleset: Ruleset;
+ players?: number;
+};
+
+export interface EngineAdapter {
+ readonly name: string;
+ readonly mock: boolean;
+ createMatch(ruleset: Ruleset, decks: [UICard[], UICard[]], seed: string): S;
+ legal(state: S, player: PlayerIndex): UIAction[];
+ apply(state: S, player: PlayerIndex, action: UIAction): S;
+ view(state: S, player: PlayerIndex): MatchView;
+ isOver(state: S): boolean;
+ result(state: S, player: PlayerIndex): ResultView;
+}
diff --git a/src/game/useAccount.ts b/src/game/useAccount.ts
new file mode 100644
index 0000000..07965d1
--- /dev/null
+++ b/src/game/useAccount.ts
@@ -0,0 +1,6 @@
+// eom.dev login state. The SSO team (#7) owns the real OIDC client; until it lands this reports
+// signed-out and the lobby shows a disabled "Sign in" chip. Swap this hook's body for theirs.
+export type Account = { name: string; avatar?: string } | null;
+export function useAccount(): { account: Account; available: boolean; login?: () => void; logout?: () => void } {
+ return { account: null, available: false };
+}
diff --git a/src/game/useModes.ts b/src/game/useModes.ts
new file mode 100644
index 0000000..d9fefb9
--- /dev/null
+++ b/src/game/useModes.ts
@@ -0,0 +1,42 @@
+import { useEffect, useState } from 'react';
+import { LOCAL_MODES } from './adapter.ts';
+import type { GameMode } from './types.ts';
+
+// Peer-hosted modes come from this node's GET /api/game/modes (owned by the modes team, #6).
+// The shape is read defensively: anything malformed is skipped, and the built-in mode is always present.
+type Remote = { id?: unknown; name?: unknown; description?: unknown; host?: unknown; hostedBy?: unknown; url?: unknown; players?: unknown; ruleset?: unknown };
+const str = (v: unknown, max = 120) => (typeof v === 'string' ? v.slice(0, max) : undefined);
+
+export function parseModes(data: unknown): GameMode[] {
+ const list = Array.isArray(data) ? data : Array.isArray((data as { modes?: unknown })?.modes) ? (data as { modes: unknown[] }).modes : [];
+ const base = LOCAL_MODES[0].ruleset;
+ return list.slice(0, 50).flatMap((raw): GameMode[] => {
+ if (!raw || typeof raw !== 'object') return [];
+ const m = raw as Remote;
+ const id = str(m.id, 64), name = str(m.name, 60);
+ if (!id || !name) return [];
+ const host = m.host as { name?: unknown; url?: unknown; kind?: unknown } | string | undefined;
+ const hostName = str(typeof host === 'string' ? host : host?.name) ?? str(m.hostedBy) ?? 'this node';
+ const r = (m.ruleset ?? {}) as Record;
+ const num = (k: string, lo: number, hi: number) => typeof r[k] === 'number' && r[k] >= lo && r[k] <= hi ? r[k] as number : (base as Record)[k] as number;
+ return [{ id: `remote:${id}`, name, description: str(m.description, 280) ?? '',
+ host: { kind: 'peer', name: hostName, url: str(typeof host === 'object' ? host?.url : m.url, 200) ?? '' },
+ players: typeof m.players === 'number' ? m.players : undefined,
+ ruleset: { ...base, id, name, maxTurns: num('maxTurns', 3, 12), deckSize: num('deckSize', 6, 30),
+ handSize: num('handSize', 1, 7), laneCount: num('laneCount', 1, 3), laneCapacity: num('laneCapacity', 1, 6), maxCopies: num('maxCopies', 1, 4) } }];
+ });
+}
+
+export function useModes() {
+ const [remote, setRemote] = useState([]);
+ const [status, setStatus] = useState<'loading' | 'ok' | 'unavailable'>('loading');
+ useEffect(() => {
+ let active = true;
+ fetch('/api/game/modes', { cache: 'no-store', signal: AbortSignal.timeout(8000) })
+ .then(r => r.ok && r.headers.get('content-type')?.includes('json') ? r.json() : Promise.reject(new Error('unavailable')))
+ .then(d => { if (active) { setRemote(parseModes(d)); setStatus('ok'); } })
+ .catch(() => { if (active) setStatus('unavailable'); });
+ return () => { active = false; };
+ }, []);
+ return { modes: [...LOCAL_MODES, ...remote], status };
+}
diff --git a/tests/ui-play.test.ts b/tests/ui-play.test.ts
new file mode 100644
index 0000000..530212a
--- /dev/null
+++ b/tests/ui-play.test.ts
@@ -0,0 +1,79 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { engine, STANDARD_RULESET } from '../src/game/adapter.ts';
+import { randomBot } from '../src/game/bots.ts';
+import { loanerPool, starterDeck } from '../src/game/cards.ts';
+import { deckProblem } from '../src/game/DeckBuilder.tsx';
+import { parseModes } from '../src/game/useModes.ts';
+import type { PlayerIndex } from '../src/game/types.ts';
+
+function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
+
+function playOut(seed: string) {
+ let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], seed);
+ const r = rand(seed.length * 7919);
+ for (let steps = 0; steps < 500 && !engine.isOver(s); steps++) {
+ for (const p of [0, 1] as PlayerIndex[]) {
+ const legal = engine.legal(s, p);
+ if (!legal.length) continue;
+ s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal.filter(a => a.type !== 'concede'), r));
+ }
+ }
+ return s;
+}
+
+test('starter deck is a legal Standard deck', () => {
+ assert.equal(deckProblem(starterDeck(), STANDARD_RULESET), '');
+ assert.match(deckProblem(starterDeck().slice(1), STANDARD_RULESET), /exactly 12/);
+ const pool = loanerPool();
+ assert.match(deckProblem([...Array(12)].map(() => pool[0]), STANDARD_RULESET), /copies/);
+});
+
+test('random legal play always terminates within the turn cap and is deterministic', () => {
+ for (let i = 0; i < 60; i++) {
+ const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
+ assert.ok(engine.isOver(a), `match ${i} finished`);
+ const ra = engine.result(a, 0);
+ assert.ok(ra.turns <= STANDARD_RULESET.maxTurns);
+ assert.deepEqual(ra, engine.result(b, 0));
+ const rb = engine.result(a, 1);
+ if (ra.winner !== null) assert.equal(rb.winner, ra.winner);
+ }
+});
+
+test('opponent staged plays stay hidden until reveal', () => {
+ let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], 'hidden');
+ const play = engine.legal(s, 1).find(a => a.type === 'play');
+ assert.ok(play);
+ s = engine.apply(s, 1, play!);
+ const mine = engine.view(s, 0);
+ assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
+ assert.equal(engine.view(s, 1).lanes.flatMap(l => l.staged).length, 1);
+});
+
+test('illegal plays are rejected and unstage refunds energy', () => {
+ let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], 'energy');
+ const v = engine.view(s, 0);
+ const expensive = v.hand.find(c => c.cost > v.energy);
+ if (expensive) assert.throws(() => engine.apply(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
+ const play = engine.legal(s, 0).find(a => a.type === 'play');
+ if (play && play.type === 'play') {
+ s = engine.apply(s, 0, play);
+ assert.ok(engine.view(s, 0).energy < v.energy);
+ s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
+ assert.equal(engine.view(s, 0).energy, v.energy);
+ }
+});
+
+test('peer mode parsing is defensive and clamps rulesets', () => {
+ const modes = parseModes({ modes: [
+ { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), host: { name: 'node-b', url: 'http://n' }, ruleset: { maxTurns: 99, laneCount: 2 } },
+ { name: 'no id' }, 'junk', null,
+ ] });
+ assert.equal(modes.length, 1);
+ assert.equal(modes[0].host.kind, 'peer');
+ assert.equal(modes[0].ruleset.maxTurns, STANDARD_RULESET.maxTurns);
+ assert.equal(modes[0].ruleset.laneCount, 2);
+ assert.ok(modes[0].description.length <= 280);
+ assert.deepEqual(parseModes('nope'), []);
+});
--
2.54.0
From c938407d36a4c9e92ac0c064de95372a965c7464 Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:17:04 -0500
Subject: [PATCH 06/14] Engine tests: viewFor never leaks opponent hand, deck
order, seed or RNG
Co-Authored-By: Claude Opus 5.5
---
tests/game-core.test.ts | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/tests/game-core.test.ts b/tests/game-core.test.ts
index 30b4d60..05a2c81 100644
--- a/tests/game-core.test.ts
+++ b/tests/game-core.test.ts
@@ -99,6 +99,18 @@ test('queued plays are hidden until reveal; undo refunds; committed seats get no
assert.throws(() => applyAction(state, { type: 'play', player: 0, cardId: play.cardId, lane: 0 }), IllegalActionError);
});
+test('viewFor never leaks the opponent hand, deck order, queue, seed or RNG state', () => {
+ let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'mine'), flatDeck(1, 'opp')], 'leak-seed');
+ const play = legalActions(state, 1).find(x => x.type === 'play')!;
+ state = applyAction(state, play);
+ const view = viewFor(state, 0);
+ const json = JSON.stringify(view);
+ for (const key of ['"seed"', '"rng"', '"deck"', '"log"', '"actions"']) assert.equal(json.includes(key), false, key);
+ for (const c of [...state.players[1].hand, ...state.players[1].deck, ...state.players[0].deck])
+ assert.equal(json.includes(`"${c.cardId}"`), false, c.cardId);
+ assert.deepEqual(view.hand.map(c => c.cardId), state.players[0].hand.map(c => c.cardId));
+});
+
test('energy: energyByTurn + carry (max 1) of unspent energy', () => {
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 3);
const first = state.players[0].hand[0].cardId;
--
2.54.0
From 89883161522f24402e4f803945162671c3289c93 Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:17:20 -0500
Subject: [PATCH 07/14] Play: clearer tiebreak result text; lanes fill the
phone screen
Co-Authored-By: Claude Opus 5.5
---
src/game/Results.tsx | 4 +++-
src/game/play.css | 3 ++-
2 files changed, 5 insertions(+), 2 deletions(-)
diff --git a/src/game/Results.tsx b/src/game/Results.tsx
index 1d74cdf..94f7976 100644
--- a/src/game/Results.tsx
+++ b/src/game/Results.tsx
@@ -4,12 +4,14 @@ import type { ResultView } from './types.ts';
export function Results({ result, modeName, onRematch, onLobby }: { result: ResultView; modeName: string; onRematch: () => void; onLobby: () => void }) {
const outcome = result.winner === null ? 'draw' : result.winner === 0 ? 'win' : 'loss';
const won = result.lanes.filter(l => l.winner === 0).length;
+ const lost = result.lanes.filter(l => l.winner === 1).length;
+ const tiebreak = result.reason === 'lanes' && won === lost;
return
{modeName.toUpperCase()} · {result.turns} TURNS
{outcome === 'win' ? 'Victory!' : outcome === 'loss' ? 'Defeat' : 'Draw'}
{result.reason === 'concede' ? (outcome === 'win' ? 'Your opponent conceded.' : 'You conceded.')
- : `You won ${won} of ${result.lanes.length} lanes.`}
+ : `You won ${won} of ${result.lanes.length} lanes${tiebreak ? ', so total power decided it' : ''}.`}
{result.lanes.map(l =>
{l.name} {l.myPower} – {l.theirPower} {l.winner === 0 ? 'Won' : l.winner === 1 ? 'Lost' : 'Tied'}
diff --git a/src/game/play.css b/src/game/play.css
index 2efd1bb..7509097 100644
--- a/src/game/play.css
+++ b/src/game/play.css
@@ -165,7 +165,8 @@
/* Phones: the match takes the whole screen so the board and the thumb dock both fit. */
@media(max-width:760px){
.match{position:fixed;inset:0;z-index:30;margin:0;max-width:none;border:0;border-radius:0;padding-top:env(safe-area-inset-top);overflow:hidden}
- .match .lanes{flex:1 1 auto;overflow-y:auto;align-content:start}
+ .match .lanes{flex:1 1 auto;overflow-y:auto;align-content:stretch}
+ .match .lane-side{flex:1 1 auto}
.match-dock{position:static;border-radius:0}
.lane-side{min-height:84px}
}
--
2.54.0
From a2573129a5db29d92b800fc7c68236af89a3da0f Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:25:29 -0500
Subject: [PATCH 08/14] Play: wire the real shared/game engine (DESIGN v1 Edit
War)
Replace the mock with an adapter over shared/game/index.ts: Topics with
stats and hidden Portals, home-stat icons and on-topic hints, queued
plays with undo, interleaved reveal log, engine deck validation, loaner
starter decks, interim NFT derivation (cost-capped). Lobby reads the
modes API (self + peers) and links to peer hosts; the account chip uses
the SSO hook; the floating account button hides during a match.
MatchView.engine / UIAction.engine expose engine state for ui-b's bots.
Co-Authored-By: Claude Opus 5.5
---
src/game/DeckBuilder.tsx | 17 ++---
src/game/GameCard.tsx | 22 ++++--
src/game/MatchScreen.tsx | 30 +++++---
src/game/PlaySection.tsx | 90 ++++++++++++----------
src/game/Results.tsx | 2 +-
src/game/Tutorial.tsx | 42 ++++++-----
src/game/adapter.ts | 120 +++++++++++++++++++++++++++---
src/game/bots.ts | 6 +-
src/game/cards.ts | 73 ++++++++----------
src/game/mock/engine.ts | 156 ---------------------------------------
src/game/play.css | 10 +++
src/game/rulesText.ts | 40 ++++++++++
src/game/types.ts | 72 ++++++++----------
src/game/useAccount.ts | 9 +--
src/game/useModes.ts | 67 +++++++++++------
tests/ui-play.test.ts | 101 +++++++++++++++----------
16 files changed, 456 insertions(+), 401 deletions(-)
delete mode 100644 src/game/mock/engine.ts
create mode 100644 src/game/rulesText.ts
diff --git a/src/game/DeckBuilder.tsx b/src/game/DeckBuilder.tsx
index fb170c4..07aedc6 100644
--- a/src/game/DeckBuilder.tsx
+++ b/src/game/DeckBuilder.tsx
@@ -2,15 +2,12 @@ import { useMemo, useState } from 'react';
import { Check, RotateCcw, Trash2 } from 'lucide-react';
import { GameCard } from './GameCard.tsx';
import { starterDeck } from './cards.ts';
-import type { Ruleset, UICard } from './types.ts';
+import { validateDeck, type Ruleset } from '../../shared/game/index.ts';
+import type { UICard } from './types.ts';
export function deckProblem(deck: UICard[], ruleset: Ruleset): string {
if (deck.length !== ruleset.deckSize) return `A deck needs exactly ${ruleset.deckSize} cards (${deck.length} now).`;
- const counts = new Map();
- for (const c of deck) counts.set(c.pageId, (counts.get(c.pageId) ?? 0) + 1);
- const over = [...counts].find(([, n]) => n > ruleset.maxCopies);
- if (over) return `At most ${ruleset.maxCopies} copies of the same article.`;
- return '';
+ return validateDeck(ruleset, deck.map(c => c.game))[0] ?? '';
}
/** Soft advice (DESIGN.md s8): warn, never block, when the early curve is thin. */
@@ -19,8 +16,8 @@ export function deckWarning(deck: UICard[]): string {
return cheap < 4 ? `Only ${cheap} card${cheap === 1 ? '' : 's'} cost 2 or less. Aim for at least 4 so you have early plays.` : '';
}
-export function DeckBuilder({ pool, deck, ruleset, onSave, onCancel }: {
- pool: UICard[]; deck: UICard[]; ruleset: Ruleset; onSave: (deck: UICard[]) => void; onCancel: () => void;
+export function DeckBuilder({ pool, deck, ruleset, modeName, onSave, onCancel }: {
+ modeName: string; pool: UICard[]; deck: UICard[]; ruleset: Ruleset; onSave: (deck: UICard[]) => void; onCancel: () => void;
}) {
const [draft, setDraft] = useState(deck);
const [filter, setFilter] = useState<'all' | 'starter' | 'nft'>('all');
@@ -37,7 +34,7 @@ export function DeckBuilder({ pool, deck, ruleset, onSave, onCancel }: {
const full = draft.length >= ruleset.deckSize;
return
- DECK BUILDER · {ruleset.name.toUpperCase()}
+ DECK BUILDER · {modeName.toUpperCase()}
Your deck {draft.length} / {ruleset.deckSize}
Tap a card to add it or take it out. Loaner cards are free previews, not NFTs; nothing you do here moves a card on-chain.
{curve.map((n, i) =>
{i + 1}{i === 5 ? '+' : ''} {n}
)}
@@ -58,7 +55,7 @@ export function DeckBuilder({ pool, deck, ruleset, onSave, onCancel }: {
{problem ? {problem}
: warning && {warning}
}
-
setDraft(starterDeck())}> Starter
+
setDraft(starterDeck(ruleset))}> Starter
setDraft([])} aria-label="Clear deck">
Cancel
onSave(draft)}> Save deck
diff --git a/src/game/GameCard.tsx b/src/game/GameCard.tsx
index 03410b8..961a116 100644
--- a/src/game/GameCard.tsx
+++ b/src/game/GameCard.tsx
@@ -1,13 +1,23 @@
-import { BookOpen, Landmark, Leaf, Orbit, Palette, Users, Zap } from 'lucide-react';
-import type { UICard } from './types.ts';
+import { BookOpen, ChevronDown, ChevronUp, Eye, Globe2, Landmark, Leaf, Library, Orbit, Palette, Users, Zap } from 'lucide-react';
+import type { Stat, UICard } from './types.ts';
+import { STAT_LABEL } from './rulesText.ts';
const ICONS: Record
= { Space: Orbit, Nature: Leaf, People: Users, Science: BookOpen, History: Landmark, Culture: Palette };
export const CategoryIcon = ({ category, size = 14 }: { category: string; size?: number }) => {
const Icon = ICONS[category] ?? Palette;
return ;
};
+const STAT_ICONS: Record = { attention: Eye, depth: Library, reach: Globe2 };
+export const StatIcon = ({ stat, size = 12 }: { stat: Stat; size?: number }) => {
+ const Icon = STAT_ICONS[stat];
+ return ;
+};
-/** Phone-readable card face: cost, power, one keyword, title. Nothing needs hover. */
+export function cardLabel(card: UICard) {
+ return `${card.title}, cost ${card.cost}, power ${card.power}, home stat ${STAT_LABEL[card.home]}${card.trend ? `, trending ${card.trend > 0 ? 'up' : 'down'}` : ''}${card.onTopic ? ', on-topic' : ''}${card.keyword ? `, ${card.keyword.name}: ${card.keyword.text}` : ''}`;
+}
+
+/** Phone-readable card face (DESIGN §1.9): cost, power, home-stat icon, trend arrow, one keyword. Nothing needs hover. */
export function GameCard({ card, size = 'hand', selected, dim, onClick, label, fresh }: {
card: UICard; size?: 'hand' | 'board' | 'deck'; selected?: boolean; dim?: boolean; fresh?: boolean;
onClick?: () => void; label?: string;
@@ -15,14 +25,16 @@ export function GameCard({ card, size = 'hand', selected, dim, onClick, label, f
const buffed = card.power > card.basePower, nerfed = card.power < card.basePower;
const Tag = onClick ? 'button' : 'div';
return
+ className={`gcard gcard-${size} cat-${card.category.toLowerCase()} ${selected ? 'is-selected' : ''} ${dim ? 'is-dim' : ''} ${fresh ? 'is-fresh' : ''} ${card.onTopic ? 'is-on-topic' : ''}`}
+ aria-label={label ?? cardLabel(card)}>
{card.cost}
{card.power}
{card.image ? { e.currentTarget.style.display = 'none'; }} /> : null}
+
+ {card.trend > 0 && }{card.trend < 0 && }
{card.title}
{card.keyword && size !== 'board' && {card.keyword.name} }
{card.source === 'nft' && size !== 'board' && NFT }
diff --git a/src/game/MatchScreen.tsx b/src/game/MatchScreen.tsx
index fb3f120..69ef793 100644
--- a/src/game/MatchScreen.tsx
+++ b/src/game/MatchScreen.tsx
@@ -2,7 +2,9 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { Flag, Hourglass, Layers3, LoaderCircle, X, Zap } from 'lucide-react';
import { engine } from './adapter.ts';
import type { Bot } from './bots.ts';
-import { GameCard } from './GameCard.tsx';
+import { GameCard, StatIcon } from './GameCard.tsx';
+import { STAT_HINT, STAT_LABEL } from './rulesText.ts';
+import type { MatchState } from '../../shared/game/index.ts';
import type { GameMode, LaneView, ResultView, UIAction, UICard } from './types.ts';
const BOT_DELAY_MS = 450;
@@ -18,7 +20,7 @@ type Sheet = { kind: 'card'; card: UICard; side: 'mine' | 'theirs' } | { kind: '
export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
mode: GameMode; deck: UICard[]; opponentDeck: UICard[]; bot: Bot; seed: string; onFinish: (r: ResultView) => void;
}) {
- const [state, setState] = useState(() => engine.createMatch(mode.ruleset, [deck, opponentDeck], seed));
+ const [state, setState] = useState(() => engine.createMatch(mode.ruleset, [deck, opponentDeck], seed));
const [selected, setSelected] = useState();
const [sheet, setSheet] = useState(null);
const [error, setError] = useState('');
@@ -51,7 +53,7 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
useEffect(() => {
if (!view.waitingForOpponent) return;
const t = setTimeout(() => {
- setState((s: unknown) => {
+ setState((s: MatchState) => {
let cur = s;
for (let guard = 0; guard < 40 && !engine.isOver(cur); guard++) {
const acts = engine.legal(cur, 1);
@@ -67,7 +69,7 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
}, [view.waitingForOpponent, state, bot]);
const act = (a: UIAction) => {
- try { setState((s: unknown) => engine.apply(s, 0, a)); setError(''); }
+ try { setState((s: MatchState) => engine.apply(s, 0, a)); setError(''); }
catch (e) { setError(e instanceof Error ? e.message : 'That move isn’t allowed.'); }
};
const canPlay = (cardId: string, lane: number) => legal.some(a => a.type === 'play' && a.cardId === cardId && a.lane === lane);
@@ -83,7 +85,7 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
return
Turn {view.turn} /{view.maxTurns}
- {bot.name} bot · {view.oppHandCount} in hand
+ {bot.name} bot · {view.oppHandCount}{view.oppQueued ? ` · ${view.oppQueued} queued` : ''}
setSheet({ kind: 'concede' })} aria-label="Concede match">
{banner && {banner}
}
@@ -91,21 +93,23 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
{view.lanes.map(lane => {
const target = !!sel && canPlay(sel.id, lane.index);
- const lead = lane.myPower > lane.theirPower ? 'ahead' : lane.myPower < lane.theirPower ? 'behind' : 'even';
+ const lead = lane.leader === 'you' ? 'ahead' : lane.leader === 'opponent' ? 'behind' : 'even';
+ const onTopic = !!sel && (sel.home === lane.stat || (lane.revealed && lane.modifier?.name === 'Disambiguation'));
+ const topicBonus = sel ? mode.ruleset.onTopicBonus[sel.cost] ?? 0 : 0;
return
{lane.theirs.map(c => setSheet({ kind: 'card', card: c, side: 'theirs' })} />)}
tapLane(lane)}
- aria-label={target ? `Play ${sel!.title} to ${lane.name}` : `${lane.name} lane: you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? ''}`}>
+ aria-label={target ? `Play ${sel!.title} to ${lane.name}${onTopic ? `, on-topic +${topicBonus}` : ''}` : `${lane.name} Topic (${STAT_LABEL[lane.stat]}): you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? lane.portalNote ?? ''}`}>
{lane.theirPower}
- {lane.modifier?.name ?? lane.name}
+ {lane.name} {!lane.revealed && ? }
{lane.myPower}
{lane.mine.map(c => setSheet({ kind: 'card', card: c, side: 'mine' })} />)}
{lane.staged.map(c => act({ type: 'unstage', cardId: c.id })} selected />)}
- {target && Play here }
+ {target && {onTopic ? `On-topic +${topicBonus}` : 'Play here'} }
;
})}
@@ -139,11 +143,13 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
setSheet(null)} aria-label="Close">
{sheet.kind === 'card' && <>
-
{sheet.card.title} {sheet.side === 'mine' ? 'Your card' : 'Opponent card'} · {sheet.card.category} · cost {sheet.card.cost} · power {sheet.card.power}{sheet.card.power !== sheet.card.basePower ? ` (base ${sheet.card.basePower})` : ''}
+
{sheet.card.title} {sheet.side === 'mine' ? 'Your card' : 'Opponent card'} · {sheet.card.category} · cost {sheet.card.cost} · power {sheet.card.power} · home {STAT_LABEL[sheet.card.home]}{sheet.card.trend ? (sheet.card.trend > 0 ? ' · trending ▲' : ' · trending ▼') : ''}{sheet.card.onTopic ? ' · on-topic' : ''}{sheet.card.power !== sheet.card.basePower ? ` (base ${sheet.card.basePower})` : ''}
{sheet.card.keyword &&
{sheet.card.keyword.name}. {sheet.card.keyword.text}
}>}
- {sheet.kind === 'lane' && <>
{sheet.lane.name} lane {sheet.lane.modifier &&
{sheet.lane.modifier.name}. {sheet.lane.modifier.text}
}
+ {sheet.kind === 'lane' && <>
{sheet.lane.name}
+
Judged on {STAT_LABEL[sheet.lane.stat]} ({STAT_HINT[sheet.lane.stat]}). Cards whose home stat is {STAT_LABEL[sheet.lane.stat]} get an on-topic bonus here.
+ {sheet.lane.modifier ?
Portal: {sheet.lane.modifier.name}. {sheet.lane.modifier.text}
: sheet.lane.portalNote &&
{sheet.lane.portalNote}.
}
You {sheet.lane.myPower} · Opponent {sheet.lane.theirPower} · up to {sheet.lane.capacity} cards each.
- {sel && !canPlay(sel.id, sheet.lane.index) &&
{sel.title} can’t go here: {sel.cost > view.energy ? 'not enough energy' : 'this lane is full'}.
}>}
+ {sel && !canPlay(sel.id, sheet.lane.index) &&
{sel.title} can’t go here: {engine.problem(state, 0, { type: 'play', cardId: sel.id, lane: sheet.lane.index }) ?? 'not allowed'}.
}>}
{sheet.kind === 'concede' && <>
Concede this match? It counts as a loss. Nothing on-chain changes.
setSheet(null)}>Keep playing
{ setSheet(null); act({ type: 'concede' }); }}> Concede
>}
diff --git a/src/game/PlaySection.tsx b/src/game/PlaySection.tsx
index e275fad..a3425bc 100644
--- a/src/game/PlaySection.tsx
+++ b/src/game/PlaySection.tsx
@@ -1,31 +1,31 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { CircleHelp, Globe2, Layers3, Play, Server, Swords, UserRound } from 'lucide-react';
+import { CircleHelp, ExternalLink, Globe2, Layers3, Play, Server, Swords, UserRound } from 'lucide-react';
import type { TestnetBlock } from '../../shared/testnet.ts';
-import { engine } from './adapter.ts';
+import { Avatar } from '../auth/LoginButton.tsx';
import { BOTS, type Bot } from './bots.ts';
-import { cardFromBlock, loanerPool, starterDeck } from './cards.ts';
-import { DeckBuilder, deckProblem } from './DeckBuilder.tsx';
+import { cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from './cards.ts';
+import { DeckBuilder, deckProblem, deckWarning } from './DeckBuilder.tsx';
import { CategoryIcon } from './GameCard.tsx';
import { MatchScreen } from './MatchScreen.tsx';
import { Results } from './Results.tsx';
import { Tutorial } from './Tutorial.tsx';
-import type { GameMode, ResultView, UICard } from './types.ts';
+import type { GameMode, ResultView } from './types.ts';
import { useAccount } from './useAccount.ts';
import { useModes } from './useModes.ts';
import './play.css';
type Screen = 'lobby' | 'deck' | 'match' | 'results' | 'tutorial';
-const DECK_KEY = 'wikideck-play-deck';
-const TUTORIAL_KEY = 'wikideck-play-tutorial-seen';
+const DECK_KEY = 'wikideck-play-deck-v1';
+const TUTORIAL_KEY = 'wikideck-play-tutorial-v1';
const store = {
get: (k: string) => { try { return localStorage.getItem(k); } catch { return null; } },
set: (k: string, v: string) => { try { localStorage.setItem(k, v); } catch { /* storage unavailable */ } },
};
+const playsHere = (m: GameMode) => m.host.kind === 'local' || m.host.self;
export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
- const pool = useMemo(() => [...loanerPool(), ...owned.map(cardFromBlock)], [owned]);
const { modes, status } = useModes();
- const { account, available: ssoAvailable, login, logout } = useAccount();
+ const account = useAccount();
const [screen, setScreen] = useState
(() => store.get(TUTORIAL_KEY) ? 'lobby' : 'tutorial');
const [modeId, setModeId] = useState('standard');
const [bot, setBot] = useState(BOTS[0]);
@@ -33,65 +33,81 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
const [seed, setSeed] = useState('');
const [result, setResult] = useState();
const mode = modes.find(m => m.id === modeId) ?? modes[0];
+ const rules = mode.ruleset;
+ const pool = useMemo(() => [...loanerPool(rules), ...owned.map(b => cardFromBlock(b, rules))], [owned, rules]);
// Rebuild the saved deck from current cards; NFTs you no longer own simply drop out.
const deck = useMemo(() => {
- if (!savedIds) return starterDeck();
+ if (!savedIds) return starterDeck(rules);
const byId = new Map(pool.map(c => [c.id, c]));
return savedIds.flatMap(id => byId.get(id) ?? []);
- }, [savedIds, pool]);
- const problem = deckProblem(deck, mode.ruleset);
- const opponentDeck = useMemo(() => starterDeck(), []);
+ }, [savedIds, pool, rules]);
+ const problem = deckProblem(deck, rules);
+ const warning = deckWarning(deck);
+ const opponent = useMemo(() => botDeck(seed, rules), [seed, rules]);
const start = () => { setSeed(`${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`); setScreen('match'); };
const finish = useCallback((r: ResultView) => { setResult(r); setScreen('results'); }, []);
useEffect(() => { window.scrollTo?.({ top: 0 }); }, [screen]);
+ // While a match is on screen, hide the floating eom.dev account button (it sits over the dock on phones).
+ useEffect(() => {
+ document.documentElement.classList.toggle('wd-in-match', screen === 'match');
+ return () => document.documentElement.classList.remove('wd-in-match');
+ }, [screen]);
if (screen === 'tutorial') return { store.set(TUTORIAL_KEY, '1'); setScreen('lobby'); }} />;
- if (screen === 'deck') return setScreen('lobby')}
+ if (screen === 'deck') return setScreen('lobby')}
onSave={d => { const ids = d.map(c => c.id); store.set(DECK_KEY, JSON.stringify(ids)); setSavedIds(ids); setScreen('lobby'); }} />;
- if (screen === 'match') return ;
+ if (screen === 'match') return ;
if (screen === 'results' && result) return setScreen('lobby')} />;
+ const remote = mode.host.kind === 'peer' && !mode.host.self ? mode.host : null;
return
PLAY · OFF-CHAIN MATCHES
Play WikiDeck
-
{account
- ? <>{account.avatar ?
:
}
{account.name} {logout &&
Log out }>
- : <>
Guest {ssoAvailable ? 'Sign in with eom.dev' : 'eom.dev sign-in soon'} >}
+
{account
+ ? <>
{account.name || account.username} >
+ : <>
Guest >}
-
Three lanes, six turns, win two lanes. New here? You already have a loaner starter deck. Matches never move or burn your cards.
+
Three Topics, six turns: win two Topics. Each Topic is judged on one Wikipedia stat, and cards are stronger on their home stat. New here? You already have a loaner starter deck. Matches never move or burn your cards.
Mode
{modes.map(m =>
setModeId(m.id)}>
{m.host.kind === 'local' ? : }
- {m.name} {m.description}
- {m.host.kind === 'local' ? 'Built in · plays in your browser' : `Hosted by ${m.host.name}`}{m.players !== undefined ? ` · ${m.players} playing` : ''}
+ {m.name} {m.description && {m.description} }
+ {m.host.kind === 'local' ? 'Built in · plays in your browser' : `Hosted by ${m.host.name}`}
+ {m.players !== undefined ? ` · ${m.players} online` : ''}{m.matchesPlayed !== undefined ? ` · ${m.matchesPlayed} played` : ''}
)}
{status === 'loading' &&
Looking for peer-hosted modes…
}
- {status === 'unavailable' &&
No peer-hosted modes on this node yet.
}
+ {status === 'unavailable' &&
No peer-hosted modes reachable from this node.
}
- {mode.host.kind === 'peer' &&
Peer modes use their host’s rules. For now the match runs in your browser{engine.mock ? ' on the preview engine' : ''}.
}
-
Opponent
-
{BOTS.map(b => setBot(b)}>{b.name} bot )}
+ {remote ? <>
+
This mode runs on {remote.name}’s node. Open it there to play; your eom.dev account works on every node.
+
+
setScreen('tutorial')}> How to play
+ {remote.url ?
Play on {remote.name}
+ :
Host address unavailable }
+
+ > : <>
+
Opponent
+
{BOTS.map(b => setBot(b)}>{b.name} bot )}
-
Deck {deck.length}
-
setScreen('deck')} aria-label="Edit deck">
- {deck.slice(0, 4).map(c => )}
- {savedIds ? 'Your deck' : 'Starter deck'} {deck.filter(c => c.source === 'nft').length} NFTs · {deck.filter(c => c.source === 'starter').length} loaners
-
-
- {problem &&
{problem} Edit your deck to play {mode.name}.
}
+
Deck {deck.length}
+
setScreen('deck')} aria-label="Edit deck">
+ {deck.slice(0, 4).map(c => )}
+ {savedIds ? 'Your deck' : 'Starter deck'} {deck.filter(c => c.source === 'nft').length} NFTs · {deck.filter(c => c.source === 'starter').length} loaners
+
+
+ {problem ?
{problem} Edit your deck to play {mode.name}.
+ : warning &&
{warning}
}
-
-
+
setScreen('tutorial')}> How to play
Play vs {bot.name}
-
-
- {engine.mock &&
Preview rules engine. The final rules arrive with the game engine.
}
+
+ >}
;
}
diff --git a/src/game/Results.tsx b/src/game/Results.tsx
index 94f7976..a31d4a3 100644
--- a/src/game/Results.tsx
+++ b/src/game/Results.tsx
@@ -5,7 +5,7 @@ export function Results({ result, modeName, onRematch, onLobby }: { result: Resu
const outcome = result.winner === null ? 'draw' : result.winner === 0 ? 'win' : 'loss';
const won = result.lanes.filter(l => l.winner === 0).length;
const lost = result.lanes.filter(l => l.winner === 1).length;
- const tiebreak = result.reason === 'lanes' && won === lost;
+ const tiebreak = result.reason === 'totalPower';
return
{modeName.toUpperCase()} · {result.turns} TURNS
diff --git a/src/game/Tutorial.tsx b/src/game/Tutorial.tsx
index a988cca..4eb7e08 100644
--- a/src/game/Tutorial.tsx
+++ b/src/game/Tutorial.tsx
@@ -1,22 +1,27 @@
import { useState } from 'react';
import { ArrowLeft, ArrowRight, Check } from 'lucide-react';
-import { GameCard } from './GameCard.tsx';
+import { GameCard, StatIcon } from './GameCard.tsx';
import { starterDeck } from './cards.ts';
+import type { Stat } from './types.ts';
const demo = starterDeck();
+const pick = (cost: number) => demo.find(c => c.cost === cost) ?? demo[0];
+const TOPICS: [string, Stat, string][] = [['Current Events', 'attention', '9 – 5'], ['Archive', 'depth', '4 – 7'], ['Translations', 'reach', '6 – 3']];
const STEPS = [
- { title: 'Win two of three lanes', body: 'The board has three lanes. When the last turn ends, whoever has more power in a lane wins it. Win two lanes to win the match.',
- show: 'lanes' },
- { title: 'Every card shows three things', body: 'The top-left number is cost: the energy it takes to play. The top-right number is power. The label at the bottom is its keyword: tap any card on the board to read what it does.',
- show: 'card' },
- { title: 'Energy grows each turn', body: 'You get 1 energy on turn 1, 2 on turn 2, and so on up to 6. Energy you don’t spend is lost. Big famous articles cost more, so weigh them against cheaper cards.',
- show: 'energy' },
- { title: 'Tap a card, then tap a lane', body: 'Tap a card in your hand to pick it up, then tap a lane to play it there. Tap a played card again before ending the turn to take it back. Each lane holds up to 4 of your cards.',
- show: 'play' },
- { title: 'Both players reveal together', body: 'Plays stay face down until both players press End turn. Then everything is revealed and keywords trigger. Your opponent can’t see what you planned, so bluff!',
- show: 'reveal' },
- { title: 'Lanes have portals', body: 'Each lane has a Wiki portal that changes the rules there, for example “Science cards here get +2 power.” Read the portal under each lane name.',
- show: 'portal' },
+ { title: 'Win two of three Topics', show: 'lanes',
+ body: 'The board has three Topics (lanes). After turn 6, whoever has more power in a Topic leads it. Lead two Topics to win. If that’s tied, total power decides.' },
+ { title: 'Every card shows a few things', show: 'card',
+ body: 'Top left is cost: the energy it takes to play. Top right is power. The small icon is the card’s home stat, and the word at the bottom is its keyword. Tap any card on the board to read what it does.' },
+ { title: 'Play on-topic for a bonus', show: 'stats',
+ body: 'Each Topic is judged on one Wikipedia stat: Attention (readers), Depth (article length) or Reach (languages). A card whose home stat matches gets extra power there. The lane says “On-topic +N” when you pick a matching card.' },
+ { title: 'Energy grows each turn', show: 'energy',
+ body: 'You get 1 energy on turn 1, 2 on turn 2, up to 6. You can carry 1 unspent energy to the next turn. Famous articles cost more, but they aren’t more efficient: it’s a trade-off.' },
+ { title: 'Tap a card, then tap a Topic', show: 'play',
+ body: 'Tap a card in your hand to pick it up, then tap a Topic to queue it there. Tap a queued card to take it back. Each Topic holds 3 of your cards. Press End turn when you’re done.' },
+ { title: 'Reveals take turns', show: 'reveal',
+ body: 'Both players plan in secret. Then the cards reveal one at a time, alternating, starting with whoever has initiative (it swaps every turn). Some keywords care about what’s already there, so order matters.' },
+ { title: 'Portals change the rules', show: 'portal',
+ body: 'Each Topic hides a Portal that reveals on turn 2, 3 or 4. Portals bend that Topic’s rules, for example “Only 2 cards per player fit here.” Tap a Topic to read its Portal.' },
];
export function Tutorial({ onDone }: { onDone: () => void }) {
@@ -26,12 +31,13 @@ export function Tutorial({ onDone }: { onDone: () => void }) {
HOW TO PLAY · {i + 1} / {STEPS.length}
{step.title}
- {step.show === 'lanes' &&
{['Left', 'Middle', 'Right'].map((n, k) =>
{n} {k === 1 ? '4 – 7' : k === 0 ? '9 – 5' : '6 – 3'}
)}
}
- {step.show === 'card' &&
2 cost3 powerRally keyword}
+ {step.show === 'lanes' &&
{TOPICS.map(([n, stat, score], k) =>
{n} {score}
)}
}
+ {step.show === 'card' &&
{pick(3).cost} cost{pick(3).power} power home stat{pick(3).keyword?.name} keyword}
+ {step.show === 'stats' &&
{TOPICS.map(([, stat]) =>
{stat[0].toUpperCase() + stat.slice(1)} {stat === 'depth' && +1 }
)}
}
{step.show === 'energy' &&
{[1, 2, 3, 4, 5, 6].map(n => {n} )}
}
- {step.show === 'play' &&
}
- {step.show === 'reveal' &&
}
- {step.show === 'portal' &&
Portal: ScienceScience cards here get +2 power.
}
+ {step.show === 'play' &&
}
+ {step.show === 'reveal' &&
}
+ {step.show === 'portal' &&
StubOnly 2 cards per player fit here.
}
{step.body}
diff --git a/src/game/adapter.ts b/src/game/adapter.ts
index 665115a..22f20c4 100644
--- a/src/game/adapter.ts
+++ b/src/game/adapter.ts
@@ -1,13 +1,113 @@
-// The single place the Play UI touches an engine. Swap mockEngine for the shared/game adapter here.
-import { mockEngine } from './mock/engine.ts';
-import type { EngineAdapter, GameMode, Ruleset } from './types.ts';
+// The single place the Play UI touches the engine (import only from shared/game/index.ts).
+import {
+ DEFAULT_RULESET, applyAction, actionProblem, createMatch, isOver, laneCapacity, legalActions, result, viewFor,
+ type Action, type CardInPlay, type LogEvent, type MatchState, type PlayerId, type Ruleset,
+} from '../../shared/game/index.ts';
+import { toUICard } from './cards.ts';
+import { portalInfo, STAT_LABEL } from './rulesText.ts';
+import type { GameMode, LaneView, MatchView, ResultView, UIAction, UICard } from './types.ts';
-export const engine: EngineAdapter
= mockEngine;
+export const STANDARD_RULESET: Ruleset = DEFAULT_RULESET;
+export const LOCAL_MODES: GameMode[] = [{
+ id: 'standard', name: 'Standard', host: { kind: 'local' }, ruleset: DEFAULT_RULESET,
+ description: 'Three Topics, six turns. Win two Topics.',
+}];
-export const STANDARD_RULESET: Ruleset = {
- id: 'standard', name: 'Standard', description: 'Three lanes, six turns. Win two lanes.',
- maxTurns: 6, deckSize: 12, handSize: 3, laneCount: 3, laneCapacity: 4, maxCopies: 2,
+function toUI(a: Action): UIAction {
+ switch (a.type) {
+ case 'play': return { type: 'play', cardId: a.cardId, lane: a.lane, engine: a };
+ case 'undo': return { type: 'unstage', cardId: a.cardId, engine: a };
+ case 'concede': return { type: 'concede', engine: a };
+ default: return { type: 'endTurn', engine: a };
+ }
+}
+function toEngine(a: UIAction, player: PlayerId): Action {
+ if (a.engine) return { ...a.engine, player } as Action;
+ switch (a.type) {
+ case 'play': return { type: 'play', player, cardId: a.cardId, lane: a.lane };
+ case 'unstage': return { type: 'undo', player, cardId: a.cardId };
+ case 'concede': return { type: 'concede', player };
+ default: return { type: 'commit', player };
+ }
+}
+
+function logLine(e: LogEvent, me: PlayerId, title: (id: string) => string): string | null {
+ const who = (p: PlayerId) => (p === me ? 'You' : 'Opponent');
+ switch (e.t) {
+ case 'turnStart': return `Turn ${e.turn}. ${e.initiative === me ? 'You reveal first.' : 'Opponent reveals first.'}`;
+ case 'portalRevealed': return `Portal revealed: ${e.topic.name}.`;
+ case 'underdog': return `${who(e.player)} got the underdog bonus.`;
+ case 'reveal': return `${who(e.player)} played ${title(e.cardId)}.`;
+ case 'fizzle': return `${who(e.player)}: ${title(e.cardId)} fizzled (no room) and went back to hand.`;
+ case 'effect': return `${e.source}: ${e.text}`;
+ case 'concede': return `${who(e.player)} ${e.afk ? 'timed out' : 'conceded'}.`;
+ case 'matchOver': return 'Match over.';
+ default: return null; // draws are private
+ }
+}
+
+export const engine = {
+ name: 'shared/game v1', mock: false,
+ createMatch(ruleset: Ruleset, decks: [UICard[], UICard[]], seed: string): MatchState {
+ return createMatch(ruleset, [decks[0].map(c => c.game), decks[1].map(c => c.game)], seed);
+ },
+ legal(state: MatchState, player: PlayerId): UIAction[] {
+ if (isOver(state)) return [];
+ const acts = legalActions(state, player).map(toUI);
+ return acts.length ? [...acts, { type: 'concede', engine: { type: 'concede', player } }] : acts;
+ },
+ apply(state: MatchState, player: PlayerId, action: UIAction): MatchState {
+ return applyAction(state, toEngine(action, player));
+ },
+ problem(state: MatchState, player: PlayerId, action: UIAction): string | null {
+ return actionProblem(state, toEngine(action, player));
+ },
+ view(state: MatchState, me: PlayerId): MatchView {
+ const v = viewFor(state, me);
+ const rules = v.ruleset;
+ const titles = new Map();
+ for (const p of state.players) for (const c of [...p.hand, ...p.deck]) titles.set(c.cardId, c.title);
+ for (const l of state.lanes) for (const side of l.cards) for (const c of side) titles.set(c.card.cardId, c.card.title);
+ const handUI = v.hand.map(c => toUICard(c, rules));
+ const onBoard = (c: CardInPlay, power: number, stat: string, allOnTopic: boolean) =>
+ toUICard(c.card, rules, { power, onTopic: allOnTopic || c.card.home === stat });
+ const lanes: LaneView[] = v.lanes.map((lane, i) => {
+ const portal = lane.portalRevealed ? portalInfo(lane.topic.portal, lane.topic.id, rules) : undefined;
+ const allOn = lane.portalRevealed && lane.topic.portal === 'disambiguation';
+ return {
+ index: i, stat: lane.topic.stat, revealed: lane.portalRevealed,
+ name: lane.portalRevealed ? lane.topic.name : STAT_LABEL[lane.topic.stat],
+ modifier: portal, portalNote: lane.portalRevealed ? undefined : `Topic and Portal reveal on turn ${rules.portalReveal[i]}`,
+ mine: lane.cards[0].map((c, k) => onBoard(c, lane.cardPower[0][k], lane.topic.stat, allOn)),
+ theirs: lane.cards[1].map((c, k) => onBoard(c, lane.cardPower[1][k], lane.topic.stat, allOn)),
+ staged: v.queue.filter(q => q.lane === i).flatMap(q => {
+ const c = state.players[me].hand.find(h => h.cardId === q.cardId);
+ return c ? [toUICard(c, rules)] : [];
+ }),
+ myPower: lane.power[0], theirPower: lane.power[1], leader: lane.leader, capacity: laneCapacity(state, i),
+ };
+ });
+ const queued = new Set(v.queue.map(q => q.cardId));
+ const log = state.log.filter(e => e.t !== 'draw')
+ .map(e => logLine(e, me, id => titles.get(id) ?? 'a card')).filter((x): x is string => !!x).slice(-30);
+ return {
+ me, turn: v.turn, maxTurns: rules.turns, energy: v.energyLeft, maxEnergy: v.energy,
+ hand: handUI.filter(c => !queued.has(c.id)), deckCount: v.deckCount,
+ oppHandCount: v.opponent.handCount, oppDeckCount: v.opponent.deckCount, oppQueued: v.opponent.queuedCount,
+ lanes, log, waitingForOpponent: v.committed && v.phase !== 'over', over: v.phase === 'over',
+ engine: { state, seat: me },
+ };
+ },
+ isOver: (s: MatchState) => isOver(s),
+ result(state: MatchState, me: PlayerId): ResultView {
+ const r = result(state)!;
+ const opp: PlayerId = me === 0 ? 1 : 0;
+ return {
+ winner: r.winner, turns: r.turns, reason: r.reason, totalPower: [r.totalPower[me], r.totalPower[opp]],
+ lanes: r.lanePower.map((pw, i) => {
+ const a = pw[me], b = pw[opp];
+ return { name: state.lanes[i].topic.name, myPower: a, theirPower: b, winner: a === b ? null : a > b ? me : opp };
+ }),
+ };
+ },
};
-export const LOCAL_MODES: GameMode[] = [
- { id: 'standard', name: 'Standard', description: STANDARD_RULESET.description, host: { kind: 'local' }, ruleset: STANDARD_RULESET },
-];
diff --git a/src/game/bots.ts b/src/game/bots.ts
index 0249561..647928e 100644
--- a/src/game/bots.ts
+++ b/src/game/bots.ts
@@ -1,15 +1,15 @@
-// AI opponents. ui-b owns the real easy/normal bots; this file is the plug-in point.
+// AI opponents. ui-b owns the real easy/normal bots in src/game/ai/; this file is the plug-in point.
import type { MatchView, UIAction } from './types.ts';
export type Bot = { id: string; name: string; choose(view: MatchView, legal: UIAction[], rand: () => number): UIAction };
-/** Placeholder: plays random affordable cards into random open lanes, then ends the turn. */
+/** Fallback: queues random affordable plays, then commits. */
export const randomBot: Bot = {
id: 'random', name: 'Random',
choose(_view, legal, rand) {
const plays = legal.filter(a => a.type === 'play');
if (plays.length && rand() < 0.85) return plays[Math.floor(rand() * plays.length)];
- return { type: 'endTurn' };
+ return legal.find(a => a.type === 'endTurn') ?? { type: 'endTurn' };
},
};
diff --git a/src/game/cards.ts b/src/game/cards.ts
index 3b9a24c..5b55bd8 100644
--- a/src/game/cards.ts
+++ b/src/game/cards.ts
@@ -1,54 +1,43 @@
import { rarity } from '../../shared/protocol.ts';
import type { TestnetBlock } from '../../shared/testnet.ts';
+import { DEFAULT_RULESET, previewPool, starterDeck as engineStarterDeck, type Faction, type GameCard, type Ruleset, type Stat } from '../../shared/game/index.ts';
+import { keywordInfo } from './rulesText.ts';
import type { UICard } from './types.ts';
-export const CATEGORIES = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const;
-
-/** Mock keywords, one per category. The real list comes from shared/game (DESIGN.md). */
-export const MOCK_KEYWORDS: Record = {
- Space: { id: 'orbit', name: 'Orbit', text: 'On reveal: +1 power to your other cards in this lane.' },
- Nature: { id: 'grow', name: 'Grow', text: 'At the end of each turn: +1 power.' },
- People: { id: 'rally', name: 'Rally', text: 'On reveal: +2 power if you already have a card here.' },
- Science: { id: 'cite', name: 'Cite', text: 'On reveal: draw a card.' },
- History: { id: 'legacy', name: 'Legacy', text: 'On reveal: +2 power if played on turn 1–3.' },
- Culture: { id: 'viral', name: 'Viral', text: 'On reveal: +3 power if you are behind in this lane.' },
+export const CATEGORIES: Faction[] = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'];
+const FACTION_KEYWORD: Record = {
+ Culture: 'viral', Nature: 'rising', People: 'local', Science: 'encyclopedic', History: 'nostalgic', Space: 'translated',
};
-// Curated loaner cards: offline previews, not NFTs. Same power budget as an average owned deck.
-const LOANERS: [number, string, string, number, number][] = [
- [19331, 'Moon', 'Space', 1, 2], [22780, 'Octopus', 'Nature', 1, 2], [23053, 'Periodic table', 'Science', 1, 1],
- [736, 'Albert Einstein', 'People', 2, 3], [13692, 'History of writing', 'History', 2, 2], [18978754, 'Jazz', 'Culture', 2, 3],
- [26751, 'Saturn', 'Space', 3, 4], [9228, 'Earth', 'Nature', 3, 4], [5180, 'Chemistry', 'Science', 3, 3],
- [14532, 'Isaac Newton', 'People', 4, 6], [13275, 'Roman Empire', 'History', 4, 5], [20484, 'Music', 'Culture', 5, 8],
- [1966, 'Ancient Egypt', 'History', 5, 7], [33083, 'Volcano', 'Nature', 6, 10],
-];
-
-
-export function starterDeck(): UICard[] {
- return LOANERS.slice(0, 12).map(([pageId, title, category, cost, power], i) => ({
- id: `starter-${i}`, pageId, title, category, cost, power, basePower: power,
- keyword: MOCK_KEYWORDS[category], source: 'starter',
- }));
-}
-export function loanerPool(): UICard[] {
- return LOANERS.map(([pageId, title, category, cost, power], i) => ({
- id: `starter-${i}`, pageId, title, category, cost, power, basePower: power,
- keyword: MOCK_KEYWORDS[category], source: 'starter',
- }));
+export function toUICard(card: GameCard, rules: Ruleset = DEFAULT_RULESET, extra: Partial = {}): UICard {
+ return { id: card.cardId, pageId: card.pageId, title: card.title, category: card.faction, cost: card.cost,
+ power: card.power, basePower: card.power, home: card.home, trend: card.trend, keyword: keywordInfo(card.keyword, rules),
+ source: card.source === 'owned' ? 'nft' : 'starter', rarity: card.rarity, game: card, ...extra };
}
+/** The default loaner deck for new players (engine starterDeck; DESIGN §2). */
+export const starterDeck = (rules: Ruleset = DEFAULT_RULESET) => engineStarterDeck(1).map(c => toUICard(c, rules));
+/** The bot's deck: a different loaner deck per match seed. */
+export const opponentDeck = (seed: string, rules: Ruleset = DEFAULT_RULESET) => engineStarterDeck(`bot:${seed}`).map(c => toUICard(c, rules));
+export const loanerPool = (rules: Ruleset = DEFAULT_RULESET) => previewPool().map(c => toUICard(c, rules));
+
/**
- * Mock NFT → card mapping (cost from overall stat level, power scales with cost: a sidegrade).
- * Replaced by the engine's cardFromNft() once it lands; never trust raw snapshot stats for power.
+ * Owned NFT → GameCard for local practice matches. INTERIM: a simplified DESIGN §1 derivation (absolute
+ * thresholds instead of percentiles) until engine-b's derive.ts lands; hosted matches derive on the host.
+ * Cost only moves a card along the curve; power comes from powerByCost, so forged stats never buy efficiency.
*/
-export function cardFromBlock(block: TestnetBlock): UICard {
+export function cardFromBlock(block: TestnetBlock, rules: Ruleset = DEFAULT_RULESET): UICard {
const s = block.statsSnapshot?.stats;
- const avg = s ? ((s.attention ?? 30) + s.depth + s.reach) / 3 : 50;
- const cost = Math.max(1, Math.min(6, Math.round((avg - 20) / 12)));
- const tier = rarity(block.powHash);
- const power = cost * 2 - (cost > 3 ? 1 : 0) + (tier === 'Legendary' ? 1 : 0);
- const category = CATEGORIES.includes(block.article.category as never) ? block.article.category : 'Culture';
- return { id: `nft-${block.tokenId}`, pageId: block.article.pageId, title: block.article.title, category,
- image: block.article.image, cost, power, basePower: power, keyword: MOCK_KEYWORDS[category],
- source: 'nft', tokenId: block.tokenId, rarity: tier };
+ const scores: [Stat, number | null][] = [['depth', s?.depth ?? null], ['reach', s?.reach ?? null], ['attention', s?.attention ?? null]];
+ const known = scores.filter((x): x is [Stat, number] => x[1] !== null);
+ const fame = known.length ? known.reduce((a, [, v]) => a + v, 0) / known.length : 50;
+ const cost = Math.min(Math.min(6, 1 + [35, 45, 55, 65, 75].filter(t => fame >= t).length), rules.uncheckedCostCap);
+ const home = known.reduce((best, cur) => (cur[1] > best[1] ? cur : best), known[0] ?? ['depth', 0])[0];
+ const faction = (CATEGORIES.includes(block.article.category as Faction) ? block.article.category : 'Culture') as Faction;
+ const kw = FACTION_KEYWORD[faction];
+ const keyword = cost === 1 || !rules.keywordsEnabled.includes(kw) ? null : kw;
+ const power = rules.powerByCost[cost] + (cost === 1 ? rules.vanillaBonus : 0);
+ const card: GameCard = { cardId: block.tokenId, pageId: block.article.pageId, title: block.article.title, faction,
+ rarity: rarity(block.powHash), cost, power, home, trend: 0, keyword, source: 'owned', check: 'unchecked' };
+ return toUICard(card, rules, { image: block.article.image, tokenId: block.tokenId });
}
diff --git a/src/game/mock/engine.ts b/src/game/mock/engine.ts
deleted file mode 100644
index f0fb108..0000000
--- a/src/game/mock/engine.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-// Stand-in 3-lane engine so the UI can be built before shared/game lands. Deterministic from a seed.
-// Not the real rules: DESIGN.md / shared/game are authoritative.
-import type { EngineAdapter, LaneView, MatchView, PlayerIndex, ResultView, Ruleset, UIAction, UICard } from '../types.ts';
-
-type Player = { deck: UICard[]; hand: UICard[]; energy: number; staged: { card: UICard; lane: number }[]; ended: boolean };
-type Modifier = { name: string; text: string; category?: string; bonus: number };
-type Lane = { name: string; modifier: Modifier; cards: [UICard[], UICard[]]; playedTurn: Record };
-export type MockState = {
- ruleset: Ruleset; rng: number; turn: number; first: PlayerIndex;
- players: [Player, Player]; lanes: Lane[]; log: string[]; over: boolean; conceded?: PlayerIndex;
-};
-
-const LANE_POOL: Modifier[] = [
- { name: 'Portal: Science', text: 'Science cards here get +2 power.', category: 'Science', bonus: 2 },
- { name: 'Portal: Space', text: 'Space cards here get +2 power.', category: 'Space', bonus: 2 },
- { name: 'Portal: Nature', text: 'Nature cards here get +2 power.', category: 'Nature', bonus: 2 },
- { name: 'Portal: People', text: 'People cards here get +2 power.', category: 'People', bonus: 2 },
- { name: 'Portal: History', text: 'History cards here get +2 power.', category: 'History', bonus: 2 },
- { name: 'Featured article', text: 'Every card here gets +1 power.', bonus: 1 },
- { name: 'Stub', text: 'No effect. A blank page.', bonus: 0 },
-];
-const LANE_NAMES = ['Left', 'Middle', 'Right'];
-
-function hashSeed(seed: string): number {
- let h = 2166136261;
- for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 16777619);
- return h >>> 0;
-}
-function next(state: { rng: number }): number { // mulberry32
- let t = (state.rng = (state.rng + 0x6d2b79f5) >>> 0);
- t = Math.imul(t ^ (t >>> 15), t | 1);
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
-}
-function shuffle(state: { rng: number }, items: T[]): T[] {
- const a = [...items];
- for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(next(state) * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
- return a;
-}
-const bonusFor = (lane: Lane, card: UICard) => !lane.modifier.category || lane.modifier.category === card.category ? lane.modifier.bonus : 0;
-const lanePower = (lane: Lane, p: PlayerIndex) => lane.cards[p].reduce((sum, c) => sum + c.power + bonusFor(lane, c), 0);
-const other = (p: PlayerIndex): PlayerIndex => (p === 0 ? 1 : 0);
-
-function draw(player: Player) { const card = player.deck.shift(); if (card) player.hand.push(card); }
-
-function reveal(s: MockState) {
- const order: PlayerIndex[] = [s.first, other(s.first)];
- for (const p of order) {
- for (const { card, lane: li } of s.players[p].staged) {
- const lane = s.lanes[li];
- const hadCard = lane.cards[p].length > 0;
- lane.cards[p].push(card);
- lane.playedTurn[card.id] = s.turn;
- const k = card.keyword?.id;
- if (k === 'orbit') lane.cards[p].forEach(c => { if (c !== card) c.power += 1; });
- if (k === 'rally' && hadCard) card.power += 2;
- if (k === 'cite') draw(s.players[p]);
- if (k === 'legacy' && s.turn <= 3) card.power += 2;
- if (k === 'viral' && lanePower(lane, p) < lanePower(lane, other(p))) card.power += 3;
- s.log.push(`${p === 0 ? 'P1' : 'P2'} played ${card.title} → ${lane.name}${card.power !== card.basePower ? ` (${card.keyword?.name} ${card.power - card.basePower >= 0 ? '+' : ''}${card.power - card.basePower})` : ''}`);
- }
- s.players[p].staged = [];
- }
- for (const lane of s.lanes) for (const p of [0, 1] as PlayerIndex[])
- for (const c of lane.cards[p]) if (c.keyword?.id === 'grow') c.power += 1;
-}
-
-function endRound(s: MockState) {
- reveal(s);
- if (s.turn >= s.ruleset.maxTurns) { s.over = true; s.log.push('Final turn complete.'); return; }
- s.turn += 1;
- s.first = other(s.first);
- for (const p of s.players) { draw(p); p.energy = Math.min(s.turn, 6); p.ended = false; }
- s.log.push(`Turn ${s.turn}.`);
-}
-
-export const mockEngine: EngineAdapter = {
- name: 'mock lanes v0', mock: true,
- createMatch(ruleset, decks, seed) {
- const rng = { rng: hashSeed(seed) };
- const tag = (deck: UICard[], p: number) => deck.map((c, i) => ({ ...c, id: `p${p}-${i}-${c.id}`, power: c.basePower }));
- const players = decks.map((d, p) => {
- const deck = shuffle(rng, tag(d, p));
- return { deck: deck.slice(ruleset.handSize), hand: deck.slice(0, ruleset.handSize), energy: 1, staged: [], ended: false };
- }) as unknown as [Player, Player];
- const mods = shuffle(rng, LANE_POOL).slice(0, ruleset.laneCount);
- const lanes = mods.map((modifier, i) => ({ name: LANE_NAMES[i] ?? `Lane ${i + 1}`, modifier, cards: [[], []] as [UICard[], UICard[]], playedTurn: {} }));
- const first = (next(rng) < 0.5 ? 0 : 1) as PlayerIndex;
- return { ruleset, rng: rng.rng, turn: 1, first, players, lanes, log: ['Turn 1.'], over: false };
- },
- legal(s, p) {
- if (s.over) return [];
- const me = s.players[p];
- if (me.ended) return [];
- const acts: UIAction[] = [{ type: 'endTurn' }, { type: 'concede' }];
- for (const { card } of me.staged) acts.push({ type: 'unstage', cardId: card.id });
- for (const card of me.hand) if (card.cost <= me.energy)
- s.lanes.forEach((lane, li) => {
- const used = lane.cards[p].length + me.staged.filter(x => x.lane === li).length;
- if (used < s.ruleset.laneCapacity) acts.push({ type: 'play', cardId: card.id, lane: li });
- });
- return acts;
- },
- apply(prev, p, action) {
- const s: MockState = structuredClone(prev);
- const me = s.players[p];
- if (s.over || me.ended) throw new Error('Not your turn');
- if (action.type === 'concede') { s.over = true; s.conceded = p; s.log.push(`${p === 0 ? 'P1' : 'P2'} conceded.`); return s; }
- if (action.type === 'play') {
- const ok = mockEngine.legal(prev, p).some(a => a.type === 'play' && a.cardId === action.cardId && a.lane === action.lane);
- if (!ok) throw new Error('Illegal play');
- const i = me.hand.findIndex(c => c.id === action.cardId);
- const [card] = me.hand.splice(i, 1);
- me.energy -= card.cost;
- me.staged.push({ card, lane: action.lane });
- } else if (action.type === 'unstage') {
- const i = me.staged.findIndex(x => x.card.id === action.cardId);
- if (i < 0) throw new Error('Not staged');
- const [{ card }] = me.staged.splice(i, 1);
- me.energy += card.cost;
- me.hand.push(card);
- } else if (action.type === 'endTurn') {
- me.ended = true;
- if (s.players.every(x => x.ended)) endRound(s);
- }
- return s;
- },
- view(s, p): MatchView {
- const me = s.players[p], them = s.players[other(p)];
- const lanes: LaneView[] = s.lanes.map((lane, i) => {
- const withBonus = (c: UICard) => ({ ...c, power: c.power + bonusFor(lane, c) });
- return { index: i, name: lane.name, modifier: { name: lane.modifier.name, text: lane.modifier.text }, revealed: true,
- mine: lane.cards[p].map(withBonus), theirs: lane.cards[other(p)].map(withBonus),
- staged: me.staged.filter(x => x.lane === i).map(x => withBonus(x.card)),
- myPower: lanePower(lane, p), theirPower: lanePower(lane, other(p)), capacity: s.ruleset.laneCapacity };
- });
- return { me: p, turn: s.turn, maxTurns: s.ruleset.maxTurns, energy: me.energy, maxEnergy: Math.min(s.turn, 6),
- hand: me.hand, deckCount: me.deck.length, oppHandCount: them.hand.length, oppDeckCount: them.deck.length,
- lanes, log: s.log.slice(-30), waitingForOpponent: me.ended && !s.over, over: s.over };
- },
- isOver: s => s.over,
- result(s, p): ResultView {
- const lanes = s.lanes.map(l => {
- const a = lanePower(l, p), b = lanePower(l, other(p));
- return { name: l.name, myPower: a, theirPower: b, winner: a === b ? null : a > b ? p : other(p) };
- });
- if (s.conceded !== undefined) return { winner: other(s.conceded), lanes, turns: s.turn, reason: 'concede' };
- const mine = lanes.filter(l => l.winner === p).length, theirs = lanes.filter(l => l.winner === other(p)).length;
- let winner: PlayerIndex | null = mine > theirs ? p : theirs > mine ? other(p) : null;
- if (winner === null) { // tiebreak: total power
- const ta = lanes.reduce((x, l) => x + l.myPower, 0), tb = lanes.reduce((x, l) => x + l.theirPower, 0);
- winner = ta === tb ? null : ta > tb ? p : other(p);
- }
- return { winner, lanes, turns: s.turn, reason: 'lanes' };
- },
-};
diff --git a/src/game/play.css b/src/game/play.css
index 7509097..001d7c8 100644
--- a/src/game/play.css
+++ b/src/game/play.css
@@ -171,3 +171,13 @@
.lane-side{min-height:84px}
}
.deck-warning{color:var(--ctp-yellow)}
+html.wd-in-match .auth-wrap{display:none}
+.gcard-home{position:absolute;top:30px;left:5px;z-index:2;display:flex;align-items:center;gap:1px;padding:2px 4px;border-radius:999px;background:var(--ctp-crust);color:var(--ctp-subtext1);font-size:10px}
+.gcard-home .trend.up{color:var(--ctp-green)}.gcard-home .trend.down{color:var(--ctp-red)}
+.gcard.is-on-topic .gcard-home{background:var(--ctp-green);color:var(--ctp-crust)}
+.gcard-board .gcard-home{position:static;order:2;margin-left:2px;padding:2px 3px;flex:0 0 auto}
+.lane-name{display:flex;flex-direction:column;align-items:center;gap:2px}
+.lane-name small{font-size:9px;color:var(--ctp-overlay1)}
+.lane-drop.on-topic{border-color:var(--ctp-green);color:var(--ctp-green);background:color-mix(in srgb,var(--ctp-green) 10%,transparent)}
+.sheet h3{display:flex;align-items:center;gap:8px}
+@media(max-width:400px){.gcard-board .gcard-home{display:none}.gcard-board.is-on-topic{box-shadow:inset 3px 0 0 var(--ctp-green)}}
diff --git a/src/game/rulesText.ts b/src/game/rulesText.ts
new file mode 100644
index 0000000..5361a0d
--- /dev/null
+++ b/src/game/rulesText.ts
@@ -0,0 +1,40 @@
+// Display names and one-line reminder text (DESIGN §10.2, §10.3). The engine registry wins when it
+// has an entry; this table covers keywords and Portals whose registry entry hasn't landed yet.
+import { KEYWORDS, PORTALS, type Ruleset, type Stat } from '../../shared/game/index.ts';
+
+const KW: Record = {
+ viral: ['Viral', 'On reveal: +{amount} power for each other card you revealed earlier this turn (max +{cap}).'],
+ rising: ['Rising', 'End of turn: +{amount} power (max +{cap} total).'],
+ local: ['Local', 'Ongoing: +{amount} power while on-topic.'],
+ encyclopedic: ['Encyclopedic', 'On reveal: +{amount} power if there are no other cards here.'],
+ nostalgic: ['Nostalgic', 'On reveal: +{amount} power if you are losing here.'],
+ translated: ['Translated', 'On reveal: +{amount} power to your most recent card in each other Topic.'],
+ edition: ['Edition', '+{amount} power for each other copy of this article on your side.'],
+ obscure: ['Obscure', 'Your opponent sees this face down until the match ends.'],
+ wildcard: ['Wildcard', 'On reveal: its home stat becomes this Topic’s stat.'],
+};
+const PORTAL: Record = {
+ 'main-page': ['Main Page', 'At scoring, each card here gets +1 power.'],
+ trending: ['Trending', 'Trend arrows count double here.'],
+ 'featured-article': ['Featured Article', 'At scoring, whoever has the single strongest card here gets +2.'],
+ stub: ['Stub', 'Only 2 cards per player fit here.'],
+ interwiki: ['Interwiki', '+1 here if you have a card in all 3 Topics.'],
+ disambiguation: ['Disambiguation', 'Every card here counts as on-topic.'],
+};
+const fill = (text: string, params: Record = {}) => text.replace(/\{(\w+)\}/g, (_, k) => String(params[k] ?? k));
+
+export const STAT_LABEL: Record = { attention: 'Attention', depth: 'Depth', reach: 'Reach' };
+export const STAT_HINT: Record = {
+ attention: 'how many people read it', depth: 'how long the article is', reach: 'how many languages it’s in',
+};
+
+export function keywordInfo(id: string | null, rules?: Ruleset) {
+ if (!id) return undefined;
+ const reg = KEYWORDS[id], fb = KW[id];
+ return { id, name: reg?.name ?? fb?.[0] ?? id, text: fill(reg?.text ?? fb?.[1] ?? '', rules?.keywordParams[id]) };
+}
+export function portalInfo(portalId: string | null, topicId: string, rules?: Ruleset) {
+ if (!portalId) return undefined;
+ const reg = PORTALS[portalId], fb = PORTAL[portalId];
+ return { name: reg?.name ?? fb?.[0] ?? portalId, text: fill(reg?.text ?? fb?.[1] ?? '', rules?.portalParams[topicId] ?? rules?.portalParams[portalId]) };
+}
diff --git a/src/game/types.ts b/src/game/types.ts
index 03d88cb..8a30c4e 100644
--- a/src/game/types.ts
+++ b/src/game/types.ts
@@ -1,34 +1,43 @@
-// UI-side contract for the Play section. Screens consume only these view models, so swapping the
-// mock engine for shared/game touches adapter.ts alone.
+// UI-side view models for the Play section. Screens consume only these; adapter.ts maps the
+// shared/game engine (docs/game/ENGINE_API.md) onto them.
+import type { Action, GameCard, MatchResult, MatchState, PlayerId, Ruleset, Stat } from '../../shared/game/index.ts';
-export type PlayerIndex = 0 | 1;
+export type PlayerIndex = PlayerId;
+export type { Stat };
-/** A card as the deck builder and match screen display it: at most 3 numbers and 1 keyword. */
+/** A card as the deck builder and match screen show it (DESIGN §1.9): cost, power, home icon, trend, one keyword. */
export type UICard = {
- id: string; // unique within a match/deck (instance id)
- pageId: number;
+ id: string; // engine cardId
+ pageId: number | null;
title: string;
- category: string;
+ category: string; // faction
image?: string;
cost: number;
- power: number; // current power (including modifiers on board)
+ power: number; // current lane power on the board, base power elsewhere
basePower: number;
+ home: Stat;
+ trend: -1 | 0 | 1;
+ onTopic?: boolean; // on the board: the Topic's stat matches home (or Disambiguation)
keyword?: { id: string; name: string; text: string };
source: 'starter' | 'nft';
tokenId?: string;
rarity?: string;
+ game: GameCard;
};
export type LaneView = {
index: number;
- name: string;
- modifier?: { name: string; text: string };
+ name: string; // Topic name
+ stat: Stat;
+ modifier?: { name: string; text: string }; // revealed Portal
+ portalNote?: string; // e.g. "Portal reveals on turn 3"
revealed: boolean;
mine: UICard[];
theirs: UICard[];
- staged: UICard[]; // my plays this turn, not yet revealed
+ staged: UICard[]; // my queued plays this turn, not yet revealed
myPower: number;
theirPower: number;
+ leader: 'you' | 'opponent' | null;
capacity: number;
};
@@ -36,59 +45,42 @@ export type MatchView = {
me: PlayerIndex;
turn: number;
maxTurns: number;
- energy: number; // remaining this turn
+ energy: number; // left this turn
maxEnergy: number;
hand: UICard[];
deckCount: number;
oppHandCount: number;
oppDeckCount: number;
+ oppQueued: number;
lanes: LaneView[];
- log: string[]; // newest last
+ log: string[]; // newest last, this seat's events only
waitingForOpponent: boolean;
over: boolean;
+ /** For bots that reuse shared/bots (ui-b): the full state and this seat. Never render it. */
+ engine?: { state: MatchState; seat: PlayerId };
};
-export type UIAction =
+export type UIAction = (
| { type: 'play'; cardId: string; lane: number }
| { type: 'unstage'; cardId: string }
| { type: 'endTurn' }
- | { type: 'concede' };
+ | { type: 'concede' }
+) & { engine?: Action };
export type ResultView = {
winner: PlayerIndex | null; // null = draw
lanes: { name: string; myPower: number; theirPower: number; winner: PlayerIndex | null }[];
turns: number;
- reason: 'lanes' | 'concede' | 'turnCap';
-};
-
-export type Ruleset = {
- id: string;
- name: string;
- description: string;
- maxTurns: number;
- deckSize: number;
- handSize: number;
- laneCount: number;
- laneCapacity: number;
- maxCopies: number;
+ reason: MatchResult['reason'];
+ totalPower: [number, number];
};
export type GameMode = {
id: string;
name: string;
description: string;
- host: { kind: 'local' } | { kind: 'peer'; name: string; url: string };
+ host: { kind: 'local' } | { kind: 'peer'; name: string; url: string; self: boolean };
ruleset: Ruleset;
players?: number;
+ matchesPlayed?: number;
};
-
-export interface EngineAdapter {
- readonly name: string;
- readonly mock: boolean;
- createMatch(ruleset: Ruleset, decks: [UICard[], UICard[]], seed: string): S;
- legal(state: S, player: PlayerIndex): UIAction[];
- apply(state: S, player: PlayerIndex, action: UIAction): S;
- view(state: S, player: PlayerIndex): MatchView;
- isOver(state: S): boolean;
- result(state: S, player: PlayerIndex): ResultView;
-}
diff --git a/src/game/useAccount.ts b/src/game/useAccount.ts
index 07965d1..2fbe25e 100644
--- a/src/game/useAccount.ts
+++ b/src/game/useAccount.ts
@@ -1,6 +1,3 @@
-// eom.dev login state. The SSO team (#7) owns the real OIDC client; until it lands this reports
-// signed-out and the lobby shows a disabled "Sign in" chip. Swap this hook's body for theirs.
-export type Account = { name: string; avatar?: string } | null;
-export function useAccount(): { account: Account; available: boolean; login?: () => void; logout?: () => void } {
- return { account: null, available: false };
-}
+// eom.dev login state from the SSO module (src/auth, #7).
+import { useAccount as useAuthAccount } from '../auth/LoginButton.tsx';
+export const useAccount = () => useAuthAccount();
diff --git a/src/game/useModes.ts b/src/game/useModes.ts
index d9fefb9..9eb4391 100644
--- a/src/game/useModes.ts
+++ b/src/game/useModes.ts
@@ -1,29 +1,35 @@
import { useEffect, useState } from 'react';
+import { DEFAULT_RULESET, parseRuleset, type Ruleset } from '../../shared/game/index.ts';
import { LOCAL_MODES } from './adapter.ts';
import type { GameMode } from './types.ts';
-// Peer-hosted modes come from this node's GET /api/game/modes (owned by the modes team, #6).
-// The shape is read defensively: anything malformed is skipped, and the built-in mode is always present.
-type Remote = { id?: unknown; name?: unknown; description?: unknown; host?: unknown; hostedBy?: unknown; url?: unknown; players?: unknown; ruleset?: unknown };
+// Modes API (modes team, #6 / docs/game/HOSTING.md §3): GET /api/game/modes for this node and
+// GET /api/game/network/modes for configured peers. Everything a peer sends is untrusted: strings are
+// length-capped and rendered as React text only, and rules go through the engine's strict parseRuleset.
const str = (v: unknown, max = 120) => (typeof v === 'string' ? v.slice(0, max) : undefined);
+const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : undefined);
+const obj = (v: unknown): Record | undefined => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record : undefined);
-export function parseModes(data: unknown): GameMode[] {
- const list = Array.isArray(data) ? data : Array.isArray((data as { modes?: unknown })?.modes) ? (data as { modes: unknown[] }).modes : [];
- const base = LOCAL_MODES[0].ruleset;
- return list.slice(0, 50).flatMap((raw): GameMode[] => {
- if (!raw || typeof raw !== 'object') return [];
- const m = raw as Remote;
- const id = str(m.id, 64), name = str(m.name, 60);
- if (!id || !name) return [];
- const host = m.host as { name?: unknown; url?: unknown; kind?: unknown } | string | undefined;
- const hostName = str(typeof host === 'string' ? host : host?.name) ?? str(m.hostedBy) ?? 'this node';
- const r = (m.ruleset ?? {}) as Record;
- const num = (k: string, lo: number, hi: number) => typeof r[k] === 'number' && r[k] >= lo && r[k] <= hi ? r[k] as number : (base as Record)[k] as number;
- return [{ id: `remote:${id}`, name, description: str(m.description, 280) ?? '',
- host: { kind: 'peer', name: hostName, url: str(typeof host === 'object' ? host?.url : m.url, 200) ?? '' },
- players: typeof m.players === 'number' ? m.players : undefined,
- ruleset: { ...base, id, name, maxTurns: num('maxTurns', 3, 12), deckSize: num('deckSize', 6, 30),
- handSize: num('handSize', 1, 7), laneCount: num('laneCount', 1, 3), laneCapacity: num('laneCapacity', 1, 6), maxCopies: num('maxCopies', 1, 4) } }];
+function rulesFor(rules: unknown): Ruleset | undefined {
+ const overrides = obj(rules);
+ try { return parseRuleset({ ...DEFAULT_RULESET, ...(overrides ?? {}) }); } catch { return undefined; }
+}
+
+/** Parse a ModeList ({ host, modes: [{ mode, stats }] }). Malformed entries are skipped. */
+export function parseModeList(data: unknown, where: { self: boolean; origin: string }): GameMode[] {
+ const list = obj(data);
+ const host = obj(list?.host);
+ const operator = str(host?.operator, 60) ?? str(host?.origin, 80) ?? (where.self ? 'this node' : where.origin);
+ const origin = str(host?.origin, 200) ?? where.origin;
+ const modes = Array.isArray(list?.modes) ? list!.modes as unknown[] : [];
+ return modes.slice(0, 16).flatMap((entry): GameMode[] => {
+ const e = obj(entry), m = obj(e?.mode), stats = obj(e?.stats);
+ const id = str(m?.id, 64), name = str(m?.name, 60);
+ const ruleset = rulesFor(m?.rules);
+ if (!id || !name || !ruleset) return [];
+ return [{ id: `${where.self ? 'self' : origin}:${id}`, name, description: str(m?.description, 280) ?? '',
+ host: { kind: 'peer', name: operator, url: /^https?:\/\//.test(origin) ? origin : '', self: where.self },
+ ruleset, players: num(stats?.playersOnline), matchesPlayed: num(stats?.matchesPlayed) }];
});
}
@@ -32,10 +38,23 @@ export function useModes() {
const [status, setStatus] = useState<'loading' | 'ok' | 'unavailable'>('loading');
useEffect(() => {
let active = true;
- fetch('/api/game/modes', { cache: 'no-store', signal: AbortSignal.timeout(8000) })
- .then(r => r.ok && r.headers.get('content-type')?.includes('json') ? r.json() : Promise.reject(new Error('unavailable')))
- .then(d => { if (active) { setRemote(parseModes(d)); setStatus('ok'); } })
- .catch(() => { if (active) setStatus('unavailable'); });
+ const get = (path: string) => fetch(path, { cache: 'no-store', signal: AbortSignal.timeout(8000) })
+ .then(r => (r.ok && r.headers.get('content-type')?.includes('json') ? r.json() : Promise.reject(new Error('unavailable'))));
+ Promise.allSettled([get('/api/game/modes'), get('/api/game/network/modes')]).then(([self, net]) => {
+ if (!active) return;
+ const found: GameMode[] = [];
+ if (self.status === 'fulfilled') found.push(...parseModeList(self.value, { self: true, origin: '' }));
+ if (net.status === 'fulfilled') {
+ const peers = obj(net.value)?.peers;
+ if (Array.isArray(peers)) for (const p of peers.slice(0, 16)) {
+ const peer = obj(p);
+ if (peer?.ok && peer.list) found.push(...parseModeList(peer.list, { self: false, origin: str(peer.origin, 200) ?? '' }));
+ }
+ }
+ const seen = new Set();
+ setRemote(found.filter(m => !seen.has(m.id) && seen.add(m.id)));
+ setStatus(self.status === 'fulfilled' || net.status === 'fulfilled' ? 'ok' : 'unavailable');
+ });
return () => { active = false; };
}, []);
return { modes: [...LOCAL_MODES, ...remote], status };
diff --git a/tests/ui-play.test.ts b/tests/ui-play.test.ts
index 530212a..17b0fee 100644
--- a/tests/ui-play.test.ts
+++ b/tests/ui-play.test.ts
@@ -1,63 +1,77 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { engine, STANDARD_RULESET } from '../src/game/adapter.ts';
+import { DEFAULT_RULESET } from '../shared/game/index.ts';
+import { engine } from '../src/game/adapter.ts';
import { randomBot } from '../src/game/bots.ts';
-import { loanerPool, starterDeck } from '../src/game/cards.ts';
-import { deckProblem } from '../src/game/DeckBuilder.tsx';
-import { parseModes } from '../src/game/useModes.ts';
+import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts';
+import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx';
+import { parseModeList } from '../src/game/useModes.ts';
import type { PlayerIndex } from '../src/game/types.ts';
+import type { TestnetBlock } from '../shared/testnet.ts';
function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
+/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */
function playOut(seed: string) {
- let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], seed);
- const r = rand(seed.length * 7919);
- for (let steps = 0; steps < 500 && !engine.isOver(s); steps++) {
+ let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed);
+ const r = rand(seed.length * 7919 + 1);
+ for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) {
for (const p of [0, 1] as PlayerIndex[]) {
- const legal = engine.legal(s, p);
+ const legal = engine.legal(s, p).filter(a => a.type !== 'concede');
if (!legal.length) continue;
- s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal.filter(a => a.type !== 'concede'), r));
+ s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
}
}
return s;
}
-test('starter deck is a legal Standard deck', () => {
- assert.equal(deckProblem(starterDeck(), STANDARD_RULESET), '');
- assert.match(deckProblem(starterDeck().slice(1), STANDARD_RULESET), /exactly 12/);
- const pool = loanerPool();
- assert.match(deckProblem([...Array(12)].map(() => pool[0]), STANDARD_RULESET), /copies/);
+test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => {
+ assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), '');
+ assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), '');
+ assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/);
});
-test('random legal play always terminates within the turn cap and is deterministic', () => {
- for (let i = 0; i < 60; i++) {
+test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => {
+ const pool = loanerPool();
+ const heavy = pool.filter(c => c.cost >= 3).slice(0, 12);
+ assert.match(deckWarning(heavy), /cost 2 or less/);
+ assert.equal(deckWarning(starterDeck()), '');
+});
+
+test('UI-driven random play always finishes within the turn cap and is deterministic', () => {
+ for (let i = 0; i < 40; i++) {
const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
assert.ok(engine.isOver(a), `match ${i} finished`);
const ra = engine.result(a, 0);
- assert.ok(ra.turns <= STANDARD_RULESET.maxTurns);
+ assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
assert.deepEqual(ra, engine.result(b, 0));
- const rb = engine.result(a, 1);
- if (ra.winner !== null) assert.equal(rb.winner, ra.winner);
+ assert.equal(engine.result(a, 1).winner, ra.winner);
}
});
-test('opponent staged plays stay hidden until reveal', () => {
- let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], 'hidden');
+test('my view never shows the opponent’s queued cards', () => {
+ // Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand).
+ let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0');
+ for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++)
+ s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`);
const play = engine.legal(s, 1).find(a => a.type === 'play');
- assert.ok(play);
+ assert.ok(play, 'some seed gives the opponent a turn-1 play');
s = engine.apply(s, 1, play!);
const mine = engine.view(s, 0);
assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
- assert.equal(engine.view(s, 1).lanes.flatMap(l => l.staged).length, 1);
+ assert.equal(mine.oppQueued, 1);
+ const theirs = engine.view(s, 1);
+ assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
+ assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
});
-test('illegal plays are rejected and unstage refunds energy', () => {
- let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], 'energy');
+test('unstage refunds energy, and illegal plays are explained', () => {
+ let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy');
const v = engine.view(s, 0);
const expensive = v.hand.find(c => c.cost > v.energy);
- if (expensive) assert.throws(() => engine.apply(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
+ if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
const play = engine.legal(s, 0).find(a => a.type === 'play');
- if (play && play.type === 'play') {
+ if (play?.type === 'play') {
s = engine.apply(s, 0, play);
assert.ok(engine.view(s, 0).energy < v.energy);
s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
@@ -65,15 +79,28 @@ test('illegal plays are rejected and unstage refunds energy', () => {
}
});
-test('peer mode parsing is defensive and clamps rulesets', () => {
- const modes = parseModes({ modes: [
- { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), host: { name: 'node-b', url: 'http://n' }, ruleset: { maxTurns: 99, laneCount: 2 } },
- { name: 'no id' }, 'junk', null,
- ] });
+test('an owned NFT maps to a sidegrade card that the engine accepts', () => {
+ const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined },
+ statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock;
+ const card = cardFromBlock(block);
+ assert.equal(card.source, 'nft');
+ assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped');
+ assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]);
+ const deck = [card, ...starterDeck().slice(1)];
+ assert.equal(deckProblem(deck, DEFAULT_RULESET), '');
+});
+
+test('peer mode lists are parsed defensively', () => {
+ const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [
+ { mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } },
+ { mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } },
+ { mode: { name: 'no id' } }, 'junk', null,
+ ] }, { self: false, origin: 'http://192.168.1.32:3102' });
assert.equal(modes.length, 1);
- assert.equal(modes[0].host.kind, 'peer');
- assert.equal(modes[0].ruleset.maxTurns, STANDARD_RULESET.maxTurns);
- assert.equal(modes[0].ruleset.laneCount, 2);
- assert.ok(modes[0].description.length <= 280);
- assert.deepEqual(parseModes('nope'), []);
+ const [m] = modes;
+ assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b');
+ assert.equal(m.ruleset.turns, 5);
+ assert.ok(m.description.length <= 280);
+ assert.equal(m.players, 3);
+ assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []);
});
--
2.54.0
From dcb2c45af2373245308abfd3d27deeefc108386f Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:29:49 -0500
Subject: [PATCH 09/14] Play: owner-prefixed board card ids; hide account
button via :has() too
Co-Authored-By: Claude Opus 5.5
---
src/game/adapter.ts | 2 +-
src/game/play.css | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/game/adapter.ts b/src/game/adapter.ts
index 22f20c4..8ad96c1 100644
--- a/src/game/adapter.ts
+++ b/src/game/adapter.ts
@@ -70,7 +70,7 @@ export const engine = {
for (const l of state.lanes) for (const side of l.cards) for (const c of side) titles.set(c.card.cardId, c.card.title);
const handUI = v.hand.map(c => toUICard(c, rules));
const onBoard = (c: CardInPlay, power: number, stat: string, allOnTopic: boolean) =>
- toUICard(c.card, rules, { power, onTopic: allOnTopic || c.card.home === stat });
+ toUICard(c.card, rules, { id: `${c.owner}:${c.card.cardId}`, power, onTopic: allOnTopic || c.card.home === stat }); // both seats may share loaner cardIds
const lanes: LaneView[] = v.lanes.map((lane, i) => {
const portal = lane.portalRevealed ? portalInfo(lane.topic.portal, lane.topic.id, rules) : undefined;
const allOn = lane.portalRevealed && lane.topic.portal === 'disambiguation';
diff --git a/src/game/play.css b/src/game/play.css
index 001d7c8..23d0edb 100644
--- a/src/game/play.css
+++ b/src/game/play.css
@@ -171,7 +171,7 @@
.lane-side{min-height:84px}
}
.deck-warning{color:var(--ctp-yellow)}
-html.wd-in-match .auth-wrap{display:none}
+html.wd-in-match .auth-wrap,body:has(.match) .auth-wrap{display:none}
.gcard-home{position:absolute;top:30px;left:5px;z-index:2;display:flex;align-items:center;gap:1px;padding:2px 4px;border-radius:999px;background:var(--ctp-crust);color:var(--ctp-subtext1);font-size:10px}
.gcard-home .trend.up{color:var(--ctp-green)}.gcard-home .trend.down{color:var(--ctp-red)}
.gcard.is-on-topic .gcard-home{background:var(--ctp-green);color:var(--ctp-crust)}
--
2.54.0
From 60af45262d52a6f91842987b862c35656a9e9076 Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:33:02 -0500
Subject: [PATCH 10/14] Play: online lobbies for modes hosted on this node;
MatchBoard split
MatchBoard renders any PlayerView; the local controller runs the engine
and bot, the online controller polls the host lobby API (create, join,
draft picks, actions, resign). Player secret is HMAC(master, hostOrigin)
per night-review. Illegal local moves no longer throw inside a state
updater.
Co-Authored-By: Claude Opus 5.5
---
src/game/MatchBoard.tsx | 123 +++++++++++++++++++++++++++++++++
src/game/MatchScreen.tsx | 144 +++++----------------------------------
src/game/OnlinePlay.tsx | 134 ++++++++++++++++++++++++++++++++++++
src/game/PlaySection.tsx | 16 +++--
src/game/adapter.ts | 97 +++++++++++++++-----------
src/game/online.ts | 64 +++++++++++++++++
src/game/types.ts | 2 +
src/game/useModes.ts | 2 +-
8 files changed, 411 insertions(+), 171 deletions(-)
create mode 100644 src/game/MatchBoard.tsx
create mode 100644 src/game/OnlinePlay.tsx
create mode 100644 src/game/online.ts
diff --git a/src/game/MatchBoard.tsx b/src/game/MatchBoard.tsx
new file mode 100644
index 0000000..4ca0085
--- /dev/null
+++ b/src/game/MatchBoard.tsx
@@ -0,0 +1,123 @@
+import { useEffect, useRef, useState } from 'react';
+import { Flag, Hourglass, Layers3, LoaderCircle, X, Zap } from 'lucide-react';
+import { GameCard, StatIcon } from './GameCard.tsx';
+import { STAT_HINT, STAT_LABEL } from './rulesText.ts';
+import type { LaneView, MatchView, UIAction, UICard } from './types.ts';
+
+type Sheet = { kind: 'card'; card: UICard; side: 'mine' | 'theirs' } | { kind: 'lane'; lane: LaneView } | { kind: 'concede' } | null;
+
+/** The match screen itself: board, thumb dock and bottom sheets. Controllers (local bot / hosted lobby) feed it. */
+export function MatchBoard({ title, opponent, view, legal, onAct, problem, error, onTopicBonus }: {
+ title: string; opponent: string; view: MatchView; legal: UIAction[]; onAct: (a: UIAction) => void;
+ problem?: (a: UIAction) => string | null; error?: string; onTopicBonus: number[];
+}) {
+ const [selected, setSelected] = useState();
+ const [sheet, setSheet] = useState(null);
+ const [banner, setBanner] = useState('');
+ const prevBoard = useRef(new Set());
+ const [fresh, setFresh] = useState(new Set());
+ const boardKey = view.lanes.map(l => [...l.mine, ...l.theirs].map(c => c.id).join(',')).join('|');
+
+ // Turn feedback: banner on turn change, and a short highlight on newly revealed cards.
+ const lastTurn = useRef(view.turn);
+ useEffect(() => {
+ const ids = new Set(boardKey.split(/[|,]/).filter(Boolean));
+ const added = new Set([...ids].filter(id => !prevBoard.current.has(id)));
+ prevBoard.current = ids;
+ if (added.size) { setFresh(added); const t = setTimeout(() => setFresh(new Set()), 900); return () => clearTimeout(t); }
+ }, [boardKey]);
+ useEffect(() => {
+ if (view.turn !== lastTurn.current && !view.over) {
+ lastTurn.current = view.turn;
+ setBanner(view.turn === view.maxTurns ? `Final turn · ${view.maxEnergy} energy` : `Turn ${view.turn} · ${view.maxEnergy} energy`);
+ const t = setTimeout(() => setBanner(''), 1400);
+ return () => clearTimeout(t);
+ }
+ }, [view.turn, view.over, view.maxTurns, view.maxEnergy]);
+
+ const act = onAct;
+ const canPlay = (cardId: string, lane: number) => legal.some(a => a.type === 'play' && a.cardId === cardId && a.lane === lane);
+ const playable = (cardId: string) => legal.some(a => a.type === 'play' && a.cardId === cardId);
+ const sel = view.hand.find(c => c.id === selected);
+ const tapLane = (lane: LaneView) => {
+ if (sel && canPlay(sel.id, lane.index)) { act({ type: 'play', cardId: sel.id, lane: lane.index }); setSelected(undefined); }
+ else setSheet({ kind: 'lane', lane });
+ };
+ const ending = view.waitingForOpponent;
+ const lastEvent = view.log.at(-1);
+
+ return
+
+ Turn {view.turn} /{view.maxTurns}
+ {opponent} · {view.oppHandCount}{view.oppQueued ? ` · ${view.oppQueued} queued` : ''}
+ setSheet({ kind: 'concede' })} aria-label="Concede match">
+
+ {banner && {banner}
}
+
+
+ {view.lanes.map(lane => {
+ const target = !!sel && canPlay(sel.id, lane.index);
+ const lead = lane.leader === 'you' ? 'ahead' : lane.leader === 'opponent' ? 'behind' : 'even';
+ const onTopic = !!sel && (sel.home === lane.stat || (lane.revealed && lane.modifier?.name === 'Disambiguation'));
+ const topicBonus = sel ? onTopicBonus[sel.cost] ?? 0 : 0;
+ return
+
+ {lane.theirs.map(c => setSheet({ kind: 'card', card: c, side: 'theirs' })} />)}
+
+
tapLane(lane)}
+ aria-label={target ? `Play ${sel!.title} to ${lane.name}${onTopic ? `, on-topic +${topicBonus}` : ''}` : `${lane.name} Topic (${STAT_LABEL[lane.stat]}): you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? lane.portalNote ?? ''}`}>
+ {lane.theirPower}
+ {lane.name} {!lane.revealed && ? }
+ {lane.myPower}
+
+
+ {lane.mine.map(c => setSheet({ kind: 'card', card: c, side: 'mine' })} />)}
+ {lane.staged.map(c => act({ type: 'unstage', cardId: c.id })} selected />)}
+ {target && {onTopic ? `On-topic +${topicBonus}` : 'Play here'} }
+
+
;
+ })}
+
+
+
+
+ {error ? {error}
+ : ending ? <> Opponent is choosing…>
+ : sel ? <> {sel.title} {sel.keyword ? ` · ${sel.keyword.name}: ${sel.keyword.text}` : ''} Tap a lane.>
+ : lastEvent}
+
+
+ {view.hand.length ? view.hand.map(c => setSelected(selected === c.id ? undefined : c.id)} />)
+ : No cards in hand. }
+
+
+
+ {Array.from({ length: view.maxEnergy }, (_, i) => )}
+ {view.energy}
+
+ {view.deckCount}
+ { setSelected(undefined); act({ type: 'endTurn' }); }}>
+ {ending ? 'Waiting…' : view.turn === view.maxTurns ? 'End match' : 'End turn'}
+
+
+
+
+ {sheet && { if (e.target === e.currentTarget) setSheet(null); }}>
+
+
setSheet(null)} aria-label="Close">
+ {sheet.kind === 'card' && <>
+
{sheet.card.title} {sheet.side === 'mine' ? 'Your card' : 'Opponent card'} · {sheet.card.category} · cost {sheet.card.cost} · power {sheet.card.power} · home {STAT_LABEL[sheet.card.home]}{sheet.card.trend ? (sheet.card.trend > 0 ? ' · trending ▲' : ' · trending ▼') : ''}{sheet.card.onTopic ? ' · on-topic' : ''}{sheet.card.power !== sheet.card.basePower ? ` (base ${sheet.card.basePower})` : ''}
+ {sheet.card.keyword &&
{sheet.card.keyword.name}. {sheet.card.keyword.text}
}>}
+ {sheet.kind === 'lane' && <>
{sheet.lane.name}
+
Judged on {STAT_LABEL[sheet.lane.stat]} ({STAT_HINT[sheet.lane.stat]}). Cards whose home stat is {STAT_LABEL[sheet.lane.stat]} get an on-topic bonus here.
+ {sheet.lane.modifier ?
Portal: {sheet.lane.modifier.name}. {sheet.lane.modifier.text}
: sheet.lane.portalNote &&
{sheet.lane.portalNote}.
}
+
You {sheet.lane.myPower} · Opponent {sheet.lane.theirPower} · up to {sheet.lane.capacity} cards each.
+ {sel && !canPlay(sel.id, sheet.lane.index) &&
{sel.title} can’t go here: {problem?.({ type: 'play', cardId: sel.id, lane: sheet.lane.index }) ?? (sel.cost > view.energy ? 'not enough energy' : 'no room')}.
}>}
+ {sheet.kind === 'concede' && <>
Concede this match? It counts as a loss. Nothing on-chain changes.
+
setSheet(null)}>Keep playing
+ { setSheet(null); act({ type: 'concede' }); }}> Concede
>}
+
+
}
+ ;
+}
diff --git a/src/game/MatchScreen.tsx b/src/game/MatchScreen.tsx
index 69ef793..171e624 100644
--- a/src/game/MatchScreen.tsx
+++ b/src/game/MatchScreen.tsx
@@ -1,11 +1,9 @@
import { useEffect, useMemo, useRef, useState } from 'react';
-import { Flag, Hourglass, Layers3, LoaderCircle, X, Zap } from 'lucide-react';
+import type { MatchState } from '../../shared/game/index.ts';
import { engine } from './adapter.ts';
import type { Bot } from './bots.ts';
-import { GameCard, StatIcon } from './GameCard.tsx';
-import { STAT_HINT, STAT_LABEL } from './rulesText.ts';
-import type { MatchState } from '../../shared/game/index.ts';
-import type { GameMode, LaneView, ResultView, UIAction, UICard } from './types.ts';
+import { MatchBoard } from './MatchBoard.tsx';
+import type { GameMode, ResultView, UIAction, UICard } from './types.ts';
const BOT_DELAY_MS = 450;
@@ -15,145 +13,39 @@ function seededRand(seed: string) {
return () => { h = Math.imul(h ^ (h >>> 16), 2246822507); h = Math.imul(h ^ (h >>> 13), 3266489909); return ((h ^= h >>> 16) >>> 0) / 4294967296; };
}
-type Sheet = { kind: 'card'; card: UICard; side: 'mine' | 'theirs' } | { kind: 'lane'; lane: LaneView } | { kind: 'concede' } | null;
-
+/** Local match against a bot: the engine runs in the browser, the bot plays seat 1. */
export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
mode: GameMode; deck: UICard[]; opponentDeck: UICard[]; bot: Bot; seed: string; onFinish: (r: ResultView) => void;
}) {
const [state, setState] = useState(() => engine.createMatch(mode.ruleset, [deck, opponentDeck], seed));
- const [selected, setSelected] = useState();
- const [sheet, setSheet] = useState(null);
const [error, setError] = useState('');
- const [banner, setBanner] = useState('');
const rand = useRef(seededRand(`${seed}:bot`));
- const view = engine.view(state, 0);
+ const view = useMemo(() => engine.view(state, 0), [state]);
const legal = useMemo(() => engine.legal(state, 0), [state]);
- const prevBoard = useRef(new Set());
- const [fresh, setFresh] = useState(new Set());
- // Turn feedback: banner on turn change, and a short highlight on newly revealed cards.
- const lastTurn = useRef(view.turn);
- useEffect(() => {
- const ids = new Set(view.lanes.flatMap(l => [...l.mine, ...l.theirs].map(c => c.id)));
- const added = new Set([...ids].filter(id => !prevBoard.current.has(id)));
- prevBoard.current = ids;
- if (added.size) { setFresh(added); const t = setTimeout(() => setFresh(new Set()), 900); return () => clearTimeout(t); }
- }, [state]); // eslint-disable-line react-hooks/exhaustive-deps
- useEffect(() => {
- if (view.turn !== lastTurn.current && !view.over) {
- lastTurn.current = view.turn;
- setBanner(view.turn === view.maxTurns ? `Final turn · ${view.maxEnergy} energy` : `Turn ${view.turn} · ${view.maxEnergy} energy`);
- const t = setTimeout(() => setBanner(''), 1400);
- return () => clearTimeout(t);
- }
- }, [view.turn, view.over, view.maxTurns, view.maxEnergy]);
useEffect(() => { if (engine.isOver(state)) { const t = setTimeout(() => onFinish(engine.result(state, 0)), 900); return () => clearTimeout(t); } }, [state, onFinish]);
- // The bot moves once the player has ended the turn (it never sees staged plays).
+ // The bot moves once the player has committed (it never sees the player's queued plays).
useEffect(() => {
if (!view.waitingForOpponent) return;
const t = setTimeout(() => {
- setState((s: MatchState) => {
- let cur = s;
- for (let guard = 0; guard < 40 && !engine.isOver(cur); guard++) {
- const acts = engine.legal(cur, 1);
- if (!acts.length) break;
- const choice = bot.choose(engine.view(cur, 1), acts.filter(a => a.type !== 'concede'), rand.current);
- try { cur = engine.apply(cur, 1, choice); } catch { cur = engine.apply(cur, 1, { type: 'endTurn' }); }
- if (choice.type === 'endTurn') break;
- }
- return cur;
- });
+ let cur = state;
+ for (let guard = 0; guard < 40 && !engine.isOver(cur); guard++) {
+ const acts = engine.legal(cur, 1);
+ if (!acts.length) break;
+ const choice = bot.choose(engine.view(cur, 1), acts.filter(a => a.type !== 'concede'), rand.current);
+ try { cur = engine.apply(cur, 1, choice); } catch { cur = engine.apply(cur, 1, { type: 'endTurn' }); }
+ if (choice.type === 'endTurn') break;
+ }
+ setState(cur);
}, BOT_DELAY_MS);
return () => clearTimeout(t);
}, [view.waitingForOpponent, state, bot]);
const act = (a: UIAction) => {
- try { setState((s: MatchState) => engine.apply(s, 0, a)); setError(''); }
+ try { setState(engine.apply(state, 0, a)); setError(''); }
catch (e) { setError(e instanceof Error ? e.message : 'That move isn’t allowed.'); }
};
- const canPlay = (cardId: string, lane: number) => legal.some(a => a.type === 'play' && a.cardId === cardId && a.lane === lane);
- const playable = (cardId: string) => legal.some(a => a.type === 'play' && a.cardId === cardId);
- const sel = view.hand.find(c => c.id === selected);
- const tapLane = (lane: LaneView) => {
- if (sel && canPlay(sel.id, lane.index)) { act({ type: 'play', cardId: sel.id, lane: lane.index }); setSelected(undefined); }
- else setSheet({ kind: 'lane', lane });
- };
- const ending = view.waitingForOpponent;
- const lastEvent = view.log.at(-1);
-
- return
-
- Turn {view.turn} /{view.maxTurns}
- {bot.name} bot · {view.oppHandCount}{view.oppQueued ? ` · ${view.oppQueued} queued` : ''}
- setSheet({ kind: 'concede' })} aria-label="Concede match">
-
- {banner && {banner}
}
-
-
- {view.lanes.map(lane => {
- const target = !!sel && canPlay(sel.id, lane.index);
- const lead = lane.leader === 'you' ? 'ahead' : lane.leader === 'opponent' ? 'behind' : 'even';
- const onTopic = !!sel && (sel.home === lane.stat || (lane.revealed && lane.modifier?.name === 'Disambiguation'));
- const topicBonus = sel ? mode.ruleset.onTopicBonus[sel.cost] ?? 0 : 0;
- return
-
- {lane.theirs.map(c => setSheet({ kind: 'card', card: c, side: 'theirs' })} />)}
-
-
tapLane(lane)}
- aria-label={target ? `Play ${sel!.title} to ${lane.name}${onTopic ? `, on-topic +${topicBonus}` : ''}` : `${lane.name} Topic (${STAT_LABEL[lane.stat]}): you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? lane.portalNote ?? ''}`}>
- {lane.theirPower}
- {lane.name} {!lane.revealed && ? }
- {lane.myPower}
-
-
- {lane.mine.map(c => setSheet({ kind: 'card', card: c, side: 'mine' })} />)}
- {lane.staged.map(c => act({ type: 'unstage', cardId: c.id })} selected />)}
- {target && {onTopic ? `On-topic +${topicBonus}` : 'Play here'} }
-
-
;
- })}
-
-
-
-
- {error ? {error}
- : ending ? <> Opponent is choosing…>
- : sel ? <> {sel.title} {sel.keyword ? ` · ${sel.keyword.name}: ${sel.keyword.text}` : ''} Tap a lane.>
- : lastEvent}
-
-
- {view.hand.length ? view.hand.map(c => setSelected(selected === c.id ? undefined : c.id)} />)
- : No cards in hand. }
-
-
-
- {Array.from({ length: view.maxEnergy }, (_, i) => )}
- {view.energy}
-
- {view.deckCount}
- { setSelected(undefined); act({ type: 'endTurn' }); }}>
- {ending ? 'Waiting…' : view.turn === view.maxTurns ? 'End match' : 'End turn'}
-
-
-
-
- {sheet && { if (e.target === e.currentTarget) setSheet(null); }}>
-
-
setSheet(null)} aria-label="Close">
- {sheet.kind === 'card' && <>
-
{sheet.card.title} {sheet.side === 'mine' ? 'Your card' : 'Opponent card'} · {sheet.card.category} · cost {sheet.card.cost} · power {sheet.card.power} · home {STAT_LABEL[sheet.card.home]}{sheet.card.trend ? (sheet.card.trend > 0 ? ' · trending ▲' : ' · trending ▼') : ''}{sheet.card.onTopic ? ' · on-topic' : ''}{sheet.card.power !== sheet.card.basePower ? ` (base ${sheet.card.basePower})` : ''}
- {sheet.card.keyword &&
{sheet.card.keyword.name}. {sheet.card.keyword.text}
}>}
- {sheet.kind === 'lane' && <>
{sheet.lane.name}
-
Judged on {STAT_LABEL[sheet.lane.stat]} ({STAT_HINT[sheet.lane.stat]}). Cards whose home stat is {STAT_LABEL[sheet.lane.stat]} get an on-topic bonus here.
- {sheet.lane.modifier ?
Portal: {sheet.lane.modifier.name}. {sheet.lane.modifier.text}
: sheet.lane.portalNote &&
{sheet.lane.portalNote}.
}
-
You {sheet.lane.myPower} · Opponent {sheet.lane.theirPower} · up to {sheet.lane.capacity} cards each.
- {sel && !canPlay(sel.id, sheet.lane.index) &&
{sel.title} can’t go here: {engine.problem(state, 0, { type: 'play', cardId: sel.id, lane: sheet.lane.index }) ?? 'not allowed'}.
}>}
- {sheet.kind === 'concede' && <>
Concede this match? It counts as a loss. Nothing on-chain changes.
-
setSheet(null)}>Keep playing
- { setSheet(null); act({ type: 'concede' }); }}> Concede
>}
-
-
}
- ;
+ return engine.problem(state, 0, a)} onTopicBonus={mode.ruleset.onTopicBonus} />;
}
diff --git a/src/game/OnlinePlay.tsx b/src/game/OnlinePlay.tsx
new file mode 100644
index 0000000..737c33b
--- /dev/null
+++ b/src/game/OnlinePlay.tsx
@@ -0,0 +1,134 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { ArrowLeft, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-react';
+import { DEFAULT_RULESET, type Faction, type GameCard, type Stat } from '../../shared/game/index.ts';
+import { engineAction, resultView, uiActions, viewFromPlayerView } from './adapter.ts';
+import { toUICard } from './cards.ts';
+import { GameCard as GameCardFace } from './GameCard.tsx';
+import { MatchBoard } from './MatchBoard.tsx';
+import { online, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
+import type { GameMode, ResultView, UIAction } from './types.ts';
+
+const POLL_MS = 1000;
+const message = (e: unknown) => (e instanceof Error ? e.message : 'The host is unreachable.');
+
+/** Human vs human on a mode hosted by this node: lobby list → (draft) → match, all via the host API. */
+export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
+ mode: GameMode; playerName: string; onExit: () => void; onFinish: (r: ResultView) => void;
+}) {
+ const modeId = mode.remoteId ?? mode.id;
+ const hostOrigin = (mode.host.kind === 'peer' && mode.host.url) || location.origin;
+ const [lobbies, setLobbies] = useState();
+ const [seat, setSeat] = useState();
+ const [status, setStatus] = useState();
+ const [error, setError] = useState('');
+ const [busy, setBusy] = useState(false);
+ const inFlight = useRef(false);
+ const finished = useRef(false);
+
+ const refreshLobbies = useCallback(() => {
+ online.openLobbies(modeId).then(l => { setLobbies(l); setError(''); }, e => setError(message(e)));
+ }, [modeId]);
+ useEffect(() => {
+ if (seat) return;
+ refreshLobbies();
+ const t = setInterval(refreshLobbies, 4000);
+ return () => clearInterval(t);
+ }, [seat, refreshLobbies]);
+
+ const poll = useCallback(async () => {
+ if (!seat || inFlight.current) return;
+ inFlight.current = true;
+ try { setStatus(await online.status(seat)); setError(''); }
+ catch (e) { setError(message(e)); }
+ finally { inFlight.current = false; }
+ }, [seat]);
+ useEffect(() => {
+ if (!seat) return;
+ void poll();
+ const t = setInterval(() => { void poll(); }, POLL_MS);
+ return () => clearInterval(t);
+ }, [seat, poll]);
+
+ useEffect(() => {
+ const st = status?.state;
+ if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
+ finished.current = true;
+ const names = st.lanes.map(l => l.topic.name);
+ const t = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names)), 900);
+ return () => clearTimeout(t);
+ }, [status, seat, onFinish]);
+
+ const enter = async (fn: () => Promise) => {
+ setBusy(true); setError('');
+ try { setSeat(await fn()); } catch (e) { setError(message(e)); } finally { setBusy(false); }
+ };
+ const leave = async () => {
+ if (seat && status && !['finished', 'expired'].includes(status.phase)) await online.resign(seat).catch(() => {});
+ onExit();
+ };
+ const send = async (fn: () => Promise) => {
+ try { setStatus(await fn()); setError(''); } catch (e) { setError(message(e)); void poll(); }
+ };
+
+ // ----- lobby list -----
+ if (!seat) return
+ {mode.name.toUpperCase()} · ONLINE
+ Play a person
+ Matches run on this node{mode.host.kind === 'peer' ? `, hosted by ${mode.host.name}` : ''}. Decks come from the mode’s rules. You play as {playerName} .
+ Open lobbies
+
+ {lobbies === undefined ?
Loading…
+ : lobbies.length ? lobbies.map(l =>
enter(() => online.join(l.lobbyId, playerName, hostOrigin))}>
+
+ {String(l.host).slice(0, 24)} Waiting {Math.max(0, Math.round((Date.now() - l.createdAt) / 60000))} min · tap to join
+ )
+ :
No one is waiting. Create a lobby and share this page with a friend.
}
+
+ {error && {error}
}
+
+
Back
+
enter(() => online.create(modeId, playerName, hostOrigin))}> Create lobby
+
+ ;
+
+ const phase = status?.phase;
+ // ----- match -----
+ if ((phase === 'playing' || phase === 'finished') && status?.state) {
+ const view = viewFromPlayerView(status.state);
+ const legal = uiActions(status.legalActions ?? []);
+ const opp = status.players.find((_, i) => i !== seat.seat)?.name ?? 'Opponent';
+ const act = (a: UIAction) => {
+ if (a.type === 'concede') return void send(() => online.resign(seat));
+ return void send(() => online.act(seat, engineAction(a, seat.seat)));
+ };
+ return ;
+ }
+
+ // ----- draft -----
+ if (phase === 'drafting' && status?.draft) {
+ const mine = status.draft.toPick === seat.seat;
+ const toCard = (c: NonNullable['pool'][number]['card']) => toUICard({ ...c, rarity: 'Common', source: 'loaner', check: 'loaner',
+ faction: c.faction as Faction, home: c.home as Stat, trend: (Math.sign(c.trend) as -1 | 0 | 1) } as GameCard, DEFAULT_RULESET);
+ return
+ {mode.name.toUpperCase()} · DRAFT
+ {mine ? 'Your pick' : 'Opponent is picking…'}
+ Take turns picking cards for your deck. {Math.max(0, Math.round((status.draft.deadline - Date.now()) / 1000))} s left on this pick.
+ {status.draft.pool.map(p => void send(() => online.pick(seat, p.index)) : undefined} />)}
+ {error && {error}
}
+
+ ;
+ }
+
+ // ----- waiting / starting / expired -----
+ return
+ {mode.name.toUpperCase()} · LOBBY
+ {phase === 'expired' ? 'This lobby expired' : phase === 'waiting' ? 'Waiting for an opponent' : 'Starting…'}
+ {phase === 'expired' ? 'Nobody joined in time. Create a new lobby to try again.'
+ : <> {phase === 'waiting' ? 'Your lobby is listed for other players on this node.' : 'Setting up the match.'}>}
+ {error && {error}
}
+ {phase === 'expired' ? 'Back' : 'Cancel'}
+ ;
+}
diff --git a/src/game/PlaySection.tsx b/src/game/PlaySection.tsx
index a3425bc..6635139 100644
--- a/src/game/PlaySection.tsx
+++ b/src/game/PlaySection.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { CircleHelp, ExternalLink, Globe2, Layers3, Play, Server, Swords, UserRound } from 'lucide-react';
+import { CircleHelp, ExternalLink, Globe2, Layers3, Play, Server, Swords, UserRound, Users } from 'lucide-react';
import type { TestnetBlock } from '../../shared/testnet.ts';
import { Avatar } from '../auth/LoginButton.tsx';
import { BOTS, type Bot } from './bots.ts';
@@ -7,6 +7,8 @@ import { cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from
import { DeckBuilder, deckProblem, deckWarning } from './DeckBuilder.tsx';
import { CategoryIcon } from './GameCard.tsx';
import { MatchScreen } from './MatchScreen.tsx';
+import { lobbyName } from './online.ts';
+import { OnlinePlay } from './OnlinePlay.tsx';
import { Results } from './Results.tsx';
import { Tutorial } from './Tutorial.tsx';
import type { GameMode, ResultView } from './types.ts';
@@ -14,7 +16,7 @@ import { useAccount } from './useAccount.ts';
import { useModes } from './useModes.ts';
import './play.css';
-type Screen = 'lobby' | 'deck' | 'match' | 'results' | 'tutorial';
+type Screen = 'lobby' | 'deck' | 'match' | 'online' | 'results' | 'tutorial';
const DECK_KEY = 'wikideck-play-deck-v1';
const TUTORIAL_KEY = 'wikideck-play-tutorial-v1';
const store = {
@@ -46,12 +48,13 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
const warning = deckWarning(deck);
const opponent = useMemo(() => botDeck(seed, rules), [seed, rules]);
- const start = () => { setSeed(`${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`); setScreen('match'); };
+ const [lastOnline, setLastOnline] = useState(false);
+ const start = () => { setLastOnline(false); setSeed(`${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`); setScreen('match'); };
const finish = useCallback((r: ResultView) => { setResult(r); setScreen('results'); }, []);
useEffect(() => { window.scrollTo?.({ top: 0 }); }, [screen]);
// While a match is on screen, hide the floating eom.dev account button (it sits over the dock on phones).
useEffect(() => {
- document.documentElement.classList.toggle('wd-in-match', screen === 'match');
+ document.documentElement.classList.toggle('wd-in-match', screen === 'match' || screen === 'online');
return () => document.documentElement.classList.remove('wd-in-match');
}, [screen]);
@@ -59,9 +62,11 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
if (screen === 'deck') return setScreen('lobby')}
onSave={d => { const ids = d.map(c => c.id); store.set(DECK_KEY, JSON.stringify(ids)); setSavedIds(ids); setScreen('lobby'); }} />;
if (screen === 'match') return ;
- if (screen === 'results' && result) return setScreen('lobby')} />;
+ if (screen === 'online') return setScreen('lobby')} onFinish={finish} />;
+ if (screen === 'results' && result) return setScreen('online') : start} onLobby={() => setScreen('lobby')} />;
const remote = mode.host.kind === 'peer' && !mode.host.self ? mode.host : null;
+ const hosted = mode.host.kind === 'peer' && mode.host.self;
return
PLAY · OFF-CHAIN MATCHES
Play WikiDeck
@@ -106,6 +111,7 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
setScreen('tutorial')}> How to play
+ {hosted &&
{ setLastOnline(true); setScreen('online'); }}> Play a person }
Play vs {bot.name}
>}
diff --git a/src/game/adapter.ts b/src/game/adapter.ts
index 8ad96c1..e70e38c 100644
--- a/src/game/adapter.ts
+++ b/src/game/adapter.ts
@@ -1,7 +1,7 @@
// The single place the Play UI touches the engine (import only from shared/game/index.ts).
import {
DEFAULT_RULESET, applyAction, actionProblem, createMatch, isOver, laneCapacity, legalActions, result, viewFor,
- type Action, type CardInPlay, type LogEvent, type MatchState, type PlayerId, type Ruleset,
+ type Action, type CardInPlay, type LogEvent, type MatchResult, type MatchState, type PlayerId, type PlayerView, type Ruleset,
} from '../../shared/game/index.ts';
import { toUICard } from './cards.ts';
import { portalInfo, STAT_LABEL } from './rulesText.ts';
@@ -63,51 +63,70 @@ export const engine = {
return actionProblem(state, toEngine(action, player));
},
view(state: MatchState, me: PlayerId): MatchView {
- const v = viewFor(state, me);
- const rules = v.ruleset;
const titles = new Map
();
for (const p of state.players) for (const c of [...p.hand, ...p.deck]) titles.set(c.cardId, c.title);
for (const l of state.lanes) for (const side of l.cards) for (const c of side) titles.set(c.card.cardId, c.card.title);
- const handUI = v.hand.map(c => toUICard(c, rules));
- const onBoard = (c: CardInPlay, power: number, stat: string, allOnTopic: boolean) =>
- toUICard(c.card, rules, { id: `${c.owner}:${c.card.cardId}`, power, onTopic: allOnTopic || c.card.home === stat }); // both seats may share loaner cardIds
- const lanes: LaneView[] = v.lanes.map((lane, i) => {
- const portal = lane.portalRevealed ? portalInfo(lane.topic.portal, lane.topic.id, rules) : undefined;
- const allOn = lane.portalRevealed && lane.topic.portal === 'disambiguation';
- return {
- index: i, stat: lane.topic.stat, revealed: lane.portalRevealed,
- name: lane.portalRevealed ? lane.topic.name : STAT_LABEL[lane.topic.stat],
- modifier: portal, portalNote: lane.portalRevealed ? undefined : `Topic and Portal reveal on turn ${rules.portalReveal[i]}`,
- mine: lane.cards[0].map((c, k) => onBoard(c, lane.cardPower[0][k], lane.topic.stat, allOn)),
- theirs: lane.cards[1].map((c, k) => onBoard(c, lane.cardPower[1][k], lane.topic.stat, allOn)),
- staged: v.queue.filter(q => q.lane === i).flatMap(q => {
- const c = state.players[me].hand.find(h => h.cardId === q.cardId);
- return c ? [toUICard(c, rules)] : [];
- }),
- myPower: lane.power[0], theirPower: lane.power[1], leader: lane.leader, capacity: laneCapacity(state, i),
- };
- });
- const queued = new Set(v.queue.map(q => q.cardId));
const log = state.log.filter(e => e.t !== 'draw')
.map(e => logLine(e, me, id => titles.get(id) ?? 'a card')).filter((x): x is string => !!x).slice(-30);
- return {
- me, turn: v.turn, maxTurns: rules.turns, energy: v.energyLeft, maxEnergy: v.energy,
- hand: handUI.filter(c => !queued.has(c.id)), deckCount: v.deckCount,
- oppHandCount: v.opponent.handCount, oppDeckCount: v.opponent.deckCount, oppQueued: v.opponent.queuedCount,
- lanes, log, waitingForOpponent: v.committed && v.phase !== 'over', over: v.phase === 'over',
- engine: { state, seat: me },
- };
+ return { ...viewFromPlayerView(viewFor(state, me), { log, capacity: i => laneCapacity(state, i) }), engine: { state, seat: me } };
},
isOver: (s: MatchState) => isOver(s),
result(state: MatchState, me: PlayerId): ResultView {
- const r = result(state)!;
- const opp: PlayerId = me === 0 ? 1 : 0;
- return {
- winner: r.winner, turns: r.turns, reason: r.reason, totalPower: [r.totalPower[me], r.totalPower[opp]],
- lanes: r.lanePower.map((pw, i) => {
- const a = pw[me], b = pw[opp];
- return { name: state.lanes[i].topic.name, myPower: a, theirPower: b, winner: a === b ? null : a > b ? me : opp };
- }),
- };
+ return resultView(result(state)!, me, state.lanes.map(l => l.topic.name));
},
};
+
+/** Stub-style Portals cap a lane; online views don't carry state, so read the cap from the ruleset. */
+function capacityFromView(v: PlayerView, i: number): number {
+ const t = v.lanes[i].topic, r = v.ruleset;
+ if (v.lanes[i].portalRevealed && t.portal === 'stub') return (r.portalParams[t.id] ?? r.portalParams.stub)?.capacity ?? Math.min(2, r.laneCapacity);
+ return r.laneCapacity;
+}
+
+/** Build the screen model from what one seat may see (local engine or a hosting node). */
+export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capacity?: (lane: number) => number } = {}): MatchView {
+ const rules = v.ruleset;
+ const me = v.you;
+ const onBoard = (c: CardInPlay, power: number, stat: string, allOnTopic: boolean) =>
+ toUICard(c.card, rules, { id: `${c.owner}:${c.card.cardId}`, power, onTopic: allOnTopic || c.card.home === stat }); // both seats may share loaner cardIds
+ const lanes: LaneView[] = v.lanes.map((lane, i) => {
+ const portal = lane.portalRevealed ? portalInfo(lane.topic.portal, lane.topic.id, rules) : undefined;
+ const allOn = lane.portalRevealed && lane.topic.portal === 'disambiguation';
+ return {
+ index: i, stat: lane.topic.stat, revealed: lane.portalRevealed,
+ name: lane.portalRevealed ? lane.topic.name : STAT_LABEL[lane.topic.stat],
+ modifier: portal, portalNote: lane.portalRevealed ? undefined : `Topic and Portal reveal on turn ${rules.portalReveal[i]}`,
+ mine: lane.cards[0].map((c, k) => onBoard(c, lane.cardPower[0][k], lane.topic.stat, allOn)),
+ theirs: lane.cards[1].map((c, k) => onBoard(c, lane.cardPower[1][k], lane.topic.stat, allOn)),
+ staged: v.queue.filter(q => q.lane === i).flatMap(q => {
+ const c = v.hand.find(h => h.cardId === q.cardId);
+ return c ? [toUICard(c, rules)] : [];
+ }),
+ myPower: lane.power[0], theirPower: lane.power[1], leader: lane.leader,
+ capacity: opts.capacity ? opts.capacity(i) : capacityFromView(v, i),
+ };
+ });
+ const queued = new Set(v.queue.map(q => q.cardId));
+ return {
+ me, turn: v.turn, maxTurns: rules.turns, energy: v.energyLeft, maxEnergy: v.energy,
+ hand: v.hand.filter(c => !queued.has(c.cardId)).map(c => toUICard(c, rules)), deckCount: v.deckCount,
+ oppHandCount: v.opponent.handCount, oppDeckCount: v.opponent.deckCount, oppQueued: v.opponent.queuedCount,
+ lanes, log: opts.log ?? [], waitingForOpponent: v.committed && v.phase !== 'over', over: v.phase === 'over',
+ };
+}
+
+/** Results from `me`'s point of view (winner stays an absolute seat; the screen compares it to `me`). */
+export function resultView(r: MatchResult, me: PlayerId, laneNames: string[]): ResultView {
+ const opp: PlayerId = me === 0 ? 1 : 0;
+ return {
+ winner: r.winner, turns: r.turns, reason: r.reason, totalPower: [r.totalPower[me], r.totalPower[opp]],
+ lanes: r.lanePower.map((pw, i) => {
+ const a = pw[me], b = pw[opp];
+ return { name: laneNames[i] ?? `Topic ${i + 1}`, myPower: a, theirPower: b, winner: a === b ? null : a > b ? me : opp };
+ }),
+ };
+}
+
+/** Engine actions from a host's legalActions, mapped for the UI (the host checks the seat). */
+export const uiActions = (acts: Action[]): UIAction[] => acts.map(toUI);
+export const engineAction = toEngine;
diff --git a/src/game/online.ts b/src/game/online.ts
new file mode 100644
index 0000000..1a8f4cc
--- /dev/null
+++ b/src/game/online.ts
@@ -0,0 +1,64 @@
+// Client for lobbies hosted by this node (modes team, docs/game/HOSTING.md §3). Same-origin only:
+// peers' modes are opened on the peer's own site. Every response is untrusted input.
+import type { Action, PlayerView } from '../../shared/game/index.ts';
+
+export type LobbySeat = { lobbyId: string; seat: 0 | 1; token: string };
+export type DraftCard = { index: number; takenBy: 0 | 1 | null; card: { cardId: string; title: string; pageId: number | null; faction: string; cost: number; power: number; home: string; trend: number; keyword: string | null } };
+export type LobbyStatus = {
+ lobbyId: string; phase: 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
+ seat: 0 | 1 | null; players: { id: string; name: string }[];
+ outcome: { winner: 0 | 1 | null; reason: string } | null;
+ state?: PlayerView; legalActions?: Action[];
+ draft?: { pool: DraftCard[]; toPick: 0 | 1 | null; deadline: number };
+};
+export type OpenLobby = { lobbyId: string; host: string; createdAt: number };
+
+const MASTER_KEY = 'wikideck-player-master';
+const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+
+function masterSecret(): string {
+ try {
+ const existing = localStorage.getItem(MASTER_KEY);
+ if (existing && /^[A-Za-z0-9_-]{43}$/.test(existing)) return existing;
+ const fresh = b64url(crypto.getRandomValues(new Uint8Array(32)));
+ localStorage.setItem(MASTER_KEY, fresh);
+ return fresh;
+ } catch { return b64url(crypto.getRandomValues(new Uint8Array(32))); } // storage blocked: per-session identity
+}
+
+/**
+ * Per-host player secret: base64url(HMAC-SHA256(master, hostOrigin)), 43 chars. A host derives the
+ * leaderboard id from it, so a malicious host can't replay it on another host (night-review, #5).
+ */
+export async function playerSecret(hostOrigin: string): Promise {
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(masterSecret()), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
+ return b64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(hostOrigin))));
+}
+
+/** Host display names allow 1–24 letters, digits, spaces and _ . - */
+export function lobbyName(name: string | undefined): string {
+ const clean = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} _.-]/gu, '').trim().slice(0, 24);
+ return clean || `Guest ${masterSecret().slice(0, 4)}`;
+}
+
+async function call(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise {
+ const res = await fetch(`/api/game/${path}`, {
+ method: init.method ?? (init.body === undefined ? 'GET' : 'POST'), cache: 'no-store', signal: AbortSignal.timeout(10000),
+ headers: { ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(init.token ? { Authorization: `Bearer ${init.token}` } : {}) },
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
+ });
+ const data = res.headers.get('content-type')?.includes('json') ? await res.json().catch(() => ({})) : {};
+ if (!res.ok) throw new Error(typeof data?.error === 'string' ? data.error.slice(0, 200) : `The host answered ${res.status}.`);
+ return data as T;
+}
+
+const id = (s: string) => encodeURIComponent(s);
+export const online = {
+ openLobbies: (modeId: string) => call<{ lobbies: OpenLobby[] }>(`modes/${id(modeId)}/lobbies`).then(r => Array.isArray(r.lobbies) ? r.lobbies.slice(0, 50) : []),
+ create: async (modeId: string, name: string, hostOrigin: string) => call(`modes/${id(modeId)}/lobbies`, { body: { name, secret: await playerSecret(hostOrigin) } }),
+ join: async (lobbyId: string, name: string, hostOrigin: string) => call(`lobbies/${id(lobbyId)}/join`, { body: { name, secret: await playerSecret(hostOrigin) } }),
+ status: (s: LobbySeat) => call(`lobbies/${id(s.lobbyId)}`, { token: s.token }),
+ act: (s: LobbySeat, action: Action) => call(`lobbies/${id(s.lobbyId)}/actions`, { body: { action }, token: s.token }),
+ pick: (s: LobbySeat, index: number) => call(`lobbies/${id(s.lobbyId)}/pick`, { body: { index }, token: s.token }),
+ resign: (s: LobbySeat) => call(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, token: s.token }),
+};
diff --git a/src/game/types.ts b/src/game/types.ts
index 8a30c4e..ff7dd74 100644
--- a/src/game/types.ts
+++ b/src/game/types.ts
@@ -77,6 +77,8 @@ export type ResultView = {
export type GameMode = {
id: string;
+ /** The host's own mode id (for /api/game/modes/:id/...). */
+ remoteId?: string;
name: string;
description: string;
host: { kind: 'local' } | { kind: 'peer'; name: string; url: string; self: boolean };
diff --git a/src/game/useModes.ts b/src/game/useModes.ts
index 9eb4391..7ee02f8 100644
--- a/src/game/useModes.ts
+++ b/src/game/useModes.ts
@@ -27,7 +27,7 @@ export function parseModeList(data: unknown, where: { self: boolean; origin: str
const id = str(m?.id, 64), name = str(m?.name, 60);
const ruleset = rulesFor(m?.rules);
if (!id || !name || !ruleset) return [];
- return [{ id: `${where.self ? 'self' : origin}:${id}`, name, description: str(m?.description, 280) ?? '',
+ return [{ id: `${where.self ? 'self' : origin}:${id}`, remoteId: id, name, description: str(m?.description, 280) ?? '',
host: { kind: 'peer', name: operator, url: /^https?:\/\//.test(origin) ? origin : '', self: where.self },
ruleset, players: num(stats?.playersOnline), matchesPlayed: num(stats?.matchesPlayed) }];
});
--
2.54.0
From efea1b70c7cc5a4ae1b3169902a62ed6858dec7d Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:43:00 -0500
Subject: [PATCH 11/14] Play: online results from each player's side; finish
timer survives polls
Found with a two-browser test against the modes host: the seat-1 player
saw Defeat after winning (ResultView is now viewer-relative), and a poll
could cancel the move to the results screen.
Co-Authored-By: Claude Opus 5.5
---
src/game/OnlinePlay.tsx | 272 ++++++++++++++++++++--------------------
src/game/adapter.ts | 7 +-
src/game/online.ts | 128 +++++++++----------
src/game/types.ts | 3 +-
tests/ui-play.test.ts | 214 +++++++++++++++----------------
5 files changed, 316 insertions(+), 308 deletions(-)
diff --git a/src/game/OnlinePlay.tsx b/src/game/OnlinePlay.tsx
index 737c33b..ae8f527 100644
--- a/src/game/OnlinePlay.tsx
+++ b/src/game/OnlinePlay.tsx
@@ -1,134 +1,138 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
-import { ArrowLeft, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-react';
-import { DEFAULT_RULESET, type Faction, type GameCard, type Stat } from '../../shared/game/index.ts';
-import { engineAction, resultView, uiActions, viewFromPlayerView } from './adapter.ts';
-import { toUICard } from './cards.ts';
-import { GameCard as GameCardFace } from './GameCard.tsx';
-import { MatchBoard } from './MatchBoard.tsx';
-import { online, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
-import type { GameMode, ResultView, UIAction } from './types.ts';
-
-const POLL_MS = 1000;
-const message = (e: unknown) => (e instanceof Error ? e.message : 'The host is unreachable.');
-
-/** Human vs human on a mode hosted by this node: lobby list → (draft) → match, all via the host API. */
-export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
- mode: GameMode; playerName: string; onExit: () => void; onFinish: (r: ResultView) => void;
-}) {
- const modeId = mode.remoteId ?? mode.id;
- const hostOrigin = (mode.host.kind === 'peer' && mode.host.url) || location.origin;
- const [lobbies, setLobbies] = useState();
- const [seat, setSeat] = useState();
- const [status, setStatus] = useState();
- const [error, setError] = useState('');
- const [busy, setBusy] = useState(false);
- const inFlight = useRef(false);
- const finished = useRef(false);
-
- const refreshLobbies = useCallback(() => {
- online.openLobbies(modeId).then(l => { setLobbies(l); setError(''); }, e => setError(message(e)));
- }, [modeId]);
- useEffect(() => {
- if (seat) return;
- refreshLobbies();
- const t = setInterval(refreshLobbies, 4000);
- return () => clearInterval(t);
- }, [seat, refreshLobbies]);
-
- const poll = useCallback(async () => {
- if (!seat || inFlight.current) return;
- inFlight.current = true;
- try { setStatus(await online.status(seat)); setError(''); }
- catch (e) { setError(message(e)); }
- finally { inFlight.current = false; }
- }, [seat]);
- useEffect(() => {
- if (!seat) return;
- void poll();
- const t = setInterval(() => { void poll(); }, POLL_MS);
- return () => clearInterval(t);
- }, [seat, poll]);
-
- useEffect(() => {
- const st = status?.state;
- if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
- finished.current = true;
- const names = st.lanes.map(l => l.topic.name);
- const t = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names)), 900);
- return () => clearTimeout(t);
- }, [status, seat, onFinish]);
-
- const enter = async (fn: () => Promise) => {
- setBusy(true); setError('');
- try { setSeat(await fn()); } catch (e) { setError(message(e)); } finally { setBusy(false); }
- };
- const leave = async () => {
- if (seat && status && !['finished', 'expired'].includes(status.phase)) await online.resign(seat).catch(() => {});
- onExit();
- };
- const send = async (fn: () => Promise) => {
- try { setStatus(await fn()); setError(''); } catch (e) { setError(message(e)); void poll(); }
- };
-
- // ----- lobby list -----
- if (!seat) return
- {mode.name.toUpperCase()} · ONLINE
- Play a person
- Matches run on this node{mode.host.kind === 'peer' ? `, hosted by ${mode.host.name}` : ''}. Decks come from the mode’s rules. You play as {playerName} .
- Open lobbies
-
- {lobbies === undefined ?
Loading…
- : lobbies.length ? lobbies.map(l =>
enter(() => online.join(l.lobbyId, playerName, hostOrigin))}>
-
- {String(l.host).slice(0, 24)} Waiting {Math.max(0, Math.round((Date.now() - l.createdAt) / 60000))} min · tap to join
- )
- :
No one is waiting. Create a lobby and share this page with a friend.
}
-
- {error && {error}
}
-
-
Back
-
enter(() => online.create(modeId, playerName, hostOrigin))}> Create lobby
-
- ;
-
- const phase = status?.phase;
- // ----- match -----
- if ((phase === 'playing' || phase === 'finished') && status?.state) {
- const view = viewFromPlayerView(status.state);
- const legal = uiActions(status.legalActions ?? []);
- const opp = status.players.find((_, i) => i !== seat.seat)?.name ?? 'Opponent';
- const act = (a: UIAction) => {
- if (a.type === 'concede') return void send(() => online.resign(seat));
- return void send(() => online.act(seat, engineAction(a, seat.seat)));
- };
- return ;
- }
-
- // ----- draft -----
- if (phase === 'drafting' && status?.draft) {
- const mine = status.draft.toPick === seat.seat;
- const toCard = (c: NonNullable['pool'][number]['card']) => toUICard({ ...c, rarity: 'Common', source: 'loaner', check: 'loaner',
- faction: c.faction as Faction, home: c.home as Stat, trend: (Math.sign(c.trend) as -1 | 0 | 1) } as GameCard, DEFAULT_RULESET);
- return
- {mode.name.toUpperCase()} · DRAFT
- {mine ? 'Your pick' : 'Opponent is picking…'}
- Take turns picking cards for your deck. {Math.max(0, Math.round((status.draft.deadline - Date.now()) / 1000))} s left on this pick.
- {status.draft.pool.map(p => void send(() => online.pick(seat, p.index)) : undefined} />)}
- {error && {error}
}
-
- ;
- }
-
- // ----- waiting / starting / expired -----
- return
- {mode.name.toUpperCase()} · LOBBY
- {phase === 'expired' ? 'This lobby expired' : phase === 'waiting' ? 'Waiting for an opponent' : 'Starting…'}
- {phase === 'expired' ? 'Nobody joined in time. Create a new lobby to try again.'
- : <> {phase === 'waiting' ? 'Your lobby is listed for other players on this node.' : 'Setting up the match.'}>}
- {error && {error}
}
- {phase === 'expired' ? 'Back' : 'Cancel'}
- ;
-}
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { ArrowLeft, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-react';
+import { DEFAULT_RULESET, type Faction, type GameCard, type Stat } from '../../shared/game/index.ts';
+import { engineAction, resultView, uiActions, viewFromPlayerView } from './adapter.ts';
+import { toUICard } from './cards.ts';
+import { GameCard as GameCardFace } from './GameCard.tsx';
+import { MatchBoard } from './MatchBoard.tsx';
+import { online, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
+import type { GameMode, ResultView, UIAction } from './types.ts';
+
+const POLL_MS = 1000;
+const message = (e: unknown) => (e instanceof Error ? e.message : 'The host is unreachable.');
+
+/** Human vs human on a mode hosted by this node: lobby list → (draft) → match, all via the host API. */
+export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
+ mode: GameMode; playerName: string; onExit: () => void; onFinish: (r: ResultView) => void;
+}) {
+ const modeId = mode.remoteId ?? mode.id;
+ const hostOrigin = (mode.host.kind === 'peer' && mode.host.url) || location.origin;
+ const [lobbies, setLobbies] = useState();
+ const [seat, setSeat] = useState();
+ const [status, setStatus] = useState();
+ const [error, setError] = useState('');
+ const [busy, setBusy] = useState(false);
+ const inFlight = useRef(false);
+ const finished = useRef(false);
+ const done = status?.phase === 'finished' || status?.phase === 'expired';
+
+ const refreshLobbies = useCallback(() => {
+ online.openLobbies(modeId).then(l => { setLobbies(l); setError(''); }, e => setError(message(e)));
+ }, [modeId]);
+ useEffect(() => {
+ if (seat) return;
+ refreshLobbies();
+ const t = setInterval(refreshLobbies, 4000);
+ return () => clearInterval(t);
+ }, [seat, refreshLobbies]);
+
+ const poll = useCallback(async () => {
+ if (!seat || inFlight.current) return;
+ inFlight.current = true;
+ try { setStatus(await online.status(seat)); setError(''); }
+ catch (e) { setError(message(e)); }
+ finally { inFlight.current = false; }
+ }, [seat]);
+ useEffect(() => {
+ if (!seat || done) return;
+ void poll();
+ const t = setInterval(() => { void poll(); }, POLL_MS);
+ return () => clearInterval(t);
+ }, [seat, poll, done]);
+
+ // Once finished, stop polling and show results after a beat. The timer must survive later
+ // re-renders, so it is only cleared on unmount.
+ const finishTimer = useRef>(undefined);
+ useEffect(() => {
+ const st = status?.state;
+ if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
+ finished.current = true;
+ const names = st.lanes.map(l => l.topic.name);
+ finishTimer.current = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names)), 900);
+ }, [status, seat, onFinish]);
+ useEffect(() => () => clearTimeout(finishTimer.current), []);
+
+ const enter = async (fn: () => Promise) => {
+ setBusy(true); setError('');
+ try { setSeat(await fn()); } catch (e) { setError(message(e)); } finally { setBusy(false); }
+ };
+ const leave = async () => {
+ if (seat && status && !['finished', 'expired'].includes(status.phase)) await online.resign(seat).catch(() => {});
+ onExit();
+ };
+ const send = async (fn: () => Promise) => {
+ try { setStatus(await fn()); setError(''); } catch (e) { setError(message(e)); void poll(); }
+ };
+
+ // ----- lobby list -----
+ if (!seat) return
+ {mode.name.toUpperCase()} · ONLINE
+ Play a person
+ Matches run on this node{mode.host.kind === 'peer' ? `, hosted by ${mode.host.name}` : ''}. Decks come from the mode’s rules. You play as {playerName} .
+ Open lobbies
+
+ {lobbies === undefined ?
Loading…
+ : lobbies.length ? lobbies.map(l =>
enter(() => online.join(l.lobbyId, playerName, hostOrigin))}>
+
+ {String(l.host).slice(0, 24)} Waiting {Math.max(0, Math.round((Date.now() - l.createdAt) / 60000))} min · tap to join
+ )
+ :
No one is waiting. Create a lobby and share this page with a friend.
}
+
+ {error && {error}
}
+
+
Back
+
enter(() => online.create(modeId, playerName, hostOrigin))}> Create lobby
+
+ ;
+
+ const phase = status?.phase;
+ // ----- match -----
+ if ((phase === 'playing' || phase === 'finished') && status?.state) {
+ const view = viewFromPlayerView(status.state);
+ const legal = uiActions(status.legalActions ?? []);
+ const opp = status.players.find((_, i) => i !== seat.seat)?.name ?? 'Opponent';
+ const act = (a: UIAction) => {
+ if (a.type === 'concede') return void send(() => online.resign(seat));
+ return void send(() => online.act(seat, engineAction(a, seat.seat)));
+ };
+ return ;
+ }
+
+ // ----- draft -----
+ if (phase === 'drafting' && status?.draft) {
+ const mine = status.draft.toPick === seat.seat;
+ const toCard = (c: NonNullable['pool'][number]['card']) => toUICard({ ...c, rarity: 'Common', source: 'loaner', check: 'loaner',
+ faction: c.faction as Faction, home: c.home as Stat, trend: (Math.sign(c.trend) as -1 | 0 | 1) } as GameCard, DEFAULT_RULESET);
+ return
+ {mode.name.toUpperCase()} · DRAFT
+ {mine ? 'Your pick' : 'Opponent is picking…'}
+ Take turns picking cards for your deck. {Math.max(0, Math.round((status.draft.deadline - Date.now()) / 1000))} s left on this pick.
+ {status.draft.pool.map(p => void send(() => online.pick(seat, p.index)) : undefined} />)}
+ {error && {error}
}
+
+ ;
+ }
+
+ // ----- waiting / starting / expired -----
+ return
+ {mode.name.toUpperCase()} · LOBBY
+ {phase === 'expired' ? 'This lobby expired' : phase === 'waiting' ? 'Waiting for an opponent' : 'Starting…'}
+ {phase === 'expired' ? 'Nobody joined in time. Create a new lobby to try again.'
+ : <> {phase === 'waiting' ? 'Your lobby is listed for other players on this node.' : 'Setting up the match.'}>}
+ {error && {error}
}
+ {phase === 'expired' ? 'Back' : 'Cancel'}
+ ;
+}
diff --git a/src/game/adapter.ts b/src/game/adapter.ts
index e70e38c..5aaa7fc 100644
--- a/src/game/adapter.ts
+++ b/src/game/adapter.ts
@@ -115,14 +115,15 @@ export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capaci
};
}
-/** Results from `me`'s point of view (winner stays an absolute seat; the screen compares it to `me`). */
+/** Results from `me`'s point of view: in a ResultView, 0 always means "you" and 1 "your opponent". */
export function resultView(r: MatchResult, me: PlayerId, laneNames: string[]): ResultView {
const opp: PlayerId = me === 0 ? 1 : 0;
return {
- winner: r.winner, turns: r.turns, reason: r.reason, totalPower: [r.totalPower[me], r.totalPower[opp]],
+ winner: r.winner === null ? null : r.winner === me ? 0 : 1, turns: r.turns, reason: r.reason,
+ totalPower: [r.totalPower[me], r.totalPower[opp]],
lanes: r.lanePower.map((pw, i) => {
const a = pw[me], b = pw[opp];
- return { name: laneNames[i] ?? `Topic ${i + 1}`, myPower: a, theirPower: b, winner: a === b ? null : a > b ? me : opp };
+ return { name: laneNames[i] ?? `Topic ${i + 1}`, myPower: a, theirPower: b, winner: a === b ? null : a > b ? 0 : 1 };
}),
};
}
diff --git a/src/game/online.ts b/src/game/online.ts
index 1a8f4cc..52d8e86 100644
--- a/src/game/online.ts
+++ b/src/game/online.ts
@@ -1,64 +1,64 @@
-// Client for lobbies hosted by this node (modes team, docs/game/HOSTING.md §3). Same-origin only:
-// peers' modes are opened on the peer's own site. Every response is untrusted input.
-import type { Action, PlayerView } from '../../shared/game/index.ts';
-
-export type LobbySeat = { lobbyId: string; seat: 0 | 1; token: string };
-export type DraftCard = { index: number; takenBy: 0 | 1 | null; card: { cardId: string; title: string; pageId: number | null; faction: string; cost: number; power: number; home: string; trend: number; keyword: string | null } };
-export type LobbyStatus = {
- lobbyId: string; phase: 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
- seat: 0 | 1 | null; players: { id: string; name: string }[];
- outcome: { winner: 0 | 1 | null; reason: string } | null;
- state?: PlayerView; legalActions?: Action[];
- draft?: { pool: DraftCard[]; toPick: 0 | 1 | null; deadline: number };
-};
-export type OpenLobby = { lobbyId: string; host: string; createdAt: number };
-
-const MASTER_KEY = 'wikideck-player-master';
-const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
-
-function masterSecret(): string {
- try {
- const existing = localStorage.getItem(MASTER_KEY);
- if (existing && /^[A-Za-z0-9_-]{43}$/.test(existing)) return existing;
- const fresh = b64url(crypto.getRandomValues(new Uint8Array(32)));
- localStorage.setItem(MASTER_KEY, fresh);
- return fresh;
- } catch { return b64url(crypto.getRandomValues(new Uint8Array(32))); } // storage blocked: per-session identity
-}
-
-/**
- * Per-host player secret: base64url(HMAC-SHA256(master, hostOrigin)), 43 chars. A host derives the
- * leaderboard id from it, so a malicious host can't replay it on another host (night-review, #5).
- */
-export async function playerSecret(hostOrigin: string): Promise {
- const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(masterSecret()), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
- return b64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(hostOrigin))));
-}
-
-/** Host display names allow 1–24 letters, digits, spaces and _ . - */
-export function lobbyName(name: string | undefined): string {
- const clean = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} _.-]/gu, '').trim().slice(0, 24);
- return clean || `Guest ${masterSecret().slice(0, 4)}`;
-}
-
-async function call(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise {
- const res = await fetch(`/api/game/${path}`, {
- method: init.method ?? (init.body === undefined ? 'GET' : 'POST'), cache: 'no-store', signal: AbortSignal.timeout(10000),
- headers: { ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(init.token ? { Authorization: `Bearer ${init.token}` } : {}) },
- ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
- });
- const data = res.headers.get('content-type')?.includes('json') ? await res.json().catch(() => ({})) : {};
- if (!res.ok) throw new Error(typeof data?.error === 'string' ? data.error.slice(0, 200) : `The host answered ${res.status}.`);
- return data as T;
-}
-
-const id = (s: string) => encodeURIComponent(s);
-export const online = {
- openLobbies: (modeId: string) => call<{ lobbies: OpenLobby[] }>(`modes/${id(modeId)}/lobbies`).then(r => Array.isArray(r.lobbies) ? r.lobbies.slice(0, 50) : []),
- create: async (modeId: string, name: string, hostOrigin: string) => call(`modes/${id(modeId)}/lobbies`, { body: { name, secret: await playerSecret(hostOrigin) } }),
- join: async (lobbyId: string, name: string, hostOrigin: string) => call(`lobbies/${id(lobbyId)}/join`, { body: { name, secret: await playerSecret(hostOrigin) } }),
- status: (s: LobbySeat) => call(`lobbies/${id(s.lobbyId)}`, { token: s.token }),
- act: (s: LobbySeat, action: Action) => call(`lobbies/${id(s.lobbyId)}/actions`, { body: { action }, token: s.token }),
- pick: (s: LobbySeat, index: number) => call(`lobbies/${id(s.lobbyId)}/pick`, { body: { index }, token: s.token }),
- resign: (s: LobbySeat) => call(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, token: s.token }),
-};
+// Client for lobbies hosted by this node (modes team, docs/game/HOSTING.md §3). Same-origin only:
+// peers' modes are opened on the peer's own site. Every response is untrusted input.
+import type { Action, PlayerView } from '../../shared/game/index.ts';
+
+export type LobbySeat = { lobbyId: string; seat: 0 | 1; token: string };
+export type DraftCard = { index: number; takenBy: 0 | 1 | null; card: { cardId: string; title: string; pageId: number | null; faction: string; cost: number; power: number; home: string; trend: number; keyword: string | null } };
+export type LobbyStatus = {
+ lobbyId: string; phase: 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
+ seat: 0 | 1 | null; players: { id: string; name: string }[];
+ outcome: { winner: 0 | 1 | null; reason: string } | null;
+ state?: PlayerView; legalActions?: Action[];
+ draft?: { pool: DraftCard[]; toPick: 0 | 1 | null; deadline: number };
+};
+export type OpenLobby = { lobbyId: string; host: string; createdAt: number };
+
+const MASTER_KEY = 'wikideck-player-master';
+const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+
+function masterSecret(): string {
+ try {
+ const existing = localStorage.getItem(MASTER_KEY);
+ if (existing && /^[A-Za-z0-9_-]{43}$/.test(existing)) return existing;
+ const fresh = b64url(crypto.getRandomValues(new Uint8Array(32)));
+ localStorage.setItem(MASTER_KEY, fresh);
+ return fresh;
+ } catch { return b64url(crypto.getRandomValues(new Uint8Array(32))); } // storage blocked: per-session identity
+}
+
+/**
+ * Per-host player secret: base64url(HMAC-SHA256(master, hostOrigin)), 43 chars. A host derives the
+ * leaderboard id from it, so a malicious host can't replay it on another host (night-review, #5).
+ */
+export async function playerSecret(hostOrigin: string): Promise {
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(masterSecret()), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
+ return b64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(hostOrigin))));
+}
+
+/** Host display names allow 1–24 letters, digits, spaces and _ . - */
+export function lobbyName(name: string | undefined): string {
+ const clean = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} _.-]/gu, '').trim().slice(0, 24);
+ return clean || `Guest ${masterSecret().slice(0, 4)}`;
+}
+
+async function call(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise {
+ const res = await fetch(`/api/game/${path}`, {
+ method: init.method ?? (init.body === undefined ? 'GET' : 'POST'), cache: 'no-store', signal: AbortSignal.timeout(10000),
+ headers: { ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(init.token ? { Authorization: `Bearer ${init.token}` } : {}) },
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
+ });
+ const data = res.headers.get('content-type')?.includes('json') ? await res.json().catch(() => ({})) : {};
+ if (!res.ok) throw new Error(typeof data?.error === 'string' ? data.error.slice(0, 200) : `The host answered ${res.status}.`);
+ return data as T;
+}
+
+const id = (s: string) => encodeURIComponent(s);
+export const online = {
+ openLobbies: (modeId: string) => call<{ lobbies: OpenLobby[] }>(`modes/${id(modeId)}/lobbies`).then(r => Array.isArray(r.lobbies) ? r.lobbies.slice(0, 50) : []),
+ create: async (modeId: string, name: string, hostOrigin: string) => call(`modes/${id(modeId)}/lobbies`, { body: { name, secret: await playerSecret(hostOrigin) } }),
+ join: async (lobbyId: string, name: string, hostOrigin: string) => call(`lobbies/${id(lobbyId)}/join`, { body: { name, secret: await playerSecret(hostOrigin) } }),
+ status: (s: LobbySeat) => call(`lobbies/${id(s.lobbyId)}`, { token: s.token }),
+ act: (s: LobbySeat, action: Action) => call(`lobbies/${id(s.lobbyId)}/actions`, { body: { action }, token: s.token }),
+ pick: (s: LobbySeat, index: number) => call(`lobbies/${id(s.lobbyId)}/pick`, { body: { index }, token: s.token }),
+ resign: (s: LobbySeat) => call(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, token: s.token }),
+};
diff --git a/src/game/types.ts b/src/game/types.ts
index ff7dd74..69612ce 100644
--- a/src/game/types.ts
+++ b/src/game/types.ts
@@ -67,8 +67,9 @@ export type UIAction = (
| { type: 'concede' }
) & { engine?: Action };
+/** Always from the viewer's side: 0 = you, 1 = your opponent, null = draw. */
export type ResultView = {
- winner: PlayerIndex | null; // null = draw
+ winner: PlayerIndex | null;
lanes: { name: string; myPower: number; theirPower: number; winner: PlayerIndex | null }[];
turns: number;
reason: MatchResult['reason'];
diff --git a/tests/ui-play.test.ts b/tests/ui-play.test.ts
index 17b0fee..bb9a90a 100644
--- a/tests/ui-play.test.ts
+++ b/tests/ui-play.test.ts
@@ -1,106 +1,108 @@
-import test from 'node:test';
-import assert from 'node:assert/strict';
-import { DEFAULT_RULESET } from '../shared/game/index.ts';
-import { engine } from '../src/game/adapter.ts';
-import { randomBot } from '../src/game/bots.ts';
-import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts';
-import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx';
-import { parseModeList } from '../src/game/useModes.ts';
-import type { PlayerIndex } from '../src/game/types.ts';
-import type { TestnetBlock } from '../shared/testnet.ts';
-
-function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
-
-/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */
-function playOut(seed: string) {
- let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed);
- const r = rand(seed.length * 7919 + 1);
- for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) {
- for (const p of [0, 1] as PlayerIndex[]) {
- const legal = engine.legal(s, p).filter(a => a.type !== 'concede');
- if (!legal.length) continue;
- s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
- }
- }
- return s;
-}
-
-test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => {
- assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), '');
- assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), '');
- assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/);
-});
-
-test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => {
- const pool = loanerPool();
- const heavy = pool.filter(c => c.cost >= 3).slice(0, 12);
- assert.match(deckWarning(heavy), /cost 2 or less/);
- assert.equal(deckWarning(starterDeck()), '');
-});
-
-test('UI-driven random play always finishes within the turn cap and is deterministic', () => {
- for (let i = 0; i < 40; i++) {
- const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
- assert.ok(engine.isOver(a), `match ${i} finished`);
- const ra = engine.result(a, 0);
- assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
- assert.deepEqual(ra, engine.result(b, 0));
- assert.equal(engine.result(a, 1).winner, ra.winner);
- }
-});
-
-test('my view never shows the opponent’s queued cards', () => {
- // Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand).
- let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0');
- for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++)
- s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`);
- const play = engine.legal(s, 1).find(a => a.type === 'play');
- assert.ok(play, 'some seed gives the opponent a turn-1 play');
- s = engine.apply(s, 1, play!);
- const mine = engine.view(s, 0);
- assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
- assert.equal(mine.oppQueued, 1);
- const theirs = engine.view(s, 1);
- assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
- assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
-});
-
-test('unstage refunds energy, and illegal plays are explained', () => {
- let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy');
- const v = engine.view(s, 0);
- const expensive = v.hand.find(c => c.cost > v.energy);
- if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
- const play = engine.legal(s, 0).find(a => a.type === 'play');
- if (play?.type === 'play') {
- s = engine.apply(s, 0, play);
- assert.ok(engine.view(s, 0).energy < v.energy);
- s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
- assert.equal(engine.view(s, 0).energy, v.energy);
- }
-});
-
-test('an owned NFT maps to a sidegrade card that the engine accepts', () => {
- const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined },
- statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock;
- const card = cardFromBlock(block);
- assert.equal(card.source, 'nft');
- assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped');
- assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]);
- const deck = [card, ...starterDeck().slice(1)];
- assert.equal(deckProblem(deck, DEFAULT_RULESET), '');
-});
-
-test('peer mode lists are parsed defensively', () => {
- const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [
- { mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } },
- { mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } },
- { mode: { name: 'no id' } }, 'junk', null,
- ] }, { self: false, origin: 'http://192.168.1.32:3102' });
- assert.equal(modes.length, 1);
- const [m] = modes;
- assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b');
- assert.equal(m.ruleset.turns, 5);
- assert.ok(m.description.length <= 280);
- assert.equal(m.players, 3);
- assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []);
-});
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { DEFAULT_RULESET } from '../shared/game/index.ts';
+import { engine } from '../src/game/adapter.ts';
+import { randomBot } from '../src/game/bots.ts';
+import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts';
+import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx';
+import { parseModeList } from '../src/game/useModes.ts';
+import type { PlayerIndex } from '../src/game/types.ts';
+import type { TestnetBlock } from '../shared/testnet.ts';
+
+function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
+
+/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */
+function playOut(seed: string) {
+ let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed);
+ const r = rand(seed.length * 7919 + 1);
+ for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) {
+ for (const p of [0, 1] as PlayerIndex[]) {
+ const legal = engine.legal(s, p).filter(a => a.type !== 'concede');
+ if (!legal.length) continue;
+ s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
+ }
+ }
+ return s;
+}
+
+test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => {
+ assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), '');
+ assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), '');
+ assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/);
+});
+
+test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => {
+ const pool = loanerPool();
+ const heavy = pool.filter(c => c.cost >= 3).slice(0, 12);
+ assert.match(deckWarning(heavy), /cost 2 or less/);
+ assert.equal(deckWarning(starterDeck()), '');
+});
+
+test('UI-driven random play always finishes within the turn cap and is deterministic', () => {
+ for (let i = 0; i < 40; i++) {
+ const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
+ assert.ok(engine.isOver(a), `match ${i} finished`);
+ const ra = engine.result(a, 0);
+ assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
+ assert.deepEqual(ra, engine.result(b, 0));
+ const rb = engine.result(a, 1);
+ assert.equal(rb.winner, ra.winner === null ? null : 1 - ra.winner, 'each side sees the other side of the same result');
+ assert.deepEqual(rb.totalPower, [ra.totalPower[1], ra.totalPower[0]]);
+ }
+});
+
+test('my view never shows the opponent’s queued cards', () => {
+ // Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand).
+ let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0');
+ for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++)
+ s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`);
+ const play = engine.legal(s, 1).find(a => a.type === 'play');
+ assert.ok(play, 'some seed gives the opponent a turn-1 play');
+ s = engine.apply(s, 1, play!);
+ const mine = engine.view(s, 0);
+ assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
+ assert.equal(mine.oppQueued, 1);
+ const theirs = engine.view(s, 1);
+ assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
+ assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
+});
+
+test('unstage refunds energy, and illegal plays are explained', () => {
+ let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy');
+ const v = engine.view(s, 0);
+ const expensive = v.hand.find(c => c.cost > v.energy);
+ if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
+ const play = engine.legal(s, 0).find(a => a.type === 'play');
+ if (play?.type === 'play') {
+ s = engine.apply(s, 0, play);
+ assert.ok(engine.view(s, 0).energy < v.energy);
+ s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
+ assert.equal(engine.view(s, 0).energy, v.energy);
+ }
+});
+
+test('an owned NFT maps to a sidegrade card that the engine accepts', () => {
+ const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined },
+ statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock;
+ const card = cardFromBlock(block);
+ assert.equal(card.source, 'nft');
+ assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped');
+ assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]);
+ const deck = [card, ...starterDeck().slice(1)];
+ assert.equal(deckProblem(deck, DEFAULT_RULESET), '');
+});
+
+test('peer mode lists are parsed defensively', () => {
+ const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [
+ { mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } },
+ { mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } },
+ { mode: { name: 'no id' } }, 'junk', null,
+ ] }, { self: false, origin: 'http://192.168.1.32:3102' });
+ assert.equal(modes.length, 1);
+ const [m] = modes;
+ assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b');
+ assert.equal(m.ruleset.turns, 5);
+ assert.ok(m.description.length <= 280);
+ assert.equal(m.players, 3);
+ assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []);
+});
--
2.54.0
From c4636530ef78a709ea04748f3e390015f5bddc14 Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:55:58 -0500
Subject: [PATCH 12/14] Play: bots see only viewFor output (MatchView.engine =
{ view, seat })
Per night-lead's rule on #5 the adapter no longer exposes MatchState to
bots; a test checks no RNG state, seed or deck order leaks.
Co-Authored-By: Claude Opus 5.5
---
src/game/OnlinePlay.tsx | 2 +-
src/game/adapter.ts | 3 +-
src/game/types.ts | 6 +-
tests/ui-play.test.ts | 225 +++++++++++++++++++++-------------------
4 files changed, 123 insertions(+), 113 deletions(-)
diff --git a/src/game/OnlinePlay.tsx b/src/game/OnlinePlay.tsx
index ae8f527..1db4caa 100644
--- a/src/game/OnlinePlay.tsx
+++ b/src/game/OnlinePlay.tsx
@@ -98,7 +98,7 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
const phase = status?.phase;
// ----- match -----
if ((phase === 'playing' || phase === 'finished') && status?.state) {
- const view = viewFromPlayerView(status.state);
+ const view = { ...viewFromPlayerView(status.state), engine: { view: status.state, seat: seat.seat } };
const legal = uiActions(status.legalActions ?? []);
const opp = status.players.find((_, i) => i !== seat.seat)?.name ?? 'Opponent';
const act = (a: UIAction) => {
diff --git a/src/game/adapter.ts b/src/game/adapter.ts
index 5aaa7fc..7da75f2 100644
--- a/src/game/adapter.ts
+++ b/src/game/adapter.ts
@@ -68,7 +68,8 @@ export const engine = {
for (const l of state.lanes) for (const side of l.cards) for (const c of side) titles.set(c.card.cardId, c.card.title);
const log = state.log.filter(e => e.t !== 'draw')
.map(e => logLine(e, me, id => titles.get(id) ?? 'a card')).filter((x): x is string => !!x).slice(-30);
- return { ...viewFromPlayerView(viewFor(state, me), { log, capacity: i => laneCapacity(state, i) }), engine: { state, seat: me } };
+ const pv = viewFor(state, me);
+ return { ...viewFromPlayerView(pv, { log, capacity: i => laneCapacity(state, i) }), engine: { view: pv, seat: me } };
},
isOver: (s: MatchState) => isOver(s),
result(state: MatchState, me: PlayerId): ResultView {
diff --git a/src/game/types.ts b/src/game/types.ts
index 69612ce..0eb1122 100644
--- a/src/game/types.ts
+++ b/src/game/types.ts
@@ -1,6 +1,6 @@
// UI-side view models for the Play section. Screens consume only these; adapter.ts maps the
// shared/game engine (docs/game/ENGINE_API.md) onto them.
-import type { Action, GameCard, MatchResult, MatchState, PlayerId, Ruleset, Stat } from '../../shared/game/index.ts';
+import type { Action, GameCard, MatchResult, PlayerId, PlayerView, Ruleset, Stat } from '../../shared/game/index.ts';
export type PlayerIndex = PlayerId;
export type { Stat };
@@ -56,8 +56,8 @@ export type MatchView = {
log: string[]; // newest last, this seat's events only
waitingForOpponent: boolean;
over: boolean;
- /** For bots that reuse shared/bots (ui-b): the full state and this seat. Never render it. */
- engine?: { state: MatchState; seat: PlayerId };
+ /** For engine-level bots (ui-b): this seat's hidden-information view only (night-lead: never the full MatchState). */
+ engine?: { view: PlayerView; seat: PlayerId };
};
export type UIAction = (
diff --git a/tests/ui-play.test.ts b/tests/ui-play.test.ts
index bb9a90a..f2ce68d 100644
--- a/tests/ui-play.test.ts
+++ b/tests/ui-play.test.ts
@@ -1,108 +1,117 @@
-import test from 'node:test';
-import assert from 'node:assert/strict';
-import { DEFAULT_RULESET } from '../shared/game/index.ts';
-import { engine } from '../src/game/adapter.ts';
-import { randomBot } from '../src/game/bots.ts';
-import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts';
-import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx';
-import { parseModeList } from '../src/game/useModes.ts';
-import type { PlayerIndex } from '../src/game/types.ts';
-import type { TestnetBlock } from '../shared/testnet.ts';
-
-function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
-
-/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */
-function playOut(seed: string) {
- let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed);
- const r = rand(seed.length * 7919 + 1);
- for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) {
- for (const p of [0, 1] as PlayerIndex[]) {
- const legal = engine.legal(s, p).filter(a => a.type !== 'concede');
- if (!legal.length) continue;
- s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
- }
- }
- return s;
-}
-
-test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => {
- assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), '');
- assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), '');
- assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/);
-});
-
-test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => {
- const pool = loanerPool();
- const heavy = pool.filter(c => c.cost >= 3).slice(0, 12);
- assert.match(deckWarning(heavy), /cost 2 or less/);
- assert.equal(deckWarning(starterDeck()), '');
-});
-
-test('UI-driven random play always finishes within the turn cap and is deterministic', () => {
- for (let i = 0; i < 40; i++) {
- const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
- assert.ok(engine.isOver(a), `match ${i} finished`);
- const ra = engine.result(a, 0);
- assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
- assert.deepEqual(ra, engine.result(b, 0));
- const rb = engine.result(a, 1);
- assert.equal(rb.winner, ra.winner === null ? null : 1 - ra.winner, 'each side sees the other side of the same result');
- assert.deepEqual(rb.totalPower, [ra.totalPower[1], ra.totalPower[0]]);
- }
-});
-
-test('my view never shows the opponent’s queued cards', () => {
- // Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand).
- let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0');
- for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++)
- s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`);
- const play = engine.legal(s, 1).find(a => a.type === 'play');
- assert.ok(play, 'some seed gives the opponent a turn-1 play');
- s = engine.apply(s, 1, play!);
- const mine = engine.view(s, 0);
- assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
- assert.equal(mine.oppQueued, 1);
- const theirs = engine.view(s, 1);
- assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
- assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
-});
-
-test('unstage refunds energy, and illegal plays are explained', () => {
- let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy');
- const v = engine.view(s, 0);
- const expensive = v.hand.find(c => c.cost > v.energy);
- if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
- const play = engine.legal(s, 0).find(a => a.type === 'play');
- if (play?.type === 'play') {
- s = engine.apply(s, 0, play);
- assert.ok(engine.view(s, 0).energy < v.energy);
- s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
- assert.equal(engine.view(s, 0).energy, v.energy);
- }
-});
-
-test('an owned NFT maps to a sidegrade card that the engine accepts', () => {
- const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined },
- statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock;
- const card = cardFromBlock(block);
- assert.equal(card.source, 'nft');
- assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped');
- assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]);
- const deck = [card, ...starterDeck().slice(1)];
- assert.equal(deckProblem(deck, DEFAULT_RULESET), '');
-});
-
-test('peer mode lists are parsed defensively', () => {
- const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [
- { mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } },
- { mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } },
- { mode: { name: 'no id' } }, 'junk', null,
- ] }, { self: false, origin: 'http://192.168.1.32:3102' });
- assert.equal(modes.length, 1);
- const [m] = modes;
- assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b');
- assert.equal(m.ruleset.turns, 5);
- assert.ok(m.description.length <= 280);
- assert.equal(m.players, 3);
- assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []);
-});
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { DEFAULT_RULESET } from '../shared/game/index.ts';
+import { engine } from '../src/game/adapter.ts';
+import { randomBot } from '../src/game/bots.ts';
+import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts';
+import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx';
+import { parseModeList } from '../src/game/useModes.ts';
+import type { PlayerIndex } from '../src/game/types.ts';
+import type { TestnetBlock } from '../shared/testnet.ts';
+
+function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
+
+/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */
+function playOut(seed: string) {
+ let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed);
+ const r = rand(seed.length * 7919 + 1);
+ for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) {
+ for (const p of [0, 1] as PlayerIndex[]) {
+ const legal = engine.legal(s, p).filter(a => a.type !== 'concede');
+ if (!legal.length) continue;
+ s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
+ }
+ }
+ return s;
+}
+
+test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => {
+ assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), '');
+ assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), '');
+ assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/);
+});
+
+test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => {
+ const pool = loanerPool();
+ const heavy = pool.filter(c => c.cost >= 3).slice(0, 12);
+ assert.match(deckWarning(heavy), /cost 2 or less/);
+ assert.equal(deckWarning(starterDeck()), '');
+});
+
+test('UI-driven random play always finishes within the turn cap and is deterministic', () => {
+ for (let i = 0; i < 40; i++) {
+ const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
+ assert.ok(engine.isOver(a), `match ${i} finished`);
+ const ra = engine.result(a, 0);
+ assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
+ assert.deepEqual(ra, engine.result(b, 0));
+ const rb = engine.result(a, 1);
+ assert.equal(rb.winner, ra.winner === null ? null : 1 - ra.winner, 'each side sees the other side of the same result');
+ assert.deepEqual(rb.totalPower, [ra.totalPower[1], ra.totalPower[0]]);
+ }
+});
+
+test('my view never shows the opponent’s queued cards', () => {
+ // Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand).
+ let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0');
+ for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++)
+ s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`);
+ const play = engine.legal(s, 1).find(a => a.type === 'play');
+ assert.ok(play, 'some seed gives the opponent a turn-1 play');
+ s = engine.apply(s, 1, play!);
+ const mine = engine.view(s, 0);
+ assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
+ assert.equal(mine.oppQueued, 1);
+ const theirs = engine.view(s, 1);
+ assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
+ assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
+});
+
+test('unstage refunds energy, and illegal plays are explained', () => {
+ let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy');
+ const v = engine.view(s, 0);
+ const expensive = v.hand.find(c => c.cost > v.energy);
+ if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
+ const play = engine.legal(s, 0).find(a => a.type === 'play');
+ if (play?.type === 'play') {
+ s = engine.apply(s, 0, play);
+ assert.ok(engine.view(s, 0).energy < v.energy);
+ s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
+ assert.equal(engine.view(s, 0).energy, v.energy);
+ }
+});
+
+test('an owned NFT maps to a sidegrade card that the engine accepts', () => {
+ const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined },
+ statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock;
+ const card = cardFromBlock(block);
+ assert.equal(card.source, 'nft');
+ assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped');
+ assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]);
+ const deck = [card, ...starterDeck().slice(1)];
+ assert.equal(deckProblem(deck, DEFAULT_RULESET), '');
+});
+
+test('peer mode lists are parsed defensively', () => {
+ const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [
+ { mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } },
+ { mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } },
+ { mode: { name: 'no id' } }, 'junk', null,
+ ] }, { self: false, origin: 'http://192.168.1.32:3102' });
+ assert.equal(modes.length, 1);
+ const [m] = modes;
+ assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b');
+ assert.equal(m.ruleset.turns, 5);
+ assert.ok(m.description.length <= 280);
+ assert.equal(m.players, 3);
+ assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []);
+});
+
+test('bots get only the hidden-information view, never the full match state', () => {
+ const s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('v')], 'view-only');
+ const v = engine.view(s, 1);
+ assert.ok(v.engine?.view);
+ const json = JSON.stringify(v);
+ assert.ok(!json.includes('"rng"') && !json.includes('"seed"'), 'no RNG state or seed');
+ assert.ok(!('deck' in (v.engine!.view as object)), 'no deck order');
+});
--
2.54.0
From a3c280b922fca472420f8edbcd3a65684e7bdaea Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 23:59:15 -0500
Subject: [PATCH 13/14] Play: review follow-ups (night-review, council-critic)
Lane plate shows Opp total on top and You below with the Portal rule and
tie-break reason; results use the engine's lane leaders (on-topic tie);
opponent fizzles never name a card in hand; guest names no longer use
secret characters; pick one of the four starter decks in the lobby;
'+N saved' energy in the turn banner; keyword words fit; hand fade hint;
phones hide node chrome on the Play route and keep the Play button clear
of the floating account button.
Co-Authored-By: Claude Opus 5.5
---
src/game/MatchBoard.tsx | 13 ++++++++-----
src/game/OnlinePlay.tsx | 2 +-
src/game/PlaySection.tsx | 17 ++++++++++++-----
src/game/Results.tsx | 2 +-
src/game/adapter.ts | 13 ++++++++-----
src/game/online.ts | 14 +++++++++++++-
src/game/play.css | 13 ++++++++++++-
src/game/types.ts | 1 +
8 files changed, 56 insertions(+), 19 deletions(-)
diff --git a/src/game/MatchBoard.tsx b/src/game/MatchBoard.tsx
index 4ca0085..9493300 100644
--- a/src/game/MatchBoard.tsx
+++ b/src/game/MatchBoard.tsx
@@ -29,11 +29,12 @@ export function MatchBoard({ title, opponent, view, legal, onAct, problem, error
useEffect(() => {
if (view.turn !== lastTurn.current && !view.over) {
lastTurn.current = view.turn;
- setBanner(view.turn === view.maxTurns ? `Final turn · ${view.maxEnergy} energy` : `Turn ${view.turn} · ${view.maxEnergy} energy`);
+ const saved = view.saved ? ` (+${view.saved} saved)` : '';
+ setBanner(view.turn === view.maxTurns ? `Final turn · ${view.maxEnergy} energy${saved}` : `Turn ${view.turn} · ${view.maxEnergy} energy${saved}`);
const t = setTimeout(() => setBanner(''), 1400);
return () => clearTimeout(t);
}
- }, [view.turn, view.over, view.maxTurns, view.maxEnergy]);
+ }, [view.turn, view.over, view.maxTurns, view.maxEnergy, view.saved]);
const act = onAct;
const canPlay = (cardId: string, lane: number) => legal.some(a => a.type === 'play' && a.cardId === cardId && a.lane === lane);
@@ -66,9 +67,11 @@ export function MatchBoard({ title, opponent, view, legal, onAct, problem, error
tapLane(lane)}
aria-label={target ? `Play ${sel!.title} to ${lane.name}${onTopic ? `, on-topic +${topicBonus}` : ''}` : `${lane.name} Topic (${STAT_LABEL[lane.stat]}): you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? lane.portalNote ?? ''}`}>
- {lane.theirPower}
- {lane.name} {!lane.revealed && ? }
- {lane.myPower}
+ Opp {lane.theirPower}
+ {lane.name} {!lane.revealed && ? }
+ {lane.modifier && {lane.modifier.text} }
+ {lane.myPower === lane.theirPower && lane.leader && Tie: {lane.leader === 'you' ? 'you lead' : 'they lead'} on-topic }
+ You {lane.myPower}
{lane.mine.map(c =>
setSheet({ kind: 'card', card: c, side: 'mine' })} />)}
diff --git a/src/game/OnlinePlay.tsx b/src/game/OnlinePlay.tsx
index 1db4caa..4e5d3a7 100644
--- a/src/game/OnlinePlay.tsx
+++ b/src/game/OnlinePlay.tsx
@@ -58,7 +58,7 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
finished.current = true;
const names = st.lanes.map(l => l.topic.name);
- finishTimer.current = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names)), 900);
+ finishTimer.current = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names, st.lanes.map(l => l.leader))), 900);
}, [status, seat, onFinish]);
useEffect(() => () => clearTimeout(finishTimer.current), []);
diff --git a/src/game/PlaySection.tsx b/src/game/PlaySection.tsx
index 6635139..b249bf0 100644
--- a/src/game/PlaySection.tsx
+++ b/src/game/PlaySection.tsx
@@ -3,7 +3,7 @@ import { CircleHelp, ExternalLink, Globe2, Layers3, Play, Server, Swords, UserRo
import type { TestnetBlock } from '../../shared/testnet.ts';
import { Avatar } from '../auth/LoginButton.tsx';
import { BOTS, type Bot } from './bots.ts';
-import { cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from './cards.ts';
+import { DEFAULT_STARTER, STARTERS, cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from './cards.ts';
import { DeckBuilder, deckProblem, deckWarning } from './DeckBuilder.tsx';
import { CategoryIcon } from './GameCard.tsx';
import { MatchScreen } from './MatchScreen.tsx';
@@ -19,6 +19,7 @@ import './play.css';
type Screen = 'lobby' | 'deck' | 'match' | 'online' | 'results' | 'tutorial';
const DECK_KEY = 'wikideck-play-deck-v1';
const TUTORIAL_KEY = 'wikideck-play-tutorial-v1';
+const STARTER_KEY = 'wikideck-play-starter-v1';
const store = {
get: (k: string) => { try { return localStorage.getItem(k); } catch { return null; } },
set: (k: string, v: string) => { try { localStorage.setItem(k, v); } catch { /* storage unavailable */ } },
@@ -33,6 +34,7 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
const [bot, setBot] = useState(BOTS[0]);
const [savedIds, setSavedIds] = useState(() => { try { return JSON.parse(store.get(DECK_KEY) ?? 'null'); } catch { return null; } });
const [seed, setSeed] = useState('');
+ const [starterId, setStarterId] = useState(() => { const s = store.get(STARTER_KEY); return STARTERS.some(d => d.id === s) ? s! : DEFAULT_STARTER; });
const [result, setResult] = useState();
const mode = modes.find(m => m.id === modeId) ?? modes[0];
const rules = mode.ruleset;
@@ -40,10 +42,10 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
// Rebuild the saved deck from current cards; NFTs you no longer own simply drop out.
const deck = useMemo(() => {
- if (!savedIds) return starterDeck(rules);
+ if (!savedIds) return starterDeck(rules, starterId);
const byId = new Map(pool.map(c => [c.id, c]));
return savedIds.flatMap(id => byId.get(id) ?? []);
- }, [savedIds, pool, rules]);
+ }, [savedIds, pool, rules, starterId]);
const problem = deckProblem(deck, rules);
const warning = deckWarning(deck);
const opponent = useMemo(() => botDeck(seed, rules), [seed, rules]);
@@ -55,7 +57,8 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
// While a match is on screen, hide the floating eom.dev account button (it sits over the dock on phones).
useEffect(() => {
document.documentElement.classList.toggle('wd-in-match', screen === 'match' || screen === 'online');
- return () => document.documentElement.classList.remove('wd-in-match');
+ document.documentElement.classList.add('wd-play');
+ return () => document.documentElement.classList.remove('wd-in-match', 'wd-play');
}, [screen]);
if (screen === 'tutorial') return { store.set(TUTORIAL_KEY, '1'); setScreen('lobby'); }} />;
@@ -103,9 +106,13 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
Deck {deck.length}
setScreen('deck')} aria-label="Edit deck">
{deck.slice(0, 4).map(c => )}
- {savedIds ? 'Your deck' : 'Starter deck'} {deck.filter(c => c.source === 'nft').length} NFTs · {deck.filter(c => c.source === 'starter').length} loaners
+ {savedIds ? 'Your deck' : `Starter: ${STARTERS.find(d => d.id === starterId)?.name}`} {deck.filter(c => c.source === 'nft').length} NFTs · {deck.filter(c => c.source === 'starter').length} loaners
+ {!savedIds && {STARTERS.map(d =>
+ { setStarterId(d.id); store.set(STARTER_KEY, d.id); }}>{d.name} )}
}
+ {savedIds && { setSavedIds(null); try { localStorage.removeItem(DECK_KEY); } catch { /* ignore */ } }}>Use a starter deck instead }
{problem ? {problem} Edit your deck to play {mode.name}.
: warning && {warning}
}
diff --git a/src/game/Results.tsx b/src/game/Results.tsx
index a31d4a3..43dd221 100644
--- a/src/game/Results.tsx
+++ b/src/game/Results.tsx
@@ -11,7 +11,7 @@ export function Results({ result, modeName, onRematch, onLobby }: { result: Resu
{modeName.toUpperCase()} · {result.turns} TURNS
{outcome === 'win' ? 'Victory!' : outcome === 'loss' ? 'Defeat' : 'Draw'}
{result.reason === 'concede' ? (outcome === 'win' ? 'Your opponent conceded.' : 'You conceded.')
- : `You won ${won} of ${result.lanes.length} lanes${tiebreak ? ', so total power decided it' : ''}.`}
+ : `You won ${won} of ${result.lanes.length} Topics${tiebreak ? ', so total power decided it' : ''}.`}
{result.lanes.map(l =>
{l.name} {l.myPower} – {l.theirPower} {l.winner === 0 ? 'Won' : l.winner === 1 ? 'Lost' : 'Tied'}
diff --git a/src/game/adapter.ts b/src/game/adapter.ts
index 7da75f2..7b3ea6f 100644
--- a/src/game/adapter.ts
+++ b/src/game/adapter.ts
@@ -38,7 +38,7 @@ function logLine(e: LogEvent, me: PlayerId, title: (id: string) => string): stri
case 'portalRevealed': return `Portal revealed: ${e.topic.name}.`;
case 'underdog': return `${who(e.player)} got the underdog bonus.`;
case 'reveal': return `${who(e.player)} played ${title(e.cardId)}.`;
- case 'fizzle': return `${who(e.player)}: ${title(e.cardId)} fizzled (no room) and went back to hand.`;
+ case 'fizzle': return e.player === me ? `Your ${title(e.cardId)} fizzled (no room) and went back to hand.` : 'An opponent play fizzled.'; // never name a card in their hand
case 'effect': return `${e.source}: ${e.text}`;
case 'concede': return `${who(e.player)} ${e.afk ? 'timed out' : 'conceded'}.`;
case 'matchOver': return 'Match over.';
@@ -73,7 +73,7 @@ export const engine = {
},
isOver: (s: MatchState) => isOver(s),
result(state: MatchState, me: PlayerId): ResultView {
- return resultView(result(state)!, me, state.lanes.map(l => l.topic.name));
+ return resultView(result(state)!, me, state.lanes.map(l => l.topic.name), viewFor(state, me).lanes.map(l => l.leader));
},
};
@@ -96,7 +96,7 @@ export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capaci
return {
index: i, stat: lane.topic.stat, revealed: lane.portalRevealed,
name: lane.portalRevealed ? lane.topic.name : STAT_LABEL[lane.topic.stat],
- modifier: portal, portalNote: lane.portalRevealed ? undefined : `Topic and Portal reveal on turn ${rules.portalReveal[i]}`,
+ modifier: portal, portalNote: lane.portalRevealed ? undefined : `Portal reveals on turn ${rules.portalReveal[i]}`,
mine: lane.cards[0].map((c, k) => onBoard(c, lane.cardPower[0][k], lane.topic.stat, allOn)),
theirs: lane.cards[1].map((c, k) => onBoard(c, lane.cardPower[1][k], lane.topic.stat, allOn)),
staged: v.queue.filter(q => q.lane === i).flatMap(q => {
@@ -110,6 +110,7 @@ export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capaci
const queued = new Set(v.queue.map(q => q.cardId));
return {
me, turn: v.turn, maxTurns: rules.turns, energy: v.energyLeft, maxEnergy: v.energy,
+ saved: Math.max(0, v.energy - (rules.energyByTurn[v.turn - 1] ?? 0) - rules.bonusEnergy),
hand: v.hand.filter(c => !queued.has(c.cardId)).map(c => toUICard(c, rules)), deckCount: v.deckCount,
oppHandCount: v.opponent.handCount, oppDeckCount: v.opponent.deckCount, oppQueued: v.opponent.queuedCount,
lanes, log: opts.log ?? [], waitingForOpponent: v.committed && v.phase !== 'over', over: v.phase === 'over',
@@ -117,14 +118,16 @@ export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capaci
}
/** Results from `me`'s point of view: in a ResultView, 0 always means "you" and 1 "your opponent". */
-export function resultView(r: MatchResult, me: PlayerId, laneNames: string[]): ResultView {
+export function resultView(r: MatchResult, me: PlayerId, laneNames: string[], leaders?: ('you' | 'opponent' | null)[]): ResultView {
const opp: PlayerId = me === 0 ? 1 : 0;
return {
winner: r.winner === null ? null : r.winner === me ? 0 : 1, turns: r.turns, reason: r.reason,
totalPower: [r.totalPower[me], r.totalPower[opp]],
lanes: r.lanePower.map((pw, i) => {
const a = pw[me], b = pw[opp];
- return { name: laneNames[i] ?? `Topic ${i + 1}`, myPower: a, theirPower: b, winner: a === b ? null : a > b ? 0 : 1 };
+ const lead = leaders?.[i]; // the consensus tie-break (on-topic count) can decide an equal lane
+ const winner = lead !== undefined ? (lead === 'you' ? 0 : lead === 'opponent' ? 1 : null) : a === b ? null : a > b ? 0 : 1;
+ return { name: laneNames[i] ?? `Topic ${i + 1}`, myPower: a, theirPower: b, winner };
}),
};
}
diff --git a/src/game/online.ts b/src/game/online.ts
index 52d8e86..b50e946 100644
--- a/src/game/online.ts
+++ b/src/game/online.ts
@@ -35,10 +35,22 @@ export async function playerSecret(hostOrigin: string): Promise {
return b64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(hostOrigin))));
}
+/** A random 4-character tag for guest names, separate from the secret. */
+function guestTag(): string {
+ const KEY = 'wikideck-guest-tag';
+ try {
+ const t = localStorage.getItem(KEY);
+ if (t && /^[A-Za-z0-9]{4}$/.test(t)) return t;
+ const fresh = b64url(crypto.getRandomValues(new Uint8Array(6))).replace(/[^A-Za-z0-9]/g, '').slice(0, 4).padEnd(4, 'x');
+ localStorage.setItem(KEY, fresh);
+ return fresh;
+ } catch { return 'anon'; }
+}
+
/** Host display names allow 1–24 letters, digits, spaces and _ . - */
export function lobbyName(name: string | undefined): string {
const clean = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} _.-]/gu, '').trim().slice(0, 24);
- return clean || `Guest ${masterSecret().slice(0, 4)}`;
+ return clean || `Guest ${guestTag()}`;
}
async function call(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise {
diff --git a/src/game/play.css b/src/game/play.css
index ab17635..754fefb 100644
--- a/src/game/play.css
+++ b/src/game/play.css
@@ -181,4 +181,15 @@ html.wd-in-match .auth-wrap,body:has(.match) .auth-wrap{display:none}
.lane-drop.on-topic{border-color:var(--ctp-green);color:var(--ctp-green);background:color-mix(in srgb,var(--ctp-green) 10%,transparent)}
.sheet h3{display:flex;align-items:center;gap:8px}
@media(max-width:400px){.gcard-board .gcard-home{display:none}.gcard-board.is-on-topic{box-shadow:inset 3px 0 0 var(--ctp-green)}}
-.starter-picks{margin-bottom:14px}
+.starter-picks{margin:8px 0 14px}
+/* Review follow-ups: vertical lane plate (opponent total on top, yours below), rule line, tie reason */
+.lane-plate{grid-template-columns:1fr;grid-template-rows:auto auto auto;justify-items:center;gap:2px;padding:4px 3px}
+.lane-score{display:flex;align-items:baseline;gap:3px;line-height:1.1}
+.lane-score small{font-size:8px;font-weight:600;color:var(--ctp-overlay1);text-transform:uppercase}
+.lane-rule{font-size:9px!important;line-height:1.25;color:var(--ctp-subtext0)!important;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
+.lane-tie{font-size:9px!important;color:var(--ctp-yellow)!important}
+.gcard-keyword{text-transform:none;letter-spacing:0;font-size:10px;white-space:nowrap}
+@media(max-width:480px){.hand{-webkit-mask-image:linear-gradient(to right,#000 82%,transparent);mask-image:linear-gradient(to right,#000 82%,transparent);padding-right:24px}}
+/* Phones: on the Play route, hide the node/RPC chrome above the game so Play starts above the fold. */
+@media(max-width:760px){html.wd-play .testnet-status,html.wd-play .error-banner,html.wd-play main>footer{display:none}}
+@media(max-width:480px){html.wd-play:not(.wd-in-match) .play-dock{padding-right:62px}}
diff --git a/src/game/types.ts b/src/game/types.ts
index 0eb1122..1b45ad2 100644
--- a/src/game/types.ts
+++ b/src/game/types.ts
@@ -47,6 +47,7 @@ export type MatchView = {
maxTurns: number;
energy: number; // left this turn
maxEnergy: number;
+ saved: number; // energy carried over from last turn (included in maxEnergy)
hand: UICard[];
deckCount: number;
oppHandCount: number;
--
2.54.0
From b5fa6d3609f2da71181fb3d83ac3e063d1411264 Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 17 Nov 2026 00:06:00 -0500
Subject: [PATCH 14/14] Play: lobby leaderboards (mode players, network hosts);
compact phone dock
Host credit per #6: hosted modes show their top players and the network's
host leaderboard (matches hosted). Same-origin GETs, strings capped and
rendered as text. On phones the lobby actions fit one row.
Co-Authored-By: Claude Opus 5.5
---
src/game/Leaderboards.tsx | 49 +++++++++++++++++++++++++++++++++++++++
src/game/PlaySection.tsx | 10 ++++----
src/game/play.css | 12 ++++++++++
tests/ui-play.test.ts | 11 +++++++++
4 files changed, 78 insertions(+), 4 deletions(-)
create mode 100644 src/game/Leaderboards.tsx
diff --git a/src/game/Leaderboards.tsx b/src/game/Leaderboards.tsx
new file mode 100644
index 0000000..9cb8939
--- /dev/null
+++ b/src/game/Leaderboards.tsx
@@ -0,0 +1,49 @@
+import { useEffect, useState } from 'react';
+import { Server, Trophy } from 'lucide-react';
+import type { GameMode } from './types.ts';
+
+// Host credit (modes, #6): per-mode player leaderboard and the network's host leaderboard.
+// Same-origin GETs only; every string is untrusted and rendered as text.
+type Entry = { name: string; wins: number; losses: number; draws: number; played: number };
+type Host = { operator: string; matchesHosted: number; playersOnline: number; self: boolean; reachable: boolean };
+const str = (v: unknown, max = 40) => (typeof v === 'string' ? v.slice(0, max) : '');
+const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0);
+const rows = (v: unknown, key: string): Record[] => {
+ const list = v && typeof v === 'object' ? (v as Record)[key] : undefined;
+ return Array.isArray(list) ? list.filter((x): x is Record => !!x && typeof x === 'object').slice(0, 10) : [];
+};
+const get = (path: string) => fetch(path, { cache: 'no-store', signal: AbortSignal.timeout(8000) })
+ .then(r => (r.ok && r.headers.get('content-type')?.includes('json') ? r.json() : Promise.reject(new Error('unavailable'))));
+
+export function parseLeaderboard(v: unknown): Entry[] {
+ return rows(v, 'entries').map(e => ({ name: str(e.name, 24) || 'Anonymous', wins: num(e.wins), losses: num(e.losses), draws: num(e.draws), played: num(e.played) }));
+}
+export function parseHosts(v: unknown): Host[] {
+ return rows(v, 'hosts').map(h => ({ operator: str(h.operator, 60) || str(h.origin, 60) || 'unknown host', matchesHosted: num(h.matchesHosted),
+ playersOnline: num(h.playersOnline), self: h.self === true, reachable: h.reachable !== false }));
+}
+
+export function Leaderboards({ mode }: { mode: GameMode }) {
+ const [players, setPlayers] = useState();
+ const [hosts, setHosts] = useState();
+ const hosted = mode.host.kind === 'peer' && mode.host.self;
+ const remoteId = mode.remoteId;
+ useEffect(() => {
+ let active = true;
+ get('/api/game/hosts/leaderboard').then(d => { if (active) setHosts(parseHosts(d)); }, () => { if (active) setHosts([]); });
+ if (hosted && remoteId) get(`/api/game/modes/${encodeURIComponent(remoteId)}/leaderboard`)
+ .then(d => { if (active) setPlayers(parseLeaderboard(d)); }, () => { if (active) setPlayers([]); });
+ else setPlayers(undefined);
+ return () => { active = false; };
+ }, [hosted, remoteId]);
+ if (!hosts?.length && !players?.length) return null;
+ return
+ Leaderboards
+ {players && <>{mode.name}: top players {players.length
+ ? {players.map((p, i) => {p.name} {p.wins}W {p.losses}L · {p.draws}D )}
+ : No finished matches yet. Be the first.
}>}
+ {!!hosts?.length && <> Top hosts · matches hosted
+ {hosts.map((h, i) => {h.operator}{h.self ? ' (this node)' : ''}{h.reachable ? '' : ' · offline'} {h.matchesHosted} {h.playersOnline} online )}
+ Run a WikiDeck node and host your own modes to appear here.
>}
+ ;
+}
diff --git a/src/game/PlaySection.tsx b/src/game/PlaySection.tsx
index b249bf0..1edefc0 100644
--- a/src/game/PlaySection.tsx
+++ b/src/game/PlaySection.tsx
@@ -6,6 +6,7 @@ import { BOTS, type Bot } from './bots.ts';
import { DEFAULT_STARTER, STARTERS, cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from './cards.ts';
import { DeckBuilder, deckProblem, deckWarning } from './DeckBuilder.tsx';
import { CategoryIcon } from './GameCard.tsx';
+import { Leaderboards } from './Leaderboards.tsx';
import { MatchScreen } from './MatchScreen.tsx';
import { lobbyName } from './online.ts';
import { OnlinePlay } from './OnlinePlay.tsx';
@@ -91,11 +92,12 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
{status === 'loading' && Looking for peer-hosted modes…
}
{status === 'unavailable' && No peer-hosted modes reachable from this node.
}
+ {status === 'ok' && }
{remote ? <>
This mode runs on {remote.name}’s node. Open it there to play; your eom.dev account works on every node.
-
setScreen('tutorial')}> How to play
+
setScreen('tutorial')}>How to play
{remote.url ?
Play on {remote.name}
:
Host address unavailable }
@@ -117,9 +119,9 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
: warning && {warning}
}
-
setScreen('tutorial')}> How to play
- {hosted &&
{ setLastOnline(true); setScreen('online'); }}> Play a person }
-
Play vs {bot.name}
+
setScreen('tutorial')}>How to play
+ {hosted &&
{ setLastOnline(true); setScreen('online'); }}>Play a person Online }
+
Play vs {bot.name} Play
>}
;
diff --git a/src/game/play.css b/src/game/play.css
index 754fefb..550e311 100644
--- a/src/game/play.css
+++ b/src/game/play.css
@@ -193,3 +193,15 @@ html.wd-in-match .auth-wrap,body:has(.match) .auth-wrap{display:none}
/* Phones: on the Play route, hide the node/RPC chrome above the game so Play starts above the fold. */
@media(max-width:760px){html.wd-play .testnet-status,html.wd-play .error-banner,html.wd-play main>footer{display:none}}
@media(max-width:480px){html.wd-play:not(.wd-in-match) .play-dock{padding-right:62px}}
+.leaderboards{margin:12px 0 0;padding:10px 12px;border:1px solid var(--theme-border);border-radius:10px;background:var(--ctp-base)}
+.leaderboards summary{cursor:pointer;display:flex;align-items:center;gap:6px;font-weight:700;font-size:13px;min-height:32px}
+.leaderboards h4{font-size:12px;margin:10px 0 6px;display:flex;align-items:center;gap:5px;color:var(--ctp-subtext1)}
+.board-list{list-style:none;padding:0;margin:0;display:grid;gap:4px;counter-reset:rank}
+.board-list li{display:grid;grid-template-columns:22px 1fr auto auto;gap:8px;align-items:baseline;font-size:13px;counter-increment:rank}
+.board-list li::before{content:counter(rank);color:var(--ctp-overlay1);font-size:11px}
+.board-list li span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.board-list li small{color:var(--ctp-subtext0);font-size:11px}
+.board-list li.self span{color:var(--theme-accent)}
+@media(max-width:480px){.hide-narrow{display:none}.play-actions{flex-wrap:nowrap}.play-actions .button{padding-inline:12px}}
+.show-narrow{display:none}
+@media(max-width:480px){.show-narrow{display:inline}.play-actions .button{min-width:0}}
diff --git a/tests/ui-play.test.ts b/tests/ui-play.test.ts
index f2ce68d..1519fbf 100644
--- a/tests/ui-play.test.ts
+++ b/tests/ui-play.test.ts
@@ -115,3 +115,14 @@ test('bots get only the hidden-information view, never the full match state', ()
assert.ok(!json.includes('"rng"') && !json.includes('"seed"'), 'no RNG state or seed');
assert.ok(!('deck' in (v.engine!.view as object)), 'no deck order');
});
+
+test('leaderboard parsers cap and sanitise host data', async () => {
+ const { parseHosts, parseLeaderboard } = await import('../src/game/Leaderboards.tsx');
+ const hosts = parseHosts({ hosts: [{ operator: 'x'.repeat(200), matchesHosted: 5, playersOnline: -3, self: true }, null, 'junk', ...Array(20).fill({ origin: 'http://n' })] });
+ assert.equal(hosts.length, 10);
+ assert.equal(hosts[0].operator.length, 60);
+ assert.equal(hosts[0].playersOnline, 0);
+ assert.equal(hosts[1].operator, 'http://n');
+ assert.deepEqual(parseLeaderboard({ entries: [{ name: '', wins: 2 }] }), [{ name: 'Anonymous', wins: 2, losses: 0, draws: 0, played: 0 }]);
+ assert.deepEqual(parseLeaderboard(42), []);
+});
--
2.54.0