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 <noreply@anthropic.com>
14 KiB
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(), noMath.random(). - It imports nothing from
server/orsrc/. - 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.
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
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
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
playreserves 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 underlaneCapacity(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).
undoand new plays are allowed until the seat sendscommit.
Resolving a turn
- When both seats have committed,
applyActionresolves the turn (DESIGN §5.4–5.5):- Carry is set: min(
energyCarryMax, energy not reserved by queued plays). Energy spent on a play that later fizzles is still spent. - 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
seqnumber, and its on-reveal effects (keyword, then Portal) run at once. - End-of-turn effects run: the initiative seat's cards first, then lanes left→right, then
seqorder. - On the last turn, scoring follows (§7). Otherwise the next turn starts:
- initiative alternates
- any Portal scheduled by
portalRevealis revealed - energy =
energyByTurn[t-1]+ carry +bonusEnergy - each seat draws
- the underdog bonus applies (only if
underdogis on)
- Carry is set: min(
- 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
fizzlelog 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
interface GameCard {
cardId: string; // unique within a deck: the NFT card hash, or `loaner:<pageId>:<n>`
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 callingcreateMatch. - Modes may adjust
GameCardfields such aspowerbeforecreateMatch. The engine does not re-derive them. - A keyword that isn't in
ruleset.keywordsEnablednever runs. Derivation is responsible for not giving that cardvanillaBonus. - 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 withinturnsturns.- Modes merge overrides onto
DEFAULT_RULESETand then callparseRuleset.
Notes on the §9 keys:
topicPoolis inlineTopicDef[] = { id, name, stat, portal: PortalId | null }[].DEFAULT_TOPIC_POOLis the 9 Topics of §10.3. A Portal id is one ofPORTAL_IDS(main-page, trending, featured-article, stub, interwiki, disambiguation).keywordParams[keywordId]holds keyword numbers; keys must be inKEYWORD_IDS.portalParams[topicId]holds Portal numbers, and falls back toportalParams[portalId], so a mode can add a Topic that reuses a Portal kind with new numbers.keywordsEnabled⊆KEYWORD_IDS(the 6 v1 ids plusedition,obscureandwildcard).mulliganmust befalse. Mulligans are not implemented in v1.percentiles,starterDecks,trendUp/Down,trendMinDaily,uncheckedCostCap,vanillaBonus,costThresholds,powerByCost,verifyStatsandfactionSynergyCapare for derivation and the host. The core loop doesn't read them.
Validation also enforces:
turns × turnSeconds ≤ 240energyByTurn.length ≥ turnsportalReveal.length = topicCountopeningHand ≤ handLimitcostThresholdsin ascending order- with
distinctStats,topicCount == 3and 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:
- p0's deck is shuffled.
- p1's deck is shuffled.
- The Topics are drawn. With
distinctStats: for each stat in the orderattention, depth, reach, takegroup[floor(next() × group.length)], wheregroupis that stat's Topics intopicPoolorder. Then the picks are shuffled, and that is the lane order. WithoutdistinctStats: the whole pool is shuffled and the firsttopicCountare taken. - 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. - Keyword and Portal hooks draw in resolution order.
- Shuffles are Fisher–Yates with
ifrom n−1 down to 1 andj = floor(next() × (i+1)). ongoingpower 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:
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:
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
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:
- The seat that leads more Topics.
- If tied on Topics, the seat with more total power.
- 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)andendOfTurn(ctx, self)may changebonuson cards inctx.state.ongoing(ctx, self, target) → numbermust be pure, and must not callctx.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 revealcapacity(ctx) → numberallOnTopic: trueatScoring(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.