forked from WikiDeck/wikideck
90 lines
9.8 KiB
Markdown
90 lines
9.8 KiB
Markdown
# WikiDeck Duel: engine API (v1, Night 2)
|
||
|
||
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 <agent>]`.
|
||
|
||
## Principles
|
||
- **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 (`derive()`), frozen by the host at match start. Shape agreed with duel-cards on #55.
|
||
|
||
| Field | Notes |
|
||
|---|---|
|
||
| `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?` | |
|
||
|
||
### 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.
|
||
- **Well-sourced**: prevent the first 1 damage dealt to it each turn.
|
||
- **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?, 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:<n>`); `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: `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`, or either `cites` contains the other's `qid`), 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 | Who acts | Listed actions |
|
||
|---|---|---|
|
||
| `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), 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; 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.
|
||
- **The seed is secret until the match ends.** `seed` plus the deck lists reproduce every shuffle, so the host never sends `seed` or `rng` (or the raw `DuelState`) to clients before `gameOver`. Live log rendering picks template variants from a derived `storySeed = sha256(seed + ':story')`.
|
||
- `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
|
||
`duelEnginePort` (engine.ts) is structurally an `EnginePort<DuelRuleset, DuelCard, DuelState, DuelAction>` (`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
|
||
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.
|