duel-core: shared/duel contracts (types, ruleset) and DUEL_API.md
Refs #55. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
# 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 <agent>]`.
|
||||
|
||||
## 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.
|
||||
|
||||
## Cards (`DuelCard`)
|
||||
Built by duel-cards (`shared/duel/derive.ts`) and frozen by the host at match start.
|
||||
|
||||
| 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'` |
|
||||
|
||||
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.
|
||||
- **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.
|
||||
|
||||
### 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).
|
||||
|
||||
## 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.
|
||||
|
||||
## Phases and actions
|
||||
`phase`: `mulligan` → `main` → `attack` → `block` → (next turn's `main`) … `over`.
|
||||
|
||||
| Phase | Who acts | 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}` (untapped, non-sick Figure), `confirmAttack` |
|
||||
| `block` | defender | `block {blocker, attacker}`, `unblock {blocker}`, `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`. |
|
||||
|
||||
`confirmAttack` with no attackers ends the turn. Attacking taps the attackers. `onAttack` triggers resolve at `confirmAttack`.
|
||||
|
||||
## 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.
|
||||
|
||||
## Host binding
|
||||
`shared/duel/engine.ts` will also export `duelEnginePort: EnginePort<DuelRuleset, DuelCard, DuelState, DuelAction>` (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/`.
|
||||
|
||||
## 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.
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* WikiDeck Duel public API. Spec: docs/game/DUEL_API.md.
|
||||
* Contracts PR: types and ruleset only. engine.ts (createDuel, legalActions,
|
||||
* applyAction, viewFor, logFor, replay, ...) lands in the engine alpha PR and
|
||||
* implements DuelEngineApi below; build against that interface until then.
|
||||
*/
|
||||
export * from './types.ts';
|
||||
export * from './ruleset.ts';
|
||||
|
||||
import type { DuelAction, DuelCard, DuelResult, DuelRuleset, DuelState, LogEvent, PlayerView, Seat } from './types.ts';
|
||||
|
||||
/** The engine's function surface (implemented by shared/duel/engine.ts). All pure; inputs are never mutated. */
|
||||
export interface DuelEngineApi {
|
||||
/** Throws if the deck is illegal: size ≠ deckSize, duplicate cardId, > maxCopiesPerPage of one pageId, bad stats, > maxKeywords. */
|
||||
validateDeck(rules: DuelRuleset, cards: DuelCard[]): void;
|
||||
/** Shuffle both decks from `seed`, deal opening hands, phase 'mulligan'. */
|
||||
createDuel(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string): DuelState;
|
||||
/** Atomic legal actions for `seat`; [] if `seat` is not the one to act (concede is always accepted by applyAction but not listed). */
|
||||
legalActions(state: DuelState, seat: Seat): DuelAction[];
|
||||
/** Returns a new state. Throws on an illegal action. */
|
||||
applyAction(state: DuelState, seat: Seat, action: DuelAction): DuelState;
|
||||
/** Seat that must act now, or null when over. Mulligan: the lowest seat not yet ready. */
|
||||
toAct(state: DuelState): Seat | null;
|
||||
isOver(state: DuelState): boolean;
|
||||
result(state: DuelState): DuelResult | null;
|
||||
viewFor(state: DuelState, seat: Seat): PlayerView;
|
||||
/** Per-seat log: the opponent's draws (and other hidden-zone cards) are masked. */
|
||||
logFor(state: DuelState, seat: Seat): LogEvent[];
|
||||
/** Deterministic: same inputs → identical state (and log). */
|
||||
replay(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string, actions: { seat: Seat; action: DuelAction }[]): DuelState;
|
||||
serialize(state: DuelState): string;
|
||||
deserialize(text: string): DuelState;
|
||||
/** Current power/toughness of a permanent after counters, buffs, statics and Connected. */
|
||||
statsOf(state: DuelState, uid: string): { power: number; toughness: number };
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Duel ruleset: every rule number as data (BRIEF "Game rules core").
|
||||
* parseDuelRuleset() is the only way untrusted JSON (mode files, peer hosts)
|
||||
* becomes a DuelRuleset. Night 1 Edit War rulesets are rejected cleanly.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import type { DuelRuleset } from './types.ts';
|
||||
|
||||
const int = (min: number, max: number) => z.number().int().min(min).max(max);
|
||||
|
||||
export const DuelRulesetSchema = z.object({
|
||||
engine: z.literal('duel'),
|
||||
version: z.string().min(1).max(16),
|
||||
deckSize: int(1, 60),
|
||||
maxCopiesPerPage: int(1, 60),
|
||||
startingLife: int(1, 100),
|
||||
openingHand: int(0, 10),
|
||||
handSize: int(1, 15),
|
||||
mulligans: int(0, 3),
|
||||
firstPlayerDraws: z.boolean(),
|
||||
maxCitations: int(1, 20),
|
||||
citationsPerTurn: int(1, 5),
|
||||
territoryCap: int(0, 10),
|
||||
libraryEmpty: z.enum(['lose', 'reshuffle', 'fatigue']),
|
||||
maxKeywords: int(0, 4),
|
||||
connectedBonus: int(0, 5),
|
||||
linkedBonus: int(0, 5),
|
||||
turnSeconds: int(5, 600),
|
||||
bankSeconds: int(0, 3600),
|
||||
turnCap: int(2, 200).nullable(),
|
||||
}).strict();
|
||||
|
||||
export const DEFAULT_DUEL_RULESET: DuelRuleset = Object.freeze({
|
||||
engine: 'duel',
|
||||
version: 'duel-1',
|
||||
deckSize: 40,
|
||||
maxCopiesPerPage: 4,
|
||||
startingLife: 20,
|
||||
openingHand: 7,
|
||||
handSize: 7,
|
||||
mulligans: 1,
|
||||
firstPlayerDraws: false,
|
||||
maxCitations: 10,
|
||||
citationsPerTurn: 1,
|
||||
territoryCap: 2,
|
||||
libraryEmpty: 'lose',
|
||||
maxKeywords: 2,
|
||||
connectedBonus: 1,
|
||||
linkedBonus: 2,
|
||||
turnSeconds: 60,
|
||||
bankSeconds: 300,
|
||||
turnCap: null,
|
||||
}) as DuelRuleset;
|
||||
|
||||
/** Validate a full ruleset. Throws (ZodError) on anything invalid or unknown. */
|
||||
export function parseDuelRuleset(value: unknown): DuelRuleset {
|
||||
return DuelRulesetSchema.parse(value) as 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 (typeof overrides !== 'object' || Array.isArray(overrides)) throw new TypeError('Ruleset overrides must be an object');
|
||||
return parseDuelRuleset({ ...base, ...(overrides as Record<string, unknown>) });
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
/**
|
||||
* WikiDeck Duel: the Magic-style 40-card engine (off-chain). Contract types.
|
||||
* Spec: docs/game/DUEL_API.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).
|
||||
* shared/game/ (Edit War) is a separate engine and is not affected.
|
||||
*/
|
||||
import type { RngState } from '../game/rng.ts';
|
||||
|
||||
export type Seat = 0 | 1;
|
||||
export const SEATS: readonly Seat[] = [0, 1];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cards (derived by duel-cards in shared/duel/derive.ts; the engine never re-derives)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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'];
|
||||
|
||||
/** Connected tiers (BRIEF "Connected", data §4). 'Linked' is the direct connection. */
|
||||
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
|
||||
|
||||
/** 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)
|
||||
|
||||
/** The ≤12 effect ops the interpreter knows. duel-cards builds templates 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
|
||||
|
||||
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
|
||||
|
||||
export interface EffectSpec {
|
||||
trigger: EffectTrigger;
|
||||
op: EffectOp;
|
||||
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). */
|
||||
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.
|
||||
*/
|
||||
export interface DuelCard {
|
||||
/** Unique within one deck: the NFT card hash (or a sample id in sims). */
|
||||
cardId: string;
|
||||
pageId: number | null;
|
||||
title: string;
|
||||
/** Short description line ("American actor (1909–1994)") for log first mentions. */
|
||||
description?: string;
|
||||
type: CardType;
|
||||
/** Faction ("Portal") id, cosmetic for deckbuilding (no colour restrictions). */
|
||||
portal: string;
|
||||
cost: number;
|
||||
/** Figures; 0 for other types. */
|
||||
power: number;
|
||||
toughness: number;
|
||||
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 };
|
||||
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';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ruleset (all numbers are data; parseDuelRuleset in ruleset.ts validates)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type LibraryEmpty = 'lose' | 'reshuffle' | 'fatigue';
|
||||
|
||||
export interface DuelRuleset {
|
||||
engine: 'duel';
|
||||
version: string;
|
||||
deckSize: number; // 40
|
||||
maxCopiesPerPage: number; // 4: copies of one pageId in a deck
|
||||
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
|
||||
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)
|
||||
turnSeconds: number; // 60
|
||||
bankSeconds: number; // 300
|
||||
/** Optional: after this many turns in total, more Notability wins (tie: draw). null = none. */
|
||||
turnCap: number | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// State
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 'mulligan' → 'main' → 'attack' → ('block' if attackers) → next turn. Refresh, draw, damage and end are automatic steps. */
|
||||
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. */
|
||||
export interface CardInstance {
|
||||
uid: string;
|
||||
owner: Seat;
|
||||
card: DuelCard;
|
||||
}
|
||||
|
||||
export interface Permanent extends CardInstance {
|
||||
controller: Seat;
|
||||
tapped: boolean;
|
||||
/** "Pending review": entered this turn, can't attack. */
|
||||
sick: boolean;
|
||||
damage: number;
|
||||
/** Permanent +1/+1 counters. */
|
||||
counters: number;
|
||||
/** Until-end-of-turn modifiers. */
|
||||
tempPower: number;
|
||||
tempToughness: number;
|
||||
/** Doctrines: uid of the Figure they're attached to. */
|
||||
attachedTo?: string;
|
||||
}
|
||||
|
||||
export interface PlayerState {
|
||||
life: number;
|
||||
/** Citations available this turn. */
|
||||
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
|
||||
mulligansTaken: number;
|
||||
ready: boolean; // kept the opening hand
|
||||
/** Remaining time bank, in seconds (the host decrements it). */
|
||||
bankSeconds: number;
|
||||
}
|
||||
|
||||
export interface CombatState {
|
||||
attackers: string[];
|
||||
/** blocker uid → attacker uid. */
|
||||
blocks: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface DuelResult {
|
||||
winner: Seat | null; // null = draw
|
||||
reason: 'life' | 'library' | 'concede' | 'timeout' | 'turnCap';
|
||||
}
|
||||
|
||||
export interface DuelState {
|
||||
engine: 'duel';
|
||||
rules: DuelRuleset;
|
||||
seed: string;
|
||||
rng: RngState;
|
||||
/** 1-based, counts both players' turns. 0 during mulligans. */
|
||||
turn: number;
|
||||
active: Seat;
|
||||
firstSeat: Seat;
|
||||
phase: Phase;
|
||||
players: [PlayerState, PlayerState];
|
||||
battlefield: Permanent[];
|
||||
combat: CombatState;
|
||||
log: LogEvent[];
|
||||
result: DuelResult | null;
|
||||
/** Increments on every applied action (host polling: unchanged → 204). */
|
||||
version: number;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Actions (atomic; legalActions enumerates them; [] for the seat not to act)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type TargetRef = { kind: 'card'; uid: string } | { kind: 'player'; seat: Seat };
|
||||
|
||||
export type DuelAction =
|
||||
| { type: 'keep' }
|
||||
| { type: 'mulligan' }
|
||||
| { type: 'play'; uid: string; target?: TargetRef }
|
||||
| { type: 'endPhase' } // main → attack
|
||||
| { type: 'toggleAttacker'; uid: string } // attack phase
|
||||
| { type: 'confirmAttack' } // no attackers → end turn
|
||||
| { type: 'block'; blocker: string; attacker: string } // block phase (defender)
|
||||
| { type: 'unblock'; blocker: string }
|
||||
| { type: 'confirmBlocks' } // damage, then end of turn
|
||||
| { type: 'concede' } // any time, either seat
|
||||
| { type: 'timeout' }; // host-only, for the seat that must act
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Log (encyclopedic, per seat via logFor; full log stays in DuelState.log)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Public reference to a card in the log. */
|
||||
export interface CardRef { uid: string; cardId: string; title: string; pageId: number | null }
|
||||
|
||||
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 }
|
||||
/** 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 }
|
||||
| { 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[] }
|
||||
| { 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 }
|
||||
| { 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'] }
|
||||
);
|
||||
|
||||
export type LogKind = LogEvent['kind'];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Views (what one seat may see; bots and UI get only this)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface PermanentView {
|
||||
uid: string;
|
||||
owner: Seat;
|
||||
controller: Seat;
|
||||
card: DuelCard;
|
||||
tapped: boolean;
|
||||
sick: boolean;
|
||||
damage: number;
|
||||
counters: number;
|
||||
attachedTo?: string;
|
||||
/** Current stats after counters, temp buffs, statics and Connected. */
|
||||
power: number;
|
||||
toughness: number;
|
||||
/** Active Connected bonus, if any (for the card face). */
|
||||
connected?: { with: string; tier: ConnectedTier; via: string; bonus: number };
|
||||
}
|
||||
|
||||
export interface SideView {
|
||||
seat: Seat;
|
||||
life: number;
|
||||
citations: number;
|
||||
maxCitations: number;
|
||||
handSize: number;
|
||||
librarySize: number;
|
||||
graveyard: CardInstance[];
|
||||
bankSeconds: number;
|
||||
ready: boolean;
|
||||
mulligansTaken: number;
|
||||
}
|
||||
|
||||
export interface PlayerView {
|
||||
engine: 'duel';
|
||||
seat: Seat;
|
||||
turn: number;
|
||||
active: Seat;
|
||||
phase: Phase;
|
||||
/** Seat that must act now (null when over). */
|
||||
toAct: Seat | null;
|
||||
you: SideView & { hand: CardInstance[] };
|
||||
opponent: SideView;
|
||||
battlefield: PermanentView[];
|
||||
combat: CombatState;
|
||||
result: DuelResult | null;
|
||||
version: number;
|
||||
rules: DuelRuleset;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { DEFAULT_DUEL_RULESET, mergeDuelRuleset, parseDuelRuleset, CARD_TYPES, KEYWORDS } from '../shared/duel/index.ts';
|
||||
import { DEFAULT_RULESET } from '../shared/game/index.ts';
|
||||
|
||||
test('duel default ruleset matches the BRIEF', () => {
|
||||
const rules = parseDuelRuleset({ ...DEFAULT_DUEL_RULESET });
|
||||
assert.equal(rules.deckSize, 40);
|
||||
assert.equal(rules.startingLife, 20);
|
||||
assert.equal(rules.maxCitations, 10);
|
||||
assert.equal(rules.handSize, 7);
|
||||
assert.equal(rules.openingHand, 7);
|
||||
assert.equal(rules.mulligans, 1);
|
||||
assert.equal(rules.libraryEmpty, 'lose');
|
||||
assert.equal(rules.firstPlayerDraws, false);
|
||||
assert.equal(rules.turnSeconds, 60);
|
||||
assert.equal(rules.bankSeconds, 300);
|
||||
assert.equal(rules.turnCap, null);
|
||||
assert.equal(rules.territoryCap, 2);
|
||||
});
|
||||
|
||||
test('duel ruleset merges overrides and rejects unknown keys', () => {
|
||||
assert.equal(mergeDuelRuleset({ deckSize: 20 }).deckSize, 20);
|
||||
assert.equal(mergeDuelRuleset({ turnCap: 30 }).turnCap, 30);
|
||||
assert.throws(() => mergeDuelRuleset({ topicCount: 3 }));
|
||||
assert.throws(() => mergeDuelRuleset({ libraryEmpty: 'shrug' }));
|
||||
assert.throws(() => mergeDuelRuleset({ deckSize: 0 }));
|
||||
assert.throws(() => mergeDuelRuleset([1]));
|
||||
});
|
||||
|
||||
test('Night 1 Edit War rulesets are rejected cleanly', () => {
|
||||
assert.throws(() => parseDuelRuleset(DEFAULT_RULESET));
|
||||
});
|
||||
|
||||
test('card types and keywords are the BRIEF set', () => {
|
||||
assert.deepEqual([...CARD_TYPES], ['Figure', 'Location', 'Event', 'Institution', 'Doctrine']);
|
||||
for (const k of ['Protected', 'Featured', 'Translated', 'Legacy', 'Stub', 'Well-sourced', 'Multilingual', 'Local']) {
|
||||
assert.ok((KEYWORDS as readonly string[]).includes(k), k);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user