diff --git a/docs/game/DUEL_API.md b/docs/game/DUEL_API.md index a52fd32..79c6d99 100644 --- a/docs/game/DUEL_API.md +++ b/docs/game/DUEL_API.md @@ -1,83 +1,88 @@ # WikiDeck Duel: engine API (v1, Night 2) -Owner: **duel-core** (claude/wikideck#55). Types: `shared/duel/types.ts`. Ruleset: `shared/duel/ruleset.ts`. -Function surface: `DuelEngineApi` in `shared/duel/index.ts` (implemented by `shared/duel/engine.ts` in the engine-alpha PR). -`shared/game/` (Edit War) is untouched. Change requests: comment on #55 with `[from ]`. +Owner: **duel-core** (claude/wikideck#55). Rules: `docs/game/DUEL_DESIGN.md` (duel-design). This file: how code talks to the engine. +- Types: `shared/duel/types.ts`. Ruleset: `shared/duel/ruleset.ts`. Function surface: `DuelEngineApi` in `shared/duel/index.ts`, implemented by `shared/duel/engine.ts` (engine-alpha PR). +- `shared/game/` (Edit War) is untouched. Change requests: comment on #55 with `[from ]`. ## Principles -- **Pure and deterministic.** `(rules, decks, seed, actions)` → identical state and log. RNG is `shared/game/rng.ts` (mulberry32), its uint32 state stored in `DuelState.rng`. -- **Plain JSON.** `DuelState` round-trips through `JSON.stringify`/`parse`. `serialize`/`deserialize` are thin wrappers. -- **Clone-on-apply.** `applyAction` never mutates its input; it throws on an illegal action. -- **Atomic actions.** `legalActions(state, seat)` is small and is `[]` for the seat that is not to act. The host checks an action by deep-equal against that list (concede excepted). -- **Off-chain.** Matches never move or burn cards. Cards arrive fully derived and frozen (type, stats, keywords, effects, Connected links); the engine never fetches anything. +- **Pure and deterministic.** `(rules, decks, seed, actions)` → identical state and log. RNG: `shared/game/rng.ts` (mulberry32); its uint32 state lives in `DuelState.rng`. +- **Plain JSON.** `DuelState` round-trips through `JSON.stringify`/`parse`; `serialize`/`deserialize` are thin wrappers. +- **Clone-on-apply.** `applyAction` never mutates its input and throws on an illegal action. +- **Atomic actions.** `legalActions(state, seat)` is small, and `[]` for the seat that is not to act. The host checks an action by deep-equal against that list (`concede` and `timeout` excepted). +- **Off-chain.** Matches never move or burn cards. Cards arrive derived and frozen; the engine does no I/O. ## Cards (`DuelCard`) -Built by duel-cards (`shared/duel/derive.ts`) and frozen by the host at match start. +Built by duel-cards (`derive()`), frozen by the host at match start. Shape agreed with duel-cards on #55. | Field | Notes | |---|---| -| `cardId` | unique in a deck (NFT hash; sample id in sims) | -| `pageId`, `title`, `description?` | `pageId` is used to match Connected pairs | -| `type` | `Figure` (creature) · `Location` (Territory/Garrison permanent) · `Event` (sorcery) · `Institution` (artifact) · `Doctrine` (Aura on a Figure) | -| `portal` | faction id; no deckbuilding restriction | -| `cost` 1–6, `power`, `toughness` | non-Figures use 0/0 | -| `keywords` | ≤ `rules.maxKeywords` (2) of `Protected, Featured, Translated, Legacy, Stub, Well-sourced, Multilingual, Local` | -| `territory?` | Location: +1 max Citations (all sources together ≤ `territoryCap`) | -| `garrison?` | Location may block with `{power, toughness}` | -| `effects` | `EffectSpec[]` (below) | -| `text`, `flavour` | display only (rules text from `text.ts`; flavour = first sentence of `article.extract`) | -| `connections?` | `{pageId, tier, via}[]`, frozen claims | -| `revisionId?`, `source` | for the recap; `'owned' | 'draft' | 'sample'` | +| `cardId` | unique in a deck (NFT tokenId; sample id in sims; `token:` for tokens) | +| `pageId`, `revisionId?`, `title`, `description?` | `pageId` matches Linked pairs; `revisionId` for recap references | +| `type`, `subtype?` | `Figure` · `Location` · `Event` · `Institution` · `Doctrine` | +| `portal` | `Arts, Earth, History, Science, Society, Neutral`; no deckbuilding restriction | +| `cost` | 1–6 (Locations 1–3) | +| `power`, `toughness` | Figures: body. Locations: 0 / Garrison (0 = can't block). Others: `null` or 0 | +| `keywords` | ≤ `maxKeywords` (2). Figures only | +| `territory?` | Location: +N max Citations while controlled (total from all sources ≤ `territoryCap`) | +| `effects` | `EffectSpec[]` (below), ≤ 4 | +| `rulesText`, `flavor` | display only | +| `connect?` | `{countries, centuries, links, p31}` frozen claims; the engine computes Connected | +| `rarity?`, `deriveVersion?`, `token?` | | -Engine-side keyword meanings (designer §3.4; duel-design owns the wording): -- **Protected**: can't be targeted by the opponent's Events or other chosen-target effects. -- **Featured** (flying): can be blocked only by Featured or Translated Figures. -- **Translated** (reach): can block Featured Figures. +### Keywords (DUEL_DESIGN §4), as the engine applies them +- **Protected**: can't be the target of Events or Doctrines an opponent controls (abilities of other permanents and combat still apply). +- **Featured**: can be blocked only by Featured, Translated or Multilingual Figures. +- **Multilingual**: can block Featured; can't be blocked by Local Figures. +- **Translated**: can block Featured. - **Legacy**: when destroyed, its controller draws a card. -- **Stub**: at the start of its controller's turn, gets a +1/+1 counter (at most 2 from Stub). - **Well-sourced**: prevent the first 1 damage dealt to it each turn. -- **Trending** (haste, Trending mode only): no summoning sickness. -- **Multilingual**, **Local**: no engine rule; duel-cards expresses them as `effects` if DUEL_DESIGN gives them one. +- **Stub**: at the start of your turn, a +1/+1 counter, up to `stubMax` (2). +- **Local**: +1/+1 while you control a Location sharing a `connect.countries` value. +- **Trending** (Trending mode, set by the host via `applyLive`): no Pending review, +`trendingPower`/+0. ### Effects (`EffectSpec`) -`{ trigger, op, target, amount?, amount2?, maxPower?, maxCost?, template? }` -- **Triggers:** `onPlay` (Event resolves / permanent enters), `onAttack`, `onDeath`, `startOfTurn`, `static`. -- **Ops (12):** `damage`, `heal`, `drain`, `draw`, `buff` (until end of turn; as `static`, while the source is in play), `counter` (+n/+n permanent), `destroy`, `bounce`, `tap`, `citations`, `ramp`, `mill`. -- **Targets:** chosen: `anyFigure`, `ownFigure`, `enemyFigure`, `enemyPermanent`, `anyTarget`; automatic: `none`, `self`, `attached`, `controller`, `opponent`, `allFigures`, `ownFigures`, `enemyFigures`. Optional filters `maxPower`, `maxCost`. -- **One chosen target per card**: the first `onPlay` effect with a chosen target defines `play.target`; other chosen-target effects on the same card reuse it. A card whose required target has no legal choice can't be played (Events) or enters with that effect fizzling (permanents). -- **Doctrine:** `play.target` is the Figure it attaches to (any Figure you control, unless its effects say `enemyFigure`); its `static` effects with `target: 'attached'` apply to that Figure. If the Figure leaves, the Doctrine goes to the graveyard. -- Triggers resolve immediately in a fixed order: active player's first, then battlefield order (oldest first). +`{ trigger, op, target?, amount?, power?, toughness?, duration?, token?, condition?, grant?, template? }` +- **Triggers:** `onPlay` (Event resolves; on a permanent same as `onEnter`), `onEnter`, `onAttack`, `onDestroyed`, `startOfTurn`, `onCombatDamageToPlayer` (on a Figure, or on a Doctrine for its attached Figure), `static`. +- **Ops:** `damage`, `damageEach`, `createToken`, `pump`, `fight`, `draw`, `attach`, `gainLife`, `drain`, `destroy`, `bounce`, `tap`. +- **Targets:** chosen: `figure`, `figureOrLocation`, `ownFigure`, `opponentFigure`, `anyTarget`; automatic: `each`, `self`, `attached`, `ownFigures`, `opponentFigures`, `opponent`, `controller`. Defaults: damage → `anyTarget`, pump → `self`, draw/gainLife/createToken → `controller`, drain → `opponent`. +- **Chosen targets:** each `onPlay`/`onEnter` effect with a chosen target consumes the next entry of `play.targets`, in effect order; `legalActions` enumerates the combinations. An Event or Doctrine with no legal target can't be played; a Figure/Location/Institution enters and its targeted effect fizzles (`targets` omitted). +- **fight:** the previous chosen target in the same card (else the source permanent) and this target deal damage equal to their power to each other. T6 = `[{op:'pump', target:'ownFigure', power:k, toughness:0}, {op:'fight', target:'opponentFigure'}]`. +- **Doctrine:** its `attach` effect's target is the Figure it attaches to (`ownFigure` for T11, `figure` for T12). Its `static` effects with `target: 'attached'` apply to that Figure; `condition.samePortal` on a Doctrine means "other Figures you control of the attached Figure's Portal". When the Figure leaves, the Doctrine is Deleted. +- **static pump** applies while the source is in play; conditions use **printed** power (no feedback loops). `condition.connected` = the affected Figure is Connected to the source (T9). +- **createToken:** `amount` tokens of `token` (a fresh `DuelCard` with `token: true`, uid `t:`); `condition.maxTokens` = only if you control fewer tokens than that. Tokens leaving play cease to exist. +- Triggers resolve immediately: the active player's first, then in entry order. -## Rules (defaults from `DEFAULT_DUEL_RULESET`) -- 40-card decks, ≤ 4 copies per `pageId`. 20 Notability; 0 loses. Drawing from an empty library loses (`libraryEmpty: 'lose'`; `reshuffle`/`fatigue` exist as data). -- Opening hand 7. Up to `mulligans` (1): shuffle hand in, draw 7, put `mulligansTaken` cards on the bottom (the last ones in hand order, automatically). Both players choose `keep`/`mulligan`; seat 0 then seat 1. -- First player (from the seed) skips the first draw. -- **Turn:** refresh (base max Citations +1 to `maxCitations` 10, plus bonus ≤ `territoryCap` 2; refill; untap; `startOfTurn` triggers) → draw → **main** → **attack** → **block** (only if attackers) → damage → end (temp buffs and damage clear; discard down to `handSize` 7, newest cards first). -- Figures have summoning sickness ("Pending review") unless Trending. Attack the opponent only. Each blocker blocks one attacker, at most one blocker per attacker; untapped Figures and Garrison Locations can block. Damage is simultaneous; unblocked attackers hit Notability. No trample, first strike, stack or instants. -- **Connected:** a Figure gets `+connectedBonus/+connectedBonus` (1) while its controller controls another permanent whose `pageId` appears in its `connections`, or `+linkedBonus` (2) if that link's tier is `Linked`. Only the best link counts. Logged once when it first applies. -- `turnCap` (optional, null by default): after that many total turns, higher Notability wins; equal = draw. +## Rules (defaults: `DEFAULT_DUEL_RULESET`; details in DUEL_DESIGN §2) +- 40-card decks (`deckSize`), ≤ 4 per `pageId`, unique `cardId`s, no tokens. 20 Notability. Drawing from an empty library loses (`libraryEmpty: 'lose'`; `'reshuffle'` and `'fatigue'` exist as data). +- Opening hand 7. Up to `mulligans` (1): shuffle in, draw 7, then on `keep` put one card per mulligan on the bottom (the last in hand order). Seat 0 decides first, then seat 1. +- First player (from the seed) skips their first draw. +- **Turn:** refresh (base max +1 to 10, plus Territory ≤ 2; refill; untap; Pending review ends; Stub and `startOfTurn` triggers) → draw → **main** → **attack** → **block** → damage → end (damage and "until end of turn" clear; discard down to `handSize` 7, **highest cost first**, automatically). +- Locations: `locationsPerTurn` (1), can't attack. Garrison Locations (toughness > 0) block as 0-power. +- Combat: attack the opponent only; each blocker blocks one attacker, at most one blocker per attacker; simultaneous damage; destroy triggers after all combat damage. No trample, first strike, stack or instants. +- **Connected** (engine, from `connect`, tiers in `connectedTiers`): Linked (either `links` contains the other's `pageId`), Compatriot (shared country), Contemporary (shared century, different types), Kin (shared P31, not Q5/Q16521). A Figure gets the single best bonus among other permanents its controller controls: `+linkedBonus` (2) if Linked, else `+connectedBonus` (1). Logged once (`connected`). Opposing Connected pairs are logged once as `rivalry`. +- **Timeouts:** `timeout` passes (mulligan: keep; main/attack: end the turn without attacking; block: confirm current blocks). `timeoutsToConcede` (3) consecutive timeouts by one seat lose (`reason: 'timeout'`). +- `turnCap` (null by default): after that many total turns, higher Notability wins, then higher total power in play, then the second player. ## Phases and actions -`phase`: `mulligan` → `main` → `attack` → `block` → (next turn's `main`) … `over`. - -| Phase | Who acts | Actions | +| Phase | Who acts | Listed actions | |---|---|---| -| `mulligan` | each seat not yet ready (seat 0 first) | `keep`, `mulligan` | -| `main` | active | `play {uid, target?}` (cost ≤ Citations; Events and permanents), `endPhase` | -| `attack` | active | `toggleAttacker {uid}` (declare an untapped, non-sick Figure not yet declared), `confirmAttack` | -| `block` | defender | `block {blocker, attacker}` (unassigned blocker, unblocked attacker), `confirmBlocks` | -| any | either seat | `concede` (not listed; always accepted) | -| any | host only | `timeout` for the seat that must act: in `main`/`attack` ends the turn without attacking, in `block` confirms the current blocks, in `mulligan` keeps. It does **not** lose the game; the host decides when a bank is exhausted and may then send `concede`. | +| `mulligan` | seat 0 until ready, then seat 1 | `keep`, `mulligan` | +| `main` | active | `play {uid, targets?}`, `endPhase` | +| `attack` | active | `toggleAttacker {uid}` (untapped, not Pending review, not yet declared), `confirmAttack` | +| `block` | defender | `block {blocker, attacker}` (unassigned blocker, unblocked attacker, evasion allowing), `confirmBlocks` | +| any | either seat | `concede` (not listed) | +| any | host, for the seat to act | `timeout` (not listed) | -Declarations are **monotonic** (no un-declare action), so every turn has a bounded number of actions; UIs stage choices locally and send them on confirm. If the defender has no legal block, combat damage resolves at `confirmAttack` without a block phase. `confirmAttack` with no attackers ends the turn. Attacking taps the attackers. `onAttack` triggers resolve at `confirmAttack`. +Declarations are **monotonic** (no un-declare), so every turn has a bounded number of actions; UIs stage choices locally and send them on confirm. If the defender has no legal block, damage resolves at `confirmAttack` with no block phase. `confirmAttack` with no attackers ends the turn. ## Views and log -- `viewFor(state, seat): PlayerView`: your hand, sizes of the opponent's hand and library, both graveyards, the battlefield with **current** power/toughness and Connected badge, combat, `toAct`, `version`, `result`. -- `state.log` is the full, omniscient event list (for the server and recap after the match). **Clients get `logFor(state, seat)`**: the opponent's `draw` events lose `card`, and nothing else from a hidden zone is revealed until it becomes public (`play`, `discard`, `mill`). Every event carries `seq` and `turn`. -- Event kinds: `start, mulligan, keep, turn, draw, play, attach, connected, effect, attack, block, damage, life, destroyed, bounced, discard, mill, fatigue, concede, timeout, end`. `destroyed` events are the recap's casualties. Text templates for these live with duel-design / ui-pvp (`shared/duel/recap.ts`), not in the engine. +- `viewFor(state, seat): PlayerView`: your hand; the opponent's hand and library **sizes** only; both graveyards; the battlefield with current power/toughness, keywords and Connected badge; combat; `toAct`; `version`; `result`. Never the RNG or library order. +- `state.log` is omniscient (server, and the recap after the match). Clients get **`logFor(state, seat)`**: the opponent's `draw` events have no `card`. Every other event is public information. +- Every event has `seq` and `turn`. `CardRef` carries `uid, cardId, title, pageId, type` plus `power`/`toughness` right after the event. +- Kinds (DUEL_DESIGN §10 names): `start, mulligan, keep, turnStart, draw, deploy, cast, adopt, tokenCreated, connected, rivalry, effect, attack, block, effectDamage, combatDamage, playerDamage, lifeGain, destroyed, bounced, discard, fatigue, concede, timeout, gameOver`. `destroyed` = the recap's casualties. Prose templates live with duel-design / ui-pvp, not in the engine. ## Host binding -`shared/duel/engine.ts` will also export `duelEnginePort: EnginePort` (shape of `server/game/engine-port.ts`): `concedeAction`, `timeoutAction`, `turnSeconds`, `turnOf` included; `starterDeck`/`previewPool` throw (no starters, BRIEF decision 2) except where draft supplies the pool. host-pvp wires it into `server/game/`. +`duelEnginePort` (engine.ts) is structurally an `EnginePort` (`server/game/engine-port.ts`; `shared/` doesn't import `server/`, so host-pvp types it there). `concedeAction`, `timeoutAction`, `turnSeconds`, `turnOf`, `applyLive` included. `starterDeck` and `previewPool` throw: there are no starters (BRIEF decision 2); draft pools come from both players' collections. ## Stability -Types in this file are the contract for duel-cards, host-pvp, ui-duel, ui-pvp and sim-balance. Additive changes (new optional fields, new log kinds) can land with the engine; breaking ones get a `[duel-core] contract change` comment on #55 first. +These types are the contract for duel-cards, host-pvp, ui-duel, ui-pvp and sim-balance. Additive changes (optional fields, new log kinds) can land with the engine; breaking ones get a `[duel-core] contract change` comment on #55 first. diff --git a/shared/duel/ruleset.ts b/shared/duel/ruleset.ts index fb33fc0..8c7e2a3 100644 --- a/shared/duel/ruleset.ts +++ b/shared/duel/ruleset.ts @@ -21,12 +21,18 @@ export const DuelRulesetSchema = z.object({ maxCitations: int(1, 20), citationsPerTurn: int(1, 5), territoryCap: int(0, 10), + locationsPerTurn: int(0, 10), libraryEmpty: z.enum(['lose', 'reshuffle', 'fatigue']), maxKeywords: int(0, 4), + stubMax: int(0, 10), + trendingPower: int(0, 5), + connectedTiers: z.array(z.enum(['Linked', 'Compatriot', 'Contemporary', 'Kin'])).max(4) + .refine(v => new Set(v).size === v.length, 'Duplicate tier'), connectedBonus: int(0, 5), linkedBonus: int(0, 5), turnSeconds: int(5, 600), bankSeconds: int(0, 3600), + timeoutsToConcede: int(1, 20), turnCap: int(2, 200).nullable(), }).strict(); @@ -43,12 +49,17 @@ export const DEFAULT_DUEL_RULESET: DuelRuleset = Object.freeze({ maxCitations: 10, citationsPerTurn: 1, territoryCap: 2, + locationsPerTurn: 1, libraryEmpty: 'lose', maxKeywords: 2, + stubMax: 2, + trendingPower: 1, + connectedTiers: ['Linked', 'Compatriot', 'Contemporary', 'Kin'], connectedBonus: 1, linkedBonus: 2, turnSeconds: 60, bankSeconds: 300, + timeoutsToConcede: 3, turnCap: null, }) as DuelRuleset; @@ -59,7 +70,7 @@ export function parseDuelRuleset(value: unknown): DuelRuleset { /** Merge a partial override (a mode file's `rules`) onto the defaults, then validate. */ export function mergeDuelRuleset(overrides: unknown, base: DuelRuleset = DEFAULT_DUEL_RULESET): DuelRuleset { - if (overrides === undefined || overrides === null) return parseDuelRuleset({ ...base }); + if (overrides === undefined || overrides === null) return parseDuelRuleset(structuredClone(base)); if (typeof overrides !== 'object' || Array.isArray(overrides)) throw new TypeError('Ruleset overrides must be an object'); - return parseDuelRuleset({ ...base, ...(overrides as Record) }); + return parseDuelRuleset({ ...structuredClone(base), ...(overrides as Record) }); } diff --git a/shared/duel/types.ts b/shared/duel/types.ts index f1b181c..a2d7e62 100644 --- a/shared/duel/types.ts +++ b/shared/duel/types.ts @@ -1,6 +1,6 @@ /** * WikiDeck Duel: the Magic-style 40-card engine (off-chain). Contract types. - * Spec: docs/game/DUEL_API.md. Owner: duel-core (claude/wikideck#55). + * Spec: docs/game/DUEL_API.md (rules: docs/game/DUEL_DESIGN.md). Owner: duel-core (claude/wikideck#55). * * Everything here is plain JSON data: DuelState round-trips through * JSON.stringify/parse with no loss (no Maps, classes or functions). @@ -18,106 +18,133 @@ export const SEATS: readonly Seat[] = [0, 1]; export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine'; export const CARD_TYPES: readonly CardType[] = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine']; -/** Keyword ids (BRIEF "Keywords"). At most `ruleset.maxKeywords` (2) per card. */ -/** Engine rules per keyword: docs/game/DUEL_API.md "Cards". 'Trending' (haste) is Trending-mode only. */ -export type Keyword = 'Protected' | 'Featured' | 'Translated' | 'Legacy' | 'Stub' | 'Well-sourced' | 'Multilingual' | 'Local' | 'Trending'; -export const KEYWORDS: readonly Keyword[] = ['Protected', 'Featured', 'Translated', 'Legacy', 'Stub', 'Well-sourced', 'Multilingual', 'Local', 'Trending']; +export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral'; +export const PORTALS: readonly Portal[] = ['Arts', 'Earth', 'History', 'Science', 'Society', 'Neutral']; -/** Connected tiers (BRIEF "Connected", data §4). 'Linked' is the direct connection. */ +/** Card keywords (DUEL_DESIGN §4), ≤ ruleset.maxKeywords per card. 'Trending' is granted by Trending mode only. */ +export type Keyword = 'Protected' | 'Featured' | 'Legacy' | 'Multilingual' | 'Translated' | 'Well-sourced' | 'Stub' | 'Local' | 'Trending'; +export const KEYWORDS: readonly Keyword[] = ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Translated', 'Well-sourced', 'Stub', 'Local', 'Trending']; + +/** Connected tiers (DUEL_DESIGN §6). The engine computes them from `connect`. */ export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin'; +export const CONNECTED_TIERS: readonly ConnectedTier[] = ['Linked', 'Compatriot', 'Contemporary', 'Kin']; + +/** Frozen claims used for Connected (no I/O during a match). */ +export interface ConnectKeys { + /** P17/P27 values (Q-ids or labels; compared as strings). */ + countries: string[]; + /** From P569/P570/P571/P580/P585, e.g. 19 for the 1800s. */ + centuries: number[]; + /** Outlink pageIds (cached), plus pageIds the card's claims cite. */ + links: number[]; + /** P31 Q-ids. Q5 (human) and Q16521 (taxon) never count for Kin. */ + p31: string[]; +} /** When an effect runs. Sorcery speed only: there is no stack and no response window. */ export type EffectTrigger = - | 'onPlay' // Event resolves, or a permanent enters the battlefield - | 'onAttack' // this Figure is declared as an attacker (resolves at confirmAttack) - | 'onDeath' // this permanent goes to the graveyard from the battlefield - | 'startOfTurn' // its controller's refresh step - | 'static'; // continuous while on the battlefield (Institution, Doctrine, Location) + | 'onPlay' // an Event resolves (on a permanent: same as onEnter) + | 'onEnter' // this permanent enters the battlefield + | 'onAttack' // this Figure is declared as an attacker (resolves at confirmAttack) + | 'onDestroyed' // this permanent is destroyed (after all combat damage) + | 'startOfTurn' // its controller's refresh step, in entry order + | 'onCombatDamageToPlayer' // this Figure (or the Figure this Doctrine is attached to) deals combat damage to a player + | 'static'; // continuous while on the battlefield -/** The ≤12 effect ops the interpreter knows. duel-cards builds templates from these. */ +/** Effect ops the interpreter knows. duel-cards builds the 12 templates (DUEL_DESIGN §5) from these. */ export type EffectOp = - | 'damage' // deal `amount` damage to each target (Figure or player) - | 'heal' // target player gains `amount` Notability - | 'drain' // target player loses `amount`, controller gains `amount` - | 'draw' // controller draws `amount` - | 'buff' // +amount/+amount2 until end of turn (static: while the source is in play) - | 'counter' // permanent +amount/+amount counters - | 'destroy' // destroy target permanent - | 'bounce' // return target permanent to its owner's hand - | 'tap' // tap target permanent - | 'citations' // controller gains `amount` Citations this turn - | 'ramp' // controller's max Citations +amount (counts against ruleset.territoryCap) - | 'mill'; // target player puts the top `amount` library cards into the graveyard + | 'damage' // `amount` to each target (Figure, Location or player) + | 'damageEach' // `amount` to every Figure and Location (target narrows: 'ownFigures' / 'opponentFigures') + | 'createToken' // `amount` (default 1) copies of `token` under the controller; condition.maxTokens limits + | 'pump' // +power/+toughness (negative allowed); duration 'turn' | 'permanent'; as static: while the source is in play + | 'fight' // the previous chosen target (else this permanent) and this target deal damage equal to their power to each other + | 'draw' // controller draws `amount` + | 'attach' // Doctrine: attach to the target Figure (defines the Doctrine's target) + | 'gainLife' // controller gains `amount` Notability + | 'drain' // opponent loses `amount`, controller gains `amount` + | 'destroy' // destroy target permanent + | 'bounce' // return target permanent to its owner's hand + | 'tap'; // tap target permanent export type TargetSpec = - | 'none' // no target (draw, citations, ramp) - | 'self' // the source permanent itself - | 'attached' // the Figure a Doctrine is attached to - | 'controller' // the source's controller - | 'opponent' // the opposing player - | 'anyFigure' // chosen: any Figure - | 'ownFigure' // chosen: a Figure you control - | 'enemyFigure' // chosen: a Figure the opponent controls - | 'enemyPermanent' // chosen: any opposing permanent - | 'anyTarget' // chosen: any Figure or player - | 'allFigures' // every Figure - | 'ownFigures' // every Figure you control - | 'enemyFigures'; // every opposing Figure + // chosen (each consumes one entry of play.targets, in effect order) + | 'figure' // any Figure + | 'figureOrLocation' // any Figure or Location + | 'ownFigure' // a Figure you control + | 'opponentFigure' // a Figure you don't control + | 'anyTarget' // any Figure, Location or player + // automatic + | 'each' // every Figure and Location + | 'self' // this permanent + | 'attached' // the Figure this Doctrine is attached to + | 'ownFigures' // every Figure you control + | 'opponentFigures' // every Figure you don't control + | 'opponent' // the opposing player + | 'controller'; // you + +export interface TokenSpec { name: string; power: number; toughness: number; portal: Portal } export interface EffectSpec { trigger: EffectTrigger; op: EffectOp; - target: TargetSpec; + /** Default per op: damage → 'anyTarget'; pump → 'self'; draw/gainLife/createToken → 'controller'; drain → 'opponent'. */ + target?: TargetSpec; amount?: number; - /** Second number where an op needs one (buff: toughness; default = amount). */ - amount2?: number; - /** Optional filter on chosen/all targets: only Figures with power ≤ maxPower, cost ≤ maxCost. */ - maxPower?: number; - maxCost?: number; - /** Template id from shared/duel/effects.ts (for rules text and log wording). */ + /** pump: +power/+toughness (default: amount/amount). */ + power?: number; + toughness?: number; + /** pump/grant outside static: 'turn' (default) or 'permanent'. */ + duration?: 'turn' | 'permanent'; + token?: TokenSpec; + condition?: { + /** Only affects Figures with printed power ≤ maxPower. */ + maxPower?: number; + /** Only Figures of the source's Portal (for a Doctrine: the attached Figure's Portal), excluding that card itself. */ + samePortal?: boolean; + /** Only Figures Connected to the source. */ + connected?: boolean; + /** createToken: only if the controller controls fewer than this many tokens. */ + maxTokens?: number; + }; + /** Keywords granted to the affected Figures (static: while in play; otherwise for `duration`). */ + grant?: Keyword[]; + /** Template id (T1–T12) for rules text and log wording. */ template?: string; } -export interface ConnectedLink { - /** The other card's Wikipedia page id (pairs are matched by pageId, never by I/O). */ - pageId: number; - tier: ConnectedTier; - /** Why, for the card face and log: e.g. "country: Bangladesh". */ - via: string; -} - /** - * A card as the engine sees it, frozen at match start (classification, stats, - * Connected links). The host builds these from the chain; the engine trusts them. + * A card as the engine sees it, frozen at match start. The host builds these + * from the chain via duel-cards' derive(); the engine trusts them. */ export interface DuelCard { - /** Unique within one deck: the NFT card hash (or a sample id in sims). */ + /** Unique within one deck: the NFT tokenId (or a sample id in sims; `token:` ids for tokens). */ cardId: string; pageId: number | null; + revisionId?: number; title: string; - /** Short description line ("American actor (1909–1994)") for log first mentions. */ + /** Wikidata description ("American actor (1909–1994)"), for log first mentions. */ description?: string; type: CardType; - /** Faction ("Portal") id, cosmetic for deckbuilding (no colour restrictions). */ - portal: string; + /** e.g. 'conflict', 'election', 'organisation', 'pathology'. */ + subtype?: string | null; + portal: Portal; cost: number; - /** Figures; 0 for other types. */ - power: number; - toughness: number; + /** Figures: the body. Locations: power 0, toughness = Garrison (0 = can't block). Others: null or 0. */ + power: number | null; + toughness: number | null; keywords: Keyword[]; - /** Locations: +1 max Citations each (capped by ruleset.territoryCap in total). */ - territory?: boolean; - /** Locations with Garrison may block with these stats. */ - garrison?: { power: number; toughness: number }; + /** Locations: +N max Citations while controlled (all sources together ≤ territoryCap). */ + territory?: number; effects: EffectSpec[]; /** Deterministic rules text (shared/duel/text.ts). Display only. */ - text: string; - /** First sentence of article.extract. Display only. */ - flavour: string; - connections?: ConnectedLink[]; - /** For recap references. */ - revisionId?: number; - source: 'owned' | 'draft' | 'sample'; + rulesText: string; + /** First sentence of article.extract (else description). Display only. */ + flavor: string; + connect?: ConnectKeys; + rarity?: 'Common' | 'Rare' | 'Epic' | 'Legendary'; + deriveVersion?: string; + /** Tokens are created in play and never in decks. */ + token?: boolean; } // --------------------------------------------------------------------------- @@ -130,22 +157,27 @@ export interface DuelRuleset { engine: 'duel'; version: string; deckSize: number; // 40 - maxCopiesPerPage: number; // 4: copies of one pageId in a deck + maxCopiesPerPage: number; // 4 startingLife: number; // 20 Notability openingHand: number; // 7 - handSize: number; // 7: hand limit at end of turn (excess discarded, newest first) - mulligans: number; // 1: shuffle, draw openingHand, bottom `mulligans taken` - firstPlayerDraws: boolean; // false: the first player skips their first draw - maxCitations: number; // 10: cap on base income - citationsPerTurn: number; // 1: base max rises by this each of your turns - territoryCap: number; // 2: total extra max Citations from Locations/ramp + handSize: number; // 7: hand limit at end of turn (DUEL_DESIGN `handLimit`); excess discarded highest cost first + mulligans: number; // 1: shuffle, draw openingHand, bottom one per mulligan taken + firstPlayerDraws: boolean; // false + maxCitations: number; // 10 + citationsPerTurn: number; // 1 + territoryCap: number; // 2 + locationsPerTurn: number; // 1 libraryEmpty: LibraryEmpty; // 'lose' maxKeywords: number; // 2 - connectedBonus: number; // 1: +1/+1 while you control a Connected card - linkedBonus: number; // 2: +2/+2 when the connection is Linked (direct) + stubMax: number; // 2: max Stub counters + trendingPower: number; // 1: Trending gets +N/+0 + connectedTiers: ConnectedTier[]; // all four; cut tiers by removing them + connectedBonus: number; // 1 + linkedBonus: number; // 2 turnSeconds: number; // 60 bankSeconds: number; // 300 - /** Optional: after this many turns in total, more Notability wins (tie: draw). null = none. */ + timeoutsToConcede: number; // 3 consecutive timeouts lose + /** Optional: after this many turns in total, higher Notability wins, then higher power in play, then the second player. */ turnCap: number | null; } @@ -153,10 +185,10 @@ export interface DuelRuleset { // State // --------------------------------------------------------------------------- -/** 'mulligan' → 'main' → 'attack' → ('block' if attackers) → next turn. Refresh, draw, damage and end are automatic steps. */ +/** 'mulligan' → 'main' → 'attack' → ('block' if attackers can be blocked) → next turn. Refresh, draw, damage and end are automatic. */ export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over'; -/** One physical card in a match. `uid` is unique per match ("0:12" = seat 0, deck index 12); actions use uids. */ +/** One physical card in a match. `uid` is unique per match ("0:12" = seat 0, deck index 12; "t:3" = token); actions use uids. */ export interface CardInstance { uid: string; owner: Seat; @@ -169,19 +201,25 @@ export interface Permanent extends CardInstance { /** "Pending review": entered this turn, can't attack. */ sick: boolean; damage: number; - /** Permanent +1/+1 counters. */ + /** Stub +1/+1 counters. */ counters: number; + /** Permanent pump modifiers. */ + permPower: number; + permToughness: number; /** Until-end-of-turn modifiers. */ tempPower: number; tempToughness: number; + /** Keywords granted until end of turn / permanently by non-static effects. */ + tempKeywords: Keyword[]; + permKeywords: Keyword[]; /** Doctrines: uid of the Figure they're attached to. */ attachedTo?: string; /** Well-sourced: prevention already used this turn. */ - shielded?: boolean; - /** Stub: counters gained from Stub so far (≤ 2). */ - stubCounters?: number; + shielded: boolean; + /** Entry order (trigger order). */ + entered: number; /** Connected bonus already logged. */ - connectedLogged?: boolean; + connectedLogged: boolean; } export interface PlayerState { @@ -190,17 +228,18 @@ export interface PlayerState { citations: number; /** Base max (rises by citationsPerTurn to maxCitations). */ baseCitations: number; - /** Extra max from Territory/ramp, ≤ territoryCap. */ - bonusCitations: number; library: CardInstance[]; // top = index 0. Hidden. hand: CardInstance[]; // hidden from the opponent - graveyard: CardInstance[]; // public + graveyard: CardInstance[]; // "Deleted", public mulligansTaken: number; - ready: boolean; // kept the opening hand - /** Remaining time bank, in seconds (the host decrements it). */ + ready: boolean; + locationsThisTurn: number; + /** Remaining time bank in seconds (the host decrements it). */ bankSeconds: number; - /** libraryEmpty 'fatigue': damage of the next empty draw minus 1. */ - fatigue?: number; + /** Consecutive timeouts. */ + timeouts: number; + /** libraryEmpty 'fatigue': damage of the last empty draw. */ + fatigue: number; } export interface CombatState { @@ -209,9 +248,11 @@ export interface CombatState { blocks: Record; } +export type EndReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap'; + export interface DuelResult { winner: Seat | null; // null = draw - reason: 'life' | 'library' | 'concede' | 'timeout' | 'turnCap'; + reason: EndReason; } export interface DuelState { @@ -231,6 +272,9 @@ export interface DuelState { result: DuelResult | null; /** Increments on every applied action (host polling: unchanged → 204). */ version: number; + /** Counters for token uids and entry order. */ + nextToken: number; + nextEntry: number; } // --------------------------------------------------------------------------- @@ -242,46 +286,57 @@ export type TargetRef = { kind: 'card'; uid: string } | { kind: 'player'; seat: export type DuelAction = | { type: 'keep' } | { type: 'mulligan' } - | { type: 'play'; uid: string; target?: TargetRef } - | { type: 'endPhase' } // main → attack - | { type: 'toggleAttacker'; uid: string } // attack phase: declare one more attacker (monotonic; UIs stage undo locally) - | { type: 'confirmAttack' } // no attackers → end turn - | { type: 'block'; blocker: string; attacker: string } // block phase (defender), monotonic - | { type: 'confirmBlocks' } // damage, then end of turn - | { type: 'concede' } // any time, either seat - | { type: 'timeout' }; // host-only, for the seat that must act + /** targets: one per chosen-target effect, in effect order (Doctrine: its 'attach' target). Omitted when none. */ + | { type: 'play'; uid: string; targets?: TargetRef[] } + | { type: 'endPhase' } // main → attack + | { type: 'toggleAttacker'; uid: string } // declare one more attacker (monotonic) + | { type: 'confirmAttack' } // no attackers → end turn + | { type: 'block'; blocker: string; attacker: string } // defender, monotonic + | { type: 'confirmBlocks' } // damage, then end of turn + | { type: 'concede' } // any time, either seat (not listed) + | { type: 'timeout' }; // host-only, for the seat that must act (not listed) // --------------------------------------------------------------------------- -// Log (encyclopedic, per seat via logFor; full log stays in DuelState.log) +// Log (encyclopedic; clients get logFor(state, seat); state.log is omniscient) // --------------------------------------------------------------------------- -/** Public reference to a card in the log. */ -export interface CardRef { uid: string; cardId: string; title: string; pageId: number | null } +/** A card in the log. power/toughness: current values right after the event (Figures and Garrisons on the battlefield). */ +export interface CardRef { uid: string; cardId: string; title: string; pageId: number | null; type: CardType; power?: number; toughness?: number } export type LogEvent = { seq: number; turn: number } & ( | { kind: 'start'; firstSeat: Seat } | { kind: 'mulligan'; seat: Seat } | { kind: 'keep'; seat: Seat; handSize: number } - | { kind: 'turn'; seat: Seat; citations: number } + | { kind: 'turnStart'; seat: Seat; citations: number; life: [number, number] } /** card is omitted in the opponent's logFor (hidden draw). */ | { kind: 'draw'; seat: Seat; card?: CardRef } - | { kind: 'play'; seat: Seat; card: CardRef; cardType: CardType; target?: TargetRef } - | { kind: 'attach'; seat: Seat; card: CardRef; to: CardRef } + /** A Figure, Location or Institution entered. */ + | { kind: 'deploy'; seat: Seat; card: CardRef } + /** An Event resolved. */ + | { kind: 'cast'; seat: Seat; card: CardRef; targets: TargetRef[] } + /** A Doctrine was attached. */ + | { kind: 'adopt'; seat: Seat; card: CardRef; to: CardRef } + | { kind: 'tokenCreated'; seat: Seat; card: CardRef; source: CardRef } | { kind: 'connected'; seat: Seat; card: CardRef; with: CardRef; tier: ConnectedTier; via: string; bonus: number } - | { kind: 'effect'; seat: Seat; source: CardRef; op: EffectOp; template?: string; amount?: number; targets: TargetRef[] } + /** Rivalry (log only): two opposing permanents are Connected. */ + | { kind: 'rivalry'; card: CardRef; with: CardRef; tier: ConnectedTier; via: string } + /** Any resolved effect (wording key: template). Damage and life changes follow as their own events. */ + | { kind: 'effect'; seat: Seat; source: CardRef; op: EffectOp; template?: string; targets: TargetRef[] } | { kind: 'attack'; seat: Seat; attackers: CardRef[] } | { kind: 'block'; seat: Seat; blocks: { blocker: CardRef; attacker: CardRef }[] } - | { kind: 'damage'; source: CardRef; target: TargetRef; amount: number } - | { kind: 'life'; seat: Seat; delta: number; life: number } + /** Damage to a permanent from an effect / from combat. */ + | { kind: 'effectDamage'; source: CardRef; target: CardRef; amount: number } + | { kind: 'combatDamage'; source: CardRef; target: CardRef; amount: number } + /** Damage or life loss to a player. source null = fatigue. */ + | { kind: 'playerDamage'; source: CardRef | null; seat: Seat; amount: number; life: number; combat: boolean } + | { kind: 'lifeGain'; source: CardRef; seat: Seat; amount: number; life: number } | { kind: 'destroyed'; card: CardRef; owner: Seat } | { kind: 'bounced'; card: CardRef; owner: Seat } - /** card is omitted for the opponent if it left a hidden zone unseen (mill shows it: graveyard is public). */ | { kind: 'discard'; seat: Seat; card: CardRef } - | { kind: 'mill'; seat: Seat; card: CardRef } | { kind: 'fatigue'; seat: Seat; amount: number } | { kind: 'concede'; seat: Seat } | { kind: 'timeout'; seat: Seat } - | { kind: 'end'; winner: Seat | null; reason: DuelResult['reason'] } + | { kind: 'gameOver'; winner: Seat | null; reason: EndReason; life: [number, number] } ); export type LogKind = LogEvent['kind']; @@ -300,9 +355,10 @@ export interface PermanentView { damage: number; counters: number; attachedTo?: string; - /** Current stats after counters, temp buffs, statics and Connected. */ + /** Current values after counters, pumps, statics, Connected and Trending. */ power: number; toughness: number; + keywords: Keyword[]; /** Active Connected bonus, if any (for the card face). */ connected?: { with: string; tier: ConnectedTier; via: string; bonus: number }; }