forked from WikiDeck/wikideck
224 lines
15 KiB
Markdown
224 lines
15 KiB
Markdown
# 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>:<n>`
|
||
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
|
||
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.
|