forked from WikiDeck/wikideck
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0eb80d23d7 | ||
|
|
4623930e8f | ||
|
|
5cd0ffb0c9 | ||
|
|
79041990ed | ||
|
|
5d5eaa5488 | ||
|
|
4daf87edde | ||
|
|
5365611c4a |
@@ -16,7 +16,7 @@ A 3-node **testnet-only** fixture on poweredge-r350. It is reachable on the LAN
|
||||
- `compose.lan.yaml` also sets, per node:
|
||||
- `WIKIDECK_USER_AGENT`, a Wikimedia-policy UA with a project URL (#19). Without it, Wikipedia returned 429 to our egress and templates failed.
|
||||
- the game-mode env from #22: A = classic and trending, B = draft, C = all three.
|
||||
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-17 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
|
||||
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-16 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
|
||||
- `testnet.sh` has `up`, `mine N [workers]`, `status` and `down`. Run it from the repo root on a checkout of the integration branch. `up` rebuilds the image from that checkout; the ledgers persist in the named volumes.
|
||||
|
||||
Never point this at mainnet or the live `wikideck` namespace.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
# because lobbies are in memory and a restart ends games in progress.
|
||||
# Head detection uses the public Gitea API, which also works where SSH auth isn't available.
|
||||
set -u
|
||||
BRANCH=${BRANCH:-night/2026-11-17}
|
||||
BRANCH=${BRANCH:-night/2026-11-16}
|
||||
API=${API:-https://gitea.eom.dev/api/v1/repos/claude/wikideck}
|
||||
INTERVAL=${INTERVAL:-180}
|
||||
LOG=${LOG:-/tmp/wikideck-night-autodeploy.log}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# 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. Balance levers (data only): `firstPlayerDraws`, and `secondPlayerCitations` (extra Citations on the second player's first turn; default 1 from balance v1, #64).
|
||||
- **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` (default 40 total turns from balance v1, #64; `null` = none): 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.
|
||||
@@ -0,0 +1,908 @@
|
||||
/**
|
||||
* WikiDeck Duel engine (off-chain, pure, deterministic). Spec: docs/game/DUEL_API.md.
|
||||
* No stack, sorcery speed only, atomic actions, clone-on-apply.
|
||||
*/
|
||||
import { Rng } from '../game/rng.ts';
|
||||
import { DEFAULT_DUEL_RULESET, parseDuelRuleset } from './ruleset.ts';
|
||||
import type {
|
||||
CardInstance, CardRef, ConnectedTier, DuelAction, DuelCard, DuelResult, DuelRuleset, DuelState, EffectSpec, EndReason,
|
||||
Keyword, LogEvent, Permanent, PermanentView, PlayerState, PlayerView, Seat, SideView, TargetRef, TargetSpec,
|
||||
} from './types.ts';
|
||||
import { CARD_TYPES, KEYWORDS } from './types.ts';
|
||||
|
||||
type LogBody = LogEvent extends infer E ? (E extends LogEvent ? Omit<E, 'seq' | 'turn'> : never) : never;
|
||||
type Source = Permanent | CardInstance;
|
||||
|
||||
const other = (seat: Seat): Seat => (seat === 0 ? 1 : 0);
|
||||
const pw = (card: DuelCard) => card.power ?? 0;
|
||||
const tg = (card: DuelCard) => card.toughness ?? 0;
|
||||
const CHOSEN: ReadonlySet<TargetSpec> = new Set(['figure', 'figureOrLocation', 'ownFigure', 'opponentFigure', 'anyTarget']);
|
||||
const NO_KIN = new Set(['Q5', 'Q16521']);
|
||||
const MAX_COMBOS = 64;
|
||||
|
||||
function targetOf(e: EffectSpec): TargetSpec {
|
||||
if (e.target) return e.target;
|
||||
switch (e.op) {
|
||||
case 'damage': return 'anyTarget';
|
||||
case 'damageEach': return 'each';
|
||||
case 'pump': return 'self';
|
||||
case 'drain': return 'opponent';
|
||||
case 'attach': return 'ownFigure';
|
||||
case 'fight': return 'opponentFigure';
|
||||
case 'destroy': case 'bounce': case 'tap': return 'opponentFigure';
|
||||
default: return 'controller';
|
||||
}
|
||||
}
|
||||
|
||||
const isEntry = (e: EffectSpec) => e.trigger === 'onPlay' || e.trigger === 'onEnter';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Decks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function validateDeck(rules: DuelRuleset, cards: DuelCard[]): void {
|
||||
if (!Array.isArray(cards)) throw new TypeError('Deck must be an array');
|
||||
if (cards.length !== rules.deckSize) throw new RangeError(`Deck must have exactly ${rules.deckSize} cards (has ${cards.length})`);
|
||||
const ids = new Set<string>();
|
||||
const pages = new Map<number, number>();
|
||||
for (const card of cards) {
|
||||
if (!card || typeof card.cardId !== 'string' || !card.cardId) throw new TypeError('Card needs a cardId');
|
||||
if (card.token) throw new RangeError(`Tokens can't be in decks (${card.cardId})`);
|
||||
if (ids.has(card.cardId)) throw new RangeError(`Duplicate card ${card.cardId}`);
|
||||
ids.add(card.cardId);
|
||||
if (card.pageId !== null) {
|
||||
const n = (pages.get(card.pageId) ?? 0) + 1;
|
||||
if (n > rules.maxCopiesPerPage) throw new RangeError(`More than ${rules.maxCopiesPerPage} copies of page ${card.pageId}`);
|
||||
pages.set(card.pageId, n);
|
||||
}
|
||||
if (!CARD_TYPES.includes(card.type)) throw new RangeError(`Bad card type ${card.type}`);
|
||||
if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 20) throw new RangeError(`Bad cost on ${card.cardId}`);
|
||||
for (const n of [pw(card), tg(card)]) if (!Number.isInteger(n) || n < 0 || n > 50) throw new RangeError(`Bad stats on ${card.cardId}`);
|
||||
if (card.type === 'Figure' && tg(card) < 1) throw new RangeError(`Figure ${card.cardId} needs toughness ≥ 1`);
|
||||
if (!Array.isArray(card.keywords)) throw new TypeError(`Bad keywords on ${card.cardId}`);
|
||||
// Trending is granted by the host at match start (applyLive) and doesn't count toward the limit.
|
||||
if (card.keywords.filter(k => k !== 'Trending').length > rules.maxKeywords) throw new RangeError(`Too many keywords on ${card.cardId}`);
|
||||
for (const k of card.keywords) if (!KEYWORDS.includes(k)) throw new RangeError(`Unknown keyword ${k}`);
|
||||
if (!Array.isArray(card.effects) || card.effects.length > 4) throw new RangeError(`Bad effects on ${card.cardId}`);
|
||||
if (card.territory !== undefined && (!Number.isInteger(card.territory) || card.territory < 0 || card.territory > 5)) throw new RangeError(`Bad territory on ${card.cardId}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Creation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function emptyPlayer(rules: DuelRuleset, library: CardInstance[]): PlayerState {
|
||||
return {
|
||||
life: rules.startingLife, citations: 0, baseCitations: 0, library, hand: [], graveyard: [], mulligansTaken: 0, ready: false,
|
||||
locationsThisTurn: 0, bankSeconds: rules.bankSeconds, timeouts: 0, fatigue: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function createDuel(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string): DuelState {
|
||||
const r = parseDuelRuleset(rules);
|
||||
const rng = Rng.fromSeed(seed);
|
||||
const firstSeat = rng.int(2) as Seat;
|
||||
const players = ([0, 1] as Seat[]).map(seat => {
|
||||
const instances = decks[seat].map((card, i) => ({ uid: `${seat}:${i}`, owner: seat, card: structuredClone(card) }));
|
||||
return emptyPlayer(r, rng.shuffle(instances));
|
||||
}) as [PlayerState, PlayerState];
|
||||
const state: DuelState = {
|
||||
engine: 'duel', rules: r, seed, rng: rng.state, turn: 0, active: firstSeat, firstSeat, phase: 'mulligan',
|
||||
players, battlefield: [], combat: { attackers: [], blocks: {} }, log: [], result: null, version: 0, nextToken: 0, nextEntry: 0,
|
||||
};
|
||||
log(state, { kind: 'start', firstSeat });
|
||||
for (const p of state.players) p.hand = p.library.splice(0, r.openingHand);
|
||||
return state;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Queries
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function toAct(state: DuelState): Seat | null {
|
||||
if (state.result) return null;
|
||||
if (state.phase === 'mulligan') {
|
||||
for (const seat of [0, 1] as Seat[]) if (!state.players[seat].ready) return seat;
|
||||
return null;
|
||||
}
|
||||
return state.phase === 'block' ? other(state.active) : state.active;
|
||||
}
|
||||
|
||||
export const isOver = (state: DuelState) => state.result !== null;
|
||||
export const result = (state: DuelState): DuelResult | null => state.result;
|
||||
export const turnOf = (state: DuelState) => state.turn;
|
||||
|
||||
const find = (state: DuelState, uid: string) => state.battlefield.find(p => p.uid === uid);
|
||||
|
||||
export function maxCitations(state: DuelState, seat: Seat): number {
|
||||
const territory = state.battlefield.filter(p => p.controller === seat && p.card.type === 'Location').reduce((n, p) => n + (p.card.territory ?? 0), 0);
|
||||
return state.players[seat].baseCitations + Math.min(state.rules.territoryCap, territory);
|
||||
}
|
||||
|
||||
/** Connected tier between two cards (DUEL_DESIGN §6), best tier first, limited to rules.connectedTiers. */
|
||||
export function tierBetween(rules: DuelRuleset, a: DuelCard, b: DuelCard): { tier: ConnectedTier; via: string } | null {
|
||||
const ca = a.connect, cb = b.connect;
|
||||
if (!ca || !cb) return null;
|
||||
const on = (t: ConnectedTier) => rules.connectedTiers.includes(t);
|
||||
const linked = (b.pageId !== null && ca.links.includes(b.pageId)) || (a.pageId !== null && cb.links.includes(a.pageId));
|
||||
const cited = (!!cb.qid && !!ca.cites?.includes(cb.qid)) || (!!ca.qid && !!cb.cites?.includes(ca.qid));
|
||||
if (on('Linked') && (linked || cited)) return { tier: 'Linked', via: cited ? 'claim' : 'link' };
|
||||
if (on('Compatriot')) { const c = ca.countries.find(x => cb.countries.includes(x)); if (c !== undefined) return { tier: 'Compatriot', via: `country: ${c}` }; }
|
||||
if (on('Contemporary') && a.type !== b.type) { const c = ca.centuries.find(x => cb.centuries.includes(x)); if (c !== undefined) return { tier: 'Contemporary', via: `century: ${c}` }; }
|
||||
if (on('Kin')) { const c = ca.p31.find(x => !NO_KIN.has(x) && cb.p31.includes(x)); if (c !== undefined) return { tier: 'Kin', via: `instance of: ${c}` }; }
|
||||
return null;
|
||||
}
|
||||
|
||||
function connectionOf(state: DuelState, perm: Permanent): { with: Permanent; tier: ConnectedTier; via: string; bonus: number } | null {
|
||||
if (perm.card.type !== 'Figure' || !perm.card.connect) return null;
|
||||
let best: { with: Permanent; tier: ConnectedTier; via: string; bonus: number } | null = null;
|
||||
for (const mate of state.battlefield) {
|
||||
if (mate.uid === perm.uid || mate.controller !== perm.controller) continue;
|
||||
const t = tierBetween(state.rules, perm.card, mate.card);
|
||||
if (!t) continue;
|
||||
const bonus = t.tier === 'Linked' ? state.rules.linkedBonus : state.rules.connectedBonus;
|
||||
if (!best || bonus > best.bonus) best = { with: mate, tier: t.tier, via: t.via, bonus };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Does a static effect of `src` apply to `perm`? Conditions use printed power (no feedback). */
|
||||
function staticApplies(state: DuelState, src: Permanent, e: EffectSpec, perm: Permanent): boolean {
|
||||
const fig = perm.card.type === 'Figure';
|
||||
const t = targetOf(e);
|
||||
const hit = t === 'attached' ? src.attachedTo === perm.uid
|
||||
: t === 'self' ? src.uid === perm.uid
|
||||
: t === 'ownFigures' ? fig && perm.controller === src.controller
|
||||
: t === 'opponentFigures' ? fig && perm.controller !== src.controller
|
||||
: t === 'each' ? fig || perm.card.type === 'Location' : false;
|
||||
if (!hit) return false;
|
||||
const c = e.condition;
|
||||
if (!c) return true;
|
||||
if (c.maxPower !== undefined && pw(perm.card) > c.maxPower) return false;
|
||||
if (c.samePortal) {
|
||||
const anchorUid = src.card.type === 'Doctrine' ? src.attachedTo : src.uid;
|
||||
const anchor = anchorUid ? find(state, anchorUid) : undefined;
|
||||
if (!anchor || perm.uid === anchor.uid || perm.card.portal !== anchor.card.portal) return false;
|
||||
}
|
||||
if (c.connected && !tierBetween(state.rules, perm.card, src.card)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function statics(state: DuelState, perm: Permanent): { p: number; t: number; grants: Keyword[] } {
|
||||
let p = 0, t = 0;
|
||||
const grants: Keyword[] = [];
|
||||
for (const src of state.battlefield) {
|
||||
for (const e of src.card.effects) {
|
||||
if (e.trigger !== 'static' || !staticApplies(state, src, e, perm)) continue;
|
||||
if (e.op === 'pump') { p += e.power ?? e.amount ?? 0; t += e.toughness ?? e.amount ?? 0; }
|
||||
if (e.grant) grants.push(...e.grant);
|
||||
}
|
||||
}
|
||||
return { p, t, grants };
|
||||
}
|
||||
|
||||
export function keywordsOf(state: DuelState, perm: Permanent): Keyword[] {
|
||||
const out = new Set<Keyword>([...perm.card.keywords, ...perm.permKeywords, ...perm.tempKeywords, ...statics(state, perm).grants]);
|
||||
return KEYWORDS.filter(k => out.has(k));
|
||||
}
|
||||
|
||||
const hasKw = (state: DuelState, perm: Permanent, k: Keyword) => keywordsOf(state, perm).includes(k);
|
||||
|
||||
export function statsOfPermanent(state: DuelState, perm: Permanent): { power: number; toughness: number } {
|
||||
if (perm.card.type === 'Location') {
|
||||
return { power: Math.max(0, perm.tempPower), toughness: tg(perm.card) > 0 ? tg(perm.card) + perm.tempToughness : 0 };
|
||||
}
|
||||
if (perm.card.type !== 'Figure') return { power: 0, toughness: 0 };
|
||||
const s = statics(state, perm);
|
||||
const c = connectionOf(state, perm)?.bonus ?? 0;
|
||||
const kws = new Set([...perm.card.keywords, ...perm.permKeywords, ...perm.tempKeywords, ...s.grants]);
|
||||
let local = 0;
|
||||
if (kws.has('Local') && perm.card.connect?.countries.length) {
|
||||
const mine = perm.card.connect.countries;
|
||||
if (state.battlefield.some(l => l.controller === perm.controller && l.card.type === 'Location' && l.card.connect?.countries.some(x => mine.includes(x)))) local = 1;
|
||||
}
|
||||
const trend = kws.has('Trending') ? state.rules.trendingPower : 0;
|
||||
const extra = perm.counters + c + local;
|
||||
return {
|
||||
power: Math.max(0, pw(perm.card) + extra + perm.permPower + perm.tempPower + s.p + trend),
|
||||
toughness: tg(perm.card) + extra + perm.permToughness + perm.tempToughness + s.t,
|
||||
};
|
||||
}
|
||||
|
||||
export function statsOf(state: DuelState, uid: string): { power: number; toughness: number } {
|
||||
const perm = find(state, uid);
|
||||
if (!perm) throw new RangeError(`No permanent ${uid}`);
|
||||
return statsOfPermanent(state, perm);
|
||||
}
|
||||
|
||||
/** Figures, and Locations with a Garrison, can block and can be destroyed by damage. */
|
||||
const isBody = (perm: Permanent) => perm.card.type === 'Figure' || (perm.card.type === 'Location' && tg(perm.card) > 0);
|
||||
|
||||
function canBlock(state: DuelState, blocker: Permanent, attacker: Permanent): boolean {
|
||||
const ka = keywordsOf(state, attacker);
|
||||
const kb = blocker.card.type === 'Figure' ? keywordsOf(state, blocker) : [];
|
||||
if (ka.includes('Featured') && !kb.some(k => k === 'Featured' || k === 'Translated' || k === 'Multilingual')) return false;
|
||||
if (ka.includes('Multilingual') && kb.includes('Local')) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function candidates(state: DuelState, seat: Seat, card: DuelCard, e: EffectSpec): TargetRef[] {
|
||||
const t = targetOf(e);
|
||||
const out: TargetRef[] = [];
|
||||
const shielded = (p: Permanent) => p.controller !== seat && (card.type === 'Event' || card.type === 'Doctrine') && hasKw(state, p, 'Protected');
|
||||
for (const p of state.battlefield) {
|
||||
const fig = p.card.type === 'Figure';
|
||||
const ok = t === 'figure' ? fig
|
||||
: t === 'figureOrLocation' || t === 'anyTarget' ? fig || (p.card.type === 'Location' && tg(p.card) > 0)
|
||||
: t === 'ownFigure' ? fig && p.controller === seat
|
||||
: t === 'opponentFigure' ? fig && p.controller !== seat : false;
|
||||
if (!ok || shielded(p)) continue;
|
||||
if (e.condition?.maxPower !== undefined && pw(p.card) > e.condition.maxPower) continue;
|
||||
out.push({ kind: 'card', uid: p.uid });
|
||||
}
|
||||
if (t === 'anyTarget') out.push({ kind: 'player', seat: other(seat) }, { kind: 'player', seat });
|
||||
return out;
|
||||
}
|
||||
|
||||
/** All target combinations for playing `card` now (capped), [] if it can't be played, [[]] if it needs none. */
|
||||
function targetCombos(state: DuelState, seat: Seat, card: DuelCard): TargetRef[][] {
|
||||
const chosen = card.effects.filter(e => isEntry(e) && CHOSEN.has(targetOf(e)));
|
||||
if (!chosen.length) return [[]];
|
||||
const lists = chosen.map(e => candidates(state, seat, card, e));
|
||||
const permanent = card.type !== 'Event' && card.type !== 'Doctrine';
|
||||
if (lists.some(l => !l.length)) return permanent ? [[]] : [];
|
||||
let combos: TargetRef[][] = [[]];
|
||||
for (const list of lists) {
|
||||
const next: TargetRef[][] = [];
|
||||
for (const c of combos) for (const t of list) {
|
||||
if (t.kind === 'card' && c.some(x => x.kind === 'card' && x.uid === t.uid)) continue;
|
||||
if (next.length < MAX_COMBOS) next.push([...c, t]);
|
||||
}
|
||||
combos = next;
|
||||
}
|
||||
return combos.length ? combos : permanent ? [[]] : [];
|
||||
}
|
||||
|
||||
export function legalActions(state: DuelState, seat: Seat): DuelAction[] {
|
||||
if (toAct(state) !== seat) return [];
|
||||
const p = state.players[seat];
|
||||
switch (state.phase) {
|
||||
case 'mulligan':
|
||||
return p.mulligansTaken < state.rules.mulligans ? [{ type: 'keep' }, { type: 'mulligan' }] : [{ type: 'keep' }];
|
||||
case 'main': {
|
||||
const out: DuelAction[] = [];
|
||||
for (const inst of p.hand) {
|
||||
if (inst.card.cost > p.citations) continue;
|
||||
if (inst.card.type === 'Location' && p.locationsThisTurn >= state.rules.locationsPerTurn) continue;
|
||||
for (const targets of targetCombos(state, seat, inst.card)) {
|
||||
out.push(targets.length ? { type: 'play', uid: inst.uid, targets } : { type: 'play', uid: inst.uid });
|
||||
}
|
||||
}
|
||||
out.push({ type: 'endPhase' });
|
||||
return out;
|
||||
}
|
||||
case 'attack': {
|
||||
const out: DuelAction[] = [];
|
||||
for (const perm of state.battlefield) {
|
||||
if (perm.controller !== seat || perm.card.type !== 'Figure' || perm.tapped || state.combat.attackers.includes(perm.uid)) continue;
|
||||
if (perm.sick && !hasKw(state, perm, 'Trending')) continue;
|
||||
out.push({ type: 'toggleAttacker', uid: perm.uid });
|
||||
}
|
||||
out.push({ type: 'confirmAttack' });
|
||||
return out;
|
||||
}
|
||||
case 'block':
|
||||
return [...blockOptions(state), { type: 'confirmBlocks' }];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function blockOptions(state: DuelState): DuelAction[] {
|
||||
const defender = other(state.active);
|
||||
const out: DuelAction[] = [];
|
||||
const blocked = new Set(Object.values(state.combat.blocks));
|
||||
for (const b of state.battlefield) {
|
||||
if (b.controller !== defender || b.tapped || !isBody(b) || state.combat.blocks[b.uid]) continue;
|
||||
for (const aUid of state.combat.attackers) {
|
||||
if (blocked.has(aUid)) continue;
|
||||
const a = find(state, aUid);
|
||||
if (a && canBlock(state, b, a)) out.push({ type: 'block', blocker: b.uid, attacker: aUid });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mutation helpers (operate on a private clone)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function log(state: DuelState, body: LogBody): void {
|
||||
state.log.push({ seq: state.log.length, turn: state.turn, ...body } as LogEvent);
|
||||
}
|
||||
|
||||
function ref(state: DuelState, inst: Source): CardRef {
|
||||
const out: CardRef = { uid: inst.uid, cardId: inst.card.cardId, title: inst.card.title, pageId: inst.card.pageId, type: inst.card.type };
|
||||
const perm = find(state, inst.uid);
|
||||
if (perm && isBody(perm)) Object.assign(out, statsOfPermanent(state, perm));
|
||||
return out;
|
||||
}
|
||||
|
||||
const life = (state: DuelState): [number, number] => [state.players[0].life, state.players[1].life];
|
||||
|
||||
function finish(state: DuelState, winner: Seat | null, reason: EndReason): void {
|
||||
if (state.result) return;
|
||||
state.result = { winner, reason };
|
||||
state.phase = 'over';
|
||||
log(state, { kind: 'gameOver', winner, reason, life: life(state) });
|
||||
}
|
||||
|
||||
function draw(state: DuelState, seat: Seat, n: number): void {
|
||||
const p = state.players[seat];
|
||||
for (let i = 0; i < n && !state.result; i++) {
|
||||
if (!p.library.length) {
|
||||
const mode = state.rules.libraryEmpty;
|
||||
if (mode === 'reshuffle' && p.graveyard.length) {
|
||||
const rng = new Rng(state.rng);
|
||||
p.library = rng.shuffle(p.graveyard);
|
||||
p.graveyard = [];
|
||||
state.rng = rng.state;
|
||||
} else if (mode === 'fatigue') {
|
||||
p.fatigue += 1;
|
||||
log(state, { kind: 'fatigue', seat, amount: p.fatigue });
|
||||
loseLife(state, seat, p.fatigue, null, false);
|
||||
continue;
|
||||
} else {
|
||||
finish(state, other(seat), 'library');
|
||||
return;
|
||||
}
|
||||
}
|
||||
const inst = p.library.shift()!;
|
||||
p.hand.push(inst);
|
||||
log(state, { kind: 'draw', seat, card: ref(state, inst) });
|
||||
}
|
||||
}
|
||||
|
||||
function loseLife(state: DuelState, seat: Seat, amount: number, source: Source | null, combat: boolean): void {
|
||||
if (amount <= 0) return;
|
||||
const p = state.players[seat];
|
||||
p.life -= amount;
|
||||
log(state, { kind: 'playerDamage', source: source ? ref(state, source) : null, seat, amount, life: p.life, combat });
|
||||
}
|
||||
|
||||
function gainLife(state: DuelState, seat: Seat, amount: number, source: Source): void {
|
||||
if (amount <= 0) return;
|
||||
const p = state.players[seat];
|
||||
p.life += amount;
|
||||
log(state, { kind: 'lifeGain', source: ref(state, source), seat, amount, life: p.life });
|
||||
}
|
||||
|
||||
/** Returns damage actually dealt. */
|
||||
function dealDamage(state: DuelState, source: Source, target: TargetRef, amount: number, combat: boolean): number {
|
||||
if (amount <= 0) return 0;
|
||||
if (target.kind === 'player') { loseLife(state, target.seat, amount, source, combat); return amount; }
|
||||
const perm = find(state, target.uid);
|
||||
if (!perm || !isBody(perm)) return 0;
|
||||
let dmg = amount;
|
||||
if (!perm.shielded && hasKw(state, perm, 'Well-sourced')) { perm.shielded = true; dmg -= 1; }
|
||||
if (dmg <= 0) return 0;
|
||||
perm.damage += dmg;
|
||||
log(state, { kind: combat ? 'combatDamage' : 'effectDamage', source: ref(state, source), target: ref(state, perm), amount: dmg });
|
||||
return dmg;
|
||||
}
|
||||
|
||||
function leave(state: DuelState, uid: string): Permanent | null {
|
||||
const i = state.battlefield.findIndex(p => p.uid === uid);
|
||||
if (i < 0) return null;
|
||||
const [perm] = state.battlefield.splice(i, 1);
|
||||
delete state.combat.blocks[uid];
|
||||
for (const [b, a] of Object.entries(state.combat.blocks)) if (a === uid) delete state.combat.blocks[b];
|
||||
state.combat.attackers = state.combat.attackers.filter(a => a !== uid);
|
||||
return perm;
|
||||
}
|
||||
|
||||
const toInstance = (perm: Permanent): CardInstance => ({ uid: perm.uid, owner: perm.owner, card: perm.card });
|
||||
|
||||
/** Destroy a set of permanents at once, then fire their triggers (active player's first, then entry order). */
|
||||
function destroyAll(state: DuelState, uids: string[]): void {
|
||||
const gone: Permanent[] = [];
|
||||
for (const uid of uids) {
|
||||
const perm = find(state, uid);
|
||||
if (!perm) continue;
|
||||
const card = ref(state, perm);
|
||||
leave(state, uid);
|
||||
if (!perm.card.token) state.players[perm.owner].graveyard.push(toInstance(perm));
|
||||
log(state, { kind: 'destroyed', card, owner: perm.owner });
|
||||
gone.push(perm);
|
||||
}
|
||||
gone.sort((a, b) => Number(a.controller !== state.active) - Number(b.controller !== state.active) || a.entered - b.entered);
|
||||
for (const perm of gone) {
|
||||
if (state.result) return;
|
||||
for (const e of perm.card.effects) if (e.trigger === 'onDestroyed') resolveEffect(state, perm, perm.controller, e, undefined, undefined);
|
||||
if (perm.card.keywords.includes('Legacy') || perm.permKeywords.includes('Legacy')) draw(state, perm.controller, 1);
|
||||
}
|
||||
}
|
||||
|
||||
function bounce(state: DuelState, uid: string): void {
|
||||
const perm = find(state, uid);
|
||||
if (!perm) return;
|
||||
const card = ref(state, perm);
|
||||
leave(state, uid);
|
||||
if (!perm.card.token) state.players[perm.owner].hand.push(toInstance(perm));
|
||||
log(state, { kind: 'bounced', card, owner: perm.owner });
|
||||
}
|
||||
|
||||
/** State-based checks to a fixpoint: lethal damage, orphaned Doctrines, life totals; then Connected logging. */
|
||||
function settle(state: DuelState): void {
|
||||
for (let guard = 0; guard < 100 && !state.result; guard++) {
|
||||
const dead = state.battlefield.filter(p => {
|
||||
if (p.card.type === 'Doctrine') return !p.attachedTo || !find(state, p.attachedTo);
|
||||
if (!isBody(p)) return false;
|
||||
const { toughness } = statsOfPermanent(state, p);
|
||||
return toughness <= 0 || p.damage >= toughness;
|
||||
}).map(p => p.uid);
|
||||
if (!dead.length) break;
|
||||
destroyAll(state, dead);
|
||||
}
|
||||
if (state.result) return;
|
||||
const lost = ([0, 1] as Seat[]).filter(s => state.players[s].life <= 0);
|
||||
if (lost.length === 2) finish(state, null, 'life');
|
||||
else if (lost.length === 1) finish(state, other(lost[0]), 'life');
|
||||
if (!state.result) logConnections(state);
|
||||
}
|
||||
|
||||
function logConnections(state: DuelState): void {
|
||||
for (const perm of state.battlefield) {
|
||||
if (perm.connectedLogged) continue;
|
||||
const c = connectionOf(state, perm);
|
||||
if (!c) continue;
|
||||
perm.connectedLogged = true;
|
||||
log(state, { kind: 'connected', seat: perm.controller, card: ref(state, perm), with: ref(state, c.with), tier: c.tier, via: c.via, bonus: c.bonus });
|
||||
}
|
||||
}
|
||||
|
||||
/** Rivalry (log only): when a card enters, note its best Connected tie to an opposing permanent, once. */
|
||||
function logRivalry(state: DuelState, perm: Permanent): void {
|
||||
let best: { with: Permanent; tier: ConnectedTier; via: string } | null = null;
|
||||
for (const o of state.battlefield) {
|
||||
if (o.controller === perm.controller) continue;
|
||||
const t = tierBetween(state.rules, perm.card, o.card);
|
||||
if (t && (!best || state.rules.connectedTiers.indexOf(t.tier) < state.rules.connectedTiers.indexOf(best.tier))) best = { with: o, ...t };
|
||||
}
|
||||
if (best) log(state, { kind: 'rivalry', card: ref(state, perm), with: ref(state, best.with), tier: best.tier, via: best.via });
|
||||
}
|
||||
|
||||
function autoTargets(state: DuelState, source: Source, seat: Seat, t: TargetSpec): TargetRef[] {
|
||||
const cards = (pred: (p: Permanent) => boolean) => state.battlefield.filter(pred).map(p => ({ kind: 'card', uid: p.uid }) as TargetRef);
|
||||
switch (t) {
|
||||
case 'controller': return [{ kind: 'player', seat }];
|
||||
case 'opponent': return [{ kind: 'player', seat: other(seat) }];
|
||||
case 'self': return find(state, source.uid) ? [{ kind: 'card', uid: source.uid }] : [];
|
||||
case 'attached': {
|
||||
const at = find(state, source.uid)?.attachedTo;
|
||||
return at && find(state, at) ? [{ kind: 'card', uid: at }] : [];
|
||||
}
|
||||
case 'each': return cards(p => p.card.type === 'Figure' || p.card.type === 'Location');
|
||||
case 'ownFigures': return cards(p => p.card.type === 'Figure' && p.controller === seat);
|
||||
case 'opponentFigures': return cards(p => p.card.type === 'Figure' && p.controller !== seat);
|
||||
default: return [];
|
||||
}
|
||||
}
|
||||
|
||||
function makeToken(state: DuelState, seat: Seat, source: Source, e: EffectSpec): void {
|
||||
const spec = e.token;
|
||||
if (!spec) return;
|
||||
const n = e.amount ?? 1;
|
||||
for (let i = 0; i < n; i++) {
|
||||
if (e.condition?.maxTokens !== undefined) {
|
||||
const count = state.battlefield.filter(p => p.controller === seat && p.card.token).length;
|
||||
if (count >= e.condition.maxTokens) return;
|
||||
}
|
||||
const id = state.nextToken++;
|
||||
const card: DuelCard = {
|
||||
cardId: `token:${id}`, pageId: null, title: spec.name, type: 'Figure', portal: spec.portal, cost: 0,
|
||||
power: spec.power, toughness: spec.toughness, keywords: [], effects: [], rulesText: '', flavor: '', token: true,
|
||||
};
|
||||
const perm = enter(state, { uid: `t:${id}`, owner: seat, card }, seat);
|
||||
log(state, { kind: 'tokenCreated', seat, card: ref(state, perm), source: ref(state, source) });
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve one effect. `chosen` is this effect's target (chosen effects); `prev` the previous chosen target (fight). */
|
||||
function resolveEffect(state: DuelState, source: Source, seat: Seat, e: EffectSpec, chosen: TargetRef | undefined, prev: TargetRef | undefined): void {
|
||||
if (state.result || e.trigger === 'static') return;
|
||||
const t = targetOf(e);
|
||||
let targets: TargetRef[];
|
||||
if (CHOSEN.has(t)) {
|
||||
if (!chosen) return; // fizzles (no target, or chosen targets in automatic triggers)
|
||||
const still = chosen.kind === 'player' ? t === 'anyTarget'
|
||||
: candidates(state, seat, source.card, e).some(x => x.kind === 'card' && x.uid === chosen.uid);
|
||||
if (!still) return;
|
||||
targets = [chosen];
|
||||
} else {
|
||||
targets = autoTargets(state, source, seat, t);
|
||||
}
|
||||
const needs = !['draw', 'gainLife', 'createToken'].includes(e.op);
|
||||
if (needs && !targets.length) return;
|
||||
log(state, { kind: 'effect', seat, source: ref(state, source), op: e.op, ...(e.template ? { template: e.template } : {}), targets });
|
||||
const amount = e.amount ?? 0;
|
||||
const permOf = (x: TargetRef) => (x.kind === 'card' ? find(state, x.uid) : undefined);
|
||||
switch (e.op) {
|
||||
case 'damage': case 'damageEach':
|
||||
for (const x of targets) dealDamage(state, source, x, amount, false);
|
||||
break;
|
||||
case 'createToken': makeToken(state, seat, source, e); break;
|
||||
case 'pump': {
|
||||
const p = e.power ?? amount, q = e.toughness ?? amount;
|
||||
for (const x of targets) {
|
||||
const perm = permOf(x);
|
||||
if (!perm) continue;
|
||||
if (e.duration === 'permanent') { perm.permPower += p; perm.permToughness += q; if (e.grant) perm.permKeywords.push(...e.grant); }
|
||||
else { perm.tempPower += p; perm.tempToughness += q; if (e.grant) perm.tempKeywords.push(...e.grant); }
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'fight': {
|
||||
const a = prev?.kind === 'card' ? find(state, prev.uid) : find(state, source.uid);
|
||||
const b = permOf(targets[0]);
|
||||
if (!a || !b || a.uid === b.uid) break;
|
||||
const [ap, bp] = [statsOfPermanent(state, a).power, statsOfPermanent(state, b).power];
|
||||
dealDamage(state, a, { kind: 'card', uid: b.uid }, ap, false);
|
||||
dealDamage(state, b, { kind: 'card', uid: a.uid }, bp, false);
|
||||
break;
|
||||
}
|
||||
case 'draw': draw(state, t === 'opponent' ? other(seat) : seat, e.amount ?? 1); break;
|
||||
case 'attach': {
|
||||
const perm = find(state, source.uid);
|
||||
const to = permOf(targets[0]);
|
||||
if (perm && to) { perm.attachedTo = to.uid; log(state, { kind: 'adopt', seat, card: ref(state, perm), to: ref(state, to) }); }
|
||||
break;
|
||||
}
|
||||
case 'gainLife': gainLife(state, seat, amount, source); break;
|
||||
case 'drain':
|
||||
for (const x of targets) {
|
||||
const victim = x.kind === 'player' ? x.seat : permOf(x)?.controller;
|
||||
if (victim === undefined) continue;
|
||||
loseLife(state, victim, amount, source, false);
|
||||
if (victim !== seat) gainLife(state, seat, amount, source);
|
||||
}
|
||||
break;
|
||||
case 'destroy': destroyAll(state, targets.filter(x => x.kind === 'card').map(x => (x as { uid: string }).uid)); break;
|
||||
case 'bounce': for (const x of targets) if (x.kind === 'card') bounce(state, x.uid); break;
|
||||
case 'tap': for (const x of targets) { const perm = permOf(x); if (perm) perm.tapped = true; } break;
|
||||
}
|
||||
}
|
||||
|
||||
function enter(state: DuelState, inst: CardInstance, seat: Seat): Permanent {
|
||||
const perm: Permanent = {
|
||||
...inst, controller: seat, tapped: false, sick: true, damage: 0, counters: 0, permPower: 0, permToughness: 0,
|
||||
tempPower: 0, tempToughness: 0, tempKeywords: [], permKeywords: [], shielded: false, entered: state.nextEntry++, connectedLogged: false,
|
||||
};
|
||||
state.battlefield.push(perm);
|
||||
return perm;
|
||||
}
|
||||
|
||||
/** Run a card's entry effects, feeding chosen targets in order. */
|
||||
function runEntry(state: DuelState, source: Source, seat: Seat, targets: TargetRef[]): void {
|
||||
let i = 0;
|
||||
let prev: TargetRef | undefined;
|
||||
for (const e of source.card.effects) {
|
||||
if (!isEntry(e) || state.result) continue;
|
||||
if (CHOSEN.has(targetOf(e))) {
|
||||
const chosen = targets[i++];
|
||||
resolveEffect(state, source, seat, e, chosen, prev);
|
||||
prev = chosen;
|
||||
} else {
|
||||
resolveEffect(state, source, seat, e, undefined, prev);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Turn structure
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function totalPower(state: DuelState, seat: Seat): number {
|
||||
return state.battlefield.filter(p => p.controller === seat && p.card.type === 'Figure').reduce((n, p) => n + statsOfPermanent(state, p).power, 0);
|
||||
}
|
||||
|
||||
function startTurn(state: DuelState, seat: Seat): void {
|
||||
if (state.rules.turnCap !== null && state.turn >= state.rules.turnCap) {
|
||||
const [a, b] = life(state);
|
||||
const [pa, pb] = [totalPower(state, 0), totalPower(state, 1)];
|
||||
const winner: Seat = a !== b ? (a > b ? 0 : 1) : pa !== pb ? (pa > pb ? 0 : 1) : other(state.firstSeat);
|
||||
finish(state, winner, 'turnCap');
|
||||
return;
|
||||
}
|
||||
state.turn += 1;
|
||||
state.active = seat;
|
||||
state.phase = 'main';
|
||||
state.combat = { attackers: [], blocks: {} };
|
||||
const p = state.players[seat];
|
||||
p.locationsThisTurn = 0;
|
||||
p.baseCitations = Math.min(state.rules.maxCitations, p.baseCitations + state.rules.citationsPerTurn);
|
||||
p.citations = maxCitations(state, seat);
|
||||
if (state.turn === 2 && seat !== state.firstSeat) p.citations += state.rules.secondPlayerCitations;
|
||||
for (const perm of state.battlefield) {
|
||||
perm.shielded = false;
|
||||
if (perm.controller === seat) { perm.tapped = false; perm.sick = false; }
|
||||
}
|
||||
log(state, { kind: 'turnStart', seat, citations: p.citations, life: life(state) });
|
||||
const mine = state.battlefield.filter(x => x.controller === seat).sort((a, b) => a.entered - b.entered);
|
||||
for (const perm of mine) {
|
||||
if (!find(state, perm.uid) || state.result) continue;
|
||||
if (perm.card.keywords.includes('Stub') && perm.counters < state.rules.stubMax) perm.counters += 1;
|
||||
for (const e of perm.card.effects) if (e.trigger === 'startOfTurn' && find(state, perm.uid)) resolveEffect(state, perm, seat, e, undefined, undefined);
|
||||
}
|
||||
settle(state);
|
||||
if (state.result) return;
|
||||
if (!(state.turn === 1 && !state.rules.firstPlayerDraws)) draw(state, seat, 1);
|
||||
settle(state);
|
||||
}
|
||||
|
||||
function endTurn(state: DuelState): void {
|
||||
for (const perm of state.battlefield) { perm.damage = 0; perm.tempPower = 0; perm.tempToughness = 0; perm.tempKeywords = []; }
|
||||
state.combat = { attackers: [], blocks: {} };
|
||||
const seat = state.active;
|
||||
const p = state.players[seat];
|
||||
while (p.hand.length > state.rules.handSize) {
|
||||
let worst = p.hand.length - 1;
|
||||
for (let i = p.hand.length - 1; i >= 0; i--) if (p.hand[i].card.cost > p.hand[worst].card.cost) worst = i;
|
||||
const [inst] = p.hand.splice(worst, 1);
|
||||
p.graveyard.push(inst);
|
||||
log(state, { kind: 'discard', seat, card: ref(state, inst) });
|
||||
}
|
||||
settle(state);
|
||||
if (!state.result) startTurn(state, other(seat));
|
||||
}
|
||||
|
||||
function play(state: DuelState, seat: Seat, uid: string, targets: TargetRef[]): void {
|
||||
const p = state.players[seat];
|
||||
const [inst] = p.hand.splice(p.hand.findIndex(c => c.uid === uid), 1);
|
||||
p.citations -= inst.card.cost;
|
||||
if (inst.card.type === 'Event') {
|
||||
log(state, { kind: 'cast', seat, card: ref(state, inst), targets });
|
||||
runEntry(state, inst, seat, targets);
|
||||
p.graveyard.push(inst);
|
||||
settle(state);
|
||||
return;
|
||||
}
|
||||
if (inst.card.type === 'Location') p.locationsThisTurn += 1;
|
||||
const perm = enter(state, inst, seat);
|
||||
if (inst.card.type !== 'Doctrine') log(state, { kind: 'deploy', seat, card: ref(state, perm) });
|
||||
logRivalry(state, perm);
|
||||
runEntry(state, perm, seat, targets);
|
||||
settle(state);
|
||||
}
|
||||
|
||||
function confirmAttack(state: DuelState): void {
|
||||
const seat = state.active;
|
||||
if (!state.combat.attackers.length) { endTurn(state); return; }
|
||||
const attackers = state.combat.attackers.map(uid => find(state, uid)).filter((x): x is Permanent => !!x);
|
||||
for (const a of attackers) a.tapped = true;
|
||||
log(state, { kind: 'attack', seat, attackers: attackers.map(a => ref(state, a)) });
|
||||
for (const a of attackers) for (const e of a.card.effects) if (e.trigger === 'onAttack' && find(state, a.uid)) resolveEffect(state, a, seat, e, undefined, undefined);
|
||||
settle(state);
|
||||
if (state.result) return;
|
||||
if (!state.combat.attackers.length) { endTurn(state); return; }
|
||||
state.phase = 'block';
|
||||
if (!blockOptions(state).length) resolveCombat(state);
|
||||
}
|
||||
|
||||
function resolveCombat(state: DuelState): void {
|
||||
const defender = other(state.active);
|
||||
const pairs = Object.entries(state.combat.blocks)
|
||||
.map(([b, a]) => ({ blocker: find(state, b), attacker: find(state, a) }))
|
||||
.filter((x): x is { blocker: Permanent; attacker: Permanent } => !!x.blocker && !!x.attacker);
|
||||
if (pairs.length) log(state, { kind: 'block', seat: defender, blocks: pairs.map(x => ({ blocker: ref(state, x.blocker), attacker: ref(state, x.attacker) })) });
|
||||
// Simultaneous: compute every amount first, then apply.
|
||||
const hits: { source: Permanent; target: TargetRef; amount: number }[] = [];
|
||||
const blockerOf = new Map(pairs.map(x => [x.attacker.uid, x.blocker]));
|
||||
for (const uid of state.combat.attackers) {
|
||||
const a = find(state, uid);
|
||||
if (!a) continue;
|
||||
const ap = statsOfPermanent(state, a).power;
|
||||
const b = blockerOf.get(uid);
|
||||
if (b) {
|
||||
hits.push({ source: a, target: { kind: 'card', uid: b.uid }, amount: ap });
|
||||
hits.push({ source: b, target: { kind: 'card', uid: a.uid }, amount: statsOfPermanent(state, b).power });
|
||||
} else {
|
||||
hits.push({ source: a, target: { kind: 'player', seat: defender }, amount: ap });
|
||||
}
|
||||
}
|
||||
const toPlayer: Permanent[] = [];
|
||||
for (const h of hits) if (dealDamage(state, h.source, h.target, h.amount, true) > 0 && h.target.kind === 'player') toPlayer.push(h.source);
|
||||
for (const a of toPlayer) {
|
||||
for (const e of a.card.effects) if (e.trigger === 'onCombatDamageToPlayer') resolveEffect(state, a, a.controller, e, undefined, undefined);
|
||||
for (const d of state.battlefield.filter(x => x.card.type === 'Doctrine' && x.attachedTo === a.uid)) {
|
||||
for (const e of d.card.effects) if (e.trigger === 'onCombatDamageToPlayer') resolveEffect(state, d, d.controller, e, undefined, undefined);
|
||||
}
|
||||
}
|
||||
settle(state);
|
||||
if (!state.result) endTurn(state);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// applyAction
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Structural clone for clone-on-apply. DuelCards, CardInstances, log events and the
|
||||
* ruleset are never mutated after creation, so they are shared between states;
|
||||
* Permanents, players and combat are copied. (structuredClone was 85% of runtime.)
|
||||
*/
|
||||
function cloneState(s: DuelState): DuelState {
|
||||
const player = (p: PlayerState): PlayerState => ({ ...p, library: p.library.slice(), hand: p.hand.slice(), graveyard: p.graveyard.slice() });
|
||||
return {
|
||||
...s,
|
||||
players: [player(s.players[0]), player(s.players[1])],
|
||||
battlefield: s.battlefield.map(p => ({ ...p, tempKeywords: p.tempKeywords.slice(), permKeywords: p.permKeywords.slice() })),
|
||||
combat: { attackers: s.combat.attackers.slice(), blocks: { ...s.combat.blocks } },
|
||||
log: s.log.slice(),
|
||||
result: s.result ? { ...s.result } : null,
|
||||
};
|
||||
}
|
||||
|
||||
function normalize(action: DuelAction): DuelAction {
|
||||
// Canonical key order so deep-equal against legalActions is stable.
|
||||
switch (action.type) {
|
||||
case 'play': {
|
||||
const targets = (action.targets ?? []).map(t => (t.kind === 'card' ? { kind: 'card' as const, uid: t.uid } : { kind: 'player' as const, seat: t.seat }));
|
||||
return targets.length ? { type: 'play', uid: action.uid, targets } : { type: 'play', uid: action.uid };
|
||||
}
|
||||
case 'toggleAttacker': return { type: 'toggleAttacker', uid: action.uid };
|
||||
case 'block': return { type: 'block', blocker: action.blocker, attacker: action.attacker };
|
||||
default: return { type: action.type } as DuelAction;
|
||||
}
|
||||
}
|
||||
|
||||
export function applyAction(input: DuelState, seat: Seat, action: DuelAction): DuelState {
|
||||
if (input.result) throw new Error('Match is over');
|
||||
if (seat !== 0 && seat !== 1) throw new RangeError('Bad seat');
|
||||
if (!action || typeof action !== 'object' || typeof (action as { type?: unknown }).type !== 'string') throw new TypeError('Bad action');
|
||||
if (action.type === 'concede') {
|
||||
const state = cloneState(input);
|
||||
state.version += 1;
|
||||
log(state, { kind: 'concede', seat });
|
||||
finish(state, other(seat), 'concede');
|
||||
return state;
|
||||
}
|
||||
if (toAct(input) !== seat) throw new Error('Not your turn to act');
|
||||
if (action.type === 'timeout') {
|
||||
const state = cloneState(input);
|
||||
state.version += 1;
|
||||
log(state, { kind: 'timeout', seat });
|
||||
const p = state.players[seat];
|
||||
p.timeouts += 1;
|
||||
if (p.timeouts >= state.rules.timeoutsToConcede) { finish(state, other(seat), 'timeout'); return state; }
|
||||
switch (state.phase) {
|
||||
case 'mulligan': keep(state, seat); break;
|
||||
case 'main': case 'attack': state.combat.attackers = []; endTurn(state); break;
|
||||
case 'block': resolveCombat(state); break;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
const a = normalize(action);
|
||||
const key = JSON.stringify(a);
|
||||
if (!legalActions(input, seat).some(x => JSON.stringify(x) === key)) throw new Error(`Illegal action ${JSON.stringify(action)}`);
|
||||
const state = cloneState(input);
|
||||
state.version += 1;
|
||||
state.players[seat].timeouts = 0;
|
||||
switch (a.type) {
|
||||
case 'keep': keep(state, seat); break;
|
||||
case 'mulligan': mulligan(state, seat); break;
|
||||
case 'play': play(state, seat, a.uid, a.targets ?? []); break;
|
||||
case 'endPhase': state.phase = 'attack'; break;
|
||||
case 'toggleAttacker': state.combat.attackers.push(a.uid); break;
|
||||
case 'confirmAttack': confirmAttack(state); break;
|
||||
case 'block': state.combat.blocks[a.blocker] = a.attacker; break;
|
||||
case 'confirmBlocks': resolveCombat(state); break;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
function keep(state: DuelState, seat: Seat): void {
|
||||
const p = state.players[seat];
|
||||
for (let i = 0; i < p.mulligansTaken && p.hand.length; i++) p.library.push(p.hand.pop()!);
|
||||
p.ready = true;
|
||||
log(state, { kind: 'keep', seat, handSize: p.hand.length });
|
||||
if (state.players[0].ready && state.players[1].ready) startTurn(state, state.firstSeat);
|
||||
}
|
||||
|
||||
function mulligan(state: DuelState, seat: Seat): void {
|
||||
const p = state.players[seat];
|
||||
const rng = new Rng(state.rng);
|
||||
p.library = rng.shuffle([...p.library, ...p.hand]);
|
||||
state.rng = rng.state;
|
||||
p.hand = p.library.splice(0, state.rules.openingHand);
|
||||
p.mulligansTaken += 1;
|
||||
log(state, { kind: 'mulligan', seat });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Views, log, replay, serialisation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function side(state: DuelState, seat: Seat): SideView {
|
||||
const p = state.players[seat];
|
||||
return {
|
||||
seat, life: p.life, citations: p.citations, maxCitations: maxCitations(state, seat), handSize: p.hand.length,
|
||||
librarySize: p.library.length, graveyard: structuredClone(p.graveyard), bankSeconds: p.bankSeconds, ready: p.ready, mulligansTaken: p.mulligansTaken,
|
||||
};
|
||||
}
|
||||
|
||||
export function viewFor(state: DuelState, seat: Seat): PlayerView {
|
||||
const battlefield: PermanentView[] = state.battlefield.map(perm => {
|
||||
const { power, toughness } = statsOfPermanent(state, perm);
|
||||
const c = connectionOf(state, perm);
|
||||
return {
|
||||
uid: perm.uid, owner: perm.owner, controller: perm.controller, card: structuredClone(perm.card), tapped: perm.tapped, sick: perm.sick,
|
||||
damage: perm.damage, counters: perm.counters, ...(perm.attachedTo ? { attachedTo: perm.attachedTo } : {}), power, toughness,
|
||||
keywords: keywordsOf(state, perm), ...(c ? { connected: { with: c.with.uid, tier: c.tier, via: c.via, bonus: c.bonus } } : {}),
|
||||
};
|
||||
});
|
||||
return {
|
||||
engine: 'duel', seat, turn: state.turn, active: state.active, phase: state.phase, toAct: toAct(state),
|
||||
you: { ...side(state, seat), hand: structuredClone(state.players[seat].hand) },
|
||||
opponent: side(state, other(seat)),
|
||||
battlefield, combat: structuredClone(state.combat), result: state.result, version: state.version, rules: structuredClone(state.rules),
|
||||
};
|
||||
}
|
||||
|
||||
export function logFor(state: DuelState, seat: Seat): LogEvent[] {
|
||||
return state.log.map(e => {
|
||||
if (e.kind === 'draw' && e.seat !== seat) return { seq: e.seq, turn: e.turn, kind: 'draw', seat: e.seat } as LogEvent;
|
||||
return structuredClone(e);
|
||||
});
|
||||
}
|
||||
|
||||
export function replay(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string, actions: { seat: Seat; action: DuelAction }[]): DuelState {
|
||||
let state = createDuel(rules, decks, seed);
|
||||
for (const { seat, action } of actions) state = applyAction(state, seat, action);
|
||||
return state;
|
||||
}
|
||||
|
||||
export const serialize = (state: DuelState): string => JSON.stringify(state);
|
||||
export function deserialize(text: string): DuelState {
|
||||
const value = JSON.parse(text) as DuelState;
|
||||
if (!value || value.engine !== 'duel') throw new TypeError('Not a duel state');
|
||||
return value;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Host binding: structurally an EnginePort<DuelRuleset, DuelCard, DuelState, DuelAction>
|
||||
// (server/game/engine-port.ts). shared/ must not import server/, so host-pvp types it there.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const duelEnginePort = {
|
||||
defaultRuleset: DEFAULT_DUEL_RULESET,
|
||||
parseRuleset: (value: unknown) => parseDuelRuleset(value),
|
||||
deckSize: (rules: DuelRuleset) => rules.deckSize,
|
||||
starterDeck(_rules?: DuelRuleset, _seed?: string): DuelCard[] { throw new Error('Duel has no starter decks: every card must be owned (BRIEF decision 2)'); },
|
||||
previewPool(_rules?: DuelRuleset, _seed?: string, _size?: number): DuelCard[] { throw new Error('Duel draft pools come from both players’ collections, not previews'); },
|
||||
validateDeck,
|
||||
cardPower: (card: DuelCard) => pw(card),
|
||||
withPower: (card: DuelCard, power: number): DuelCard => ({ ...card, power: Math.max(0, Math.round(power)) }),
|
||||
cardPageId: (card: DuelCard) => card.pageId,
|
||||
cardSummary: (card: DuelCard) => ({
|
||||
cardId: card.cardId, pageId: card.pageId, title: card.title, type: card.type, portal: card.portal, cost: card.cost,
|
||||
power: card.power, toughness: card.toughness, keywords: card.keywords, rulesText: card.rulesText,
|
||||
}),
|
||||
createMatch: (rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string) => createDuel(rules, decks, seed),
|
||||
legalActions,
|
||||
applyAction,
|
||||
concedeAction: (_seat: Seat): DuelAction => ({ type: 'concede' }),
|
||||
timeoutAction: (_seat: Seat): DuelAction => ({ type: 'timeout' }),
|
||||
turnSeconds: (rules: DuelRuleset) => rules.turnSeconds,
|
||||
turnOf,
|
||||
/** Trending mode (DUEL_DESIGN §4): a frozen live ▲ ≥ +25% grants Trending (haste, +trendingPower/+0 in play). */
|
||||
applyLive(_rules: DuelRuleset, card: DuelCard, live: { trendPercent: number | null }): DuelCard {
|
||||
if (live.trendPercent === null || live.trendPercent < 25 || card.type !== 'Figure' || card.keywords.includes('Trending')) return card;
|
||||
return { ...card, keywords: [...card.keywords, 'Trending'] };
|
||||
},
|
||||
isOver,
|
||||
result: (state: DuelState) => state.result ?? { winner: null, reason: 'in progress' },
|
||||
viewFor,
|
||||
logFor,
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* 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';
|
||||
export * from './engine.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 };
|
||||
}
|
||||
|
||||
import * as engine from './engine.ts';
|
||||
/** Compile-time check that engine.ts implements the contract. */
|
||||
export const duelEngine: DuelEngineApi = engine;
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* 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(),
|
||||
secondPlayerCitations: int(0, 5),
|
||||
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();
|
||||
|
||||
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,
|
||||
secondPlayerCitations: 1, // balance v1 (#64): first player 60.1% → 54.7%
|
||||
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: 40, // balance v1 (#64): 3.9% of games decided at the cap
|
||||
}) 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(structuredClone(base));
|
||||
if (typeof overrides !== 'object' || Array.isArray(overrides)) throw new TypeError('Ruleset overrides must be an object');
|
||||
return parseDuelRuleset({ ...structuredClone(base), ...(overrides as Record<string, unknown>) });
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
/**
|
||||
* WikiDeck Duel: the Magic-style 40-card engine (off-chain). Contract types.
|
||||
* 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).
|
||||
* 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'];
|
||||
|
||||
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
|
||||
export const PORTALS: readonly Portal[] = ['Arts', 'Earth', 'History', 'Science', 'Society', 'Neutral'];
|
||||
|
||||
/** 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[];
|
||||
/** The card's own Q-id, and the Q-ids its claims cite: Linked if either cites the other (DUEL_DESIGN §6). */
|
||||
qid?: string;
|
||||
cites?: string[];
|
||||
}
|
||||
|
||||
/** When an effect runs. Sorcery speed only: there is no stack and no response window. */
|
||||
export type EffectTrigger =
|
||||
| '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
|
||||
|
||||
/** Effect ops the interpreter knows. duel-cards builds the 12 templates (DUEL_DESIGN §5) from these. */
|
||||
export type EffectOp =
|
||||
| '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 =
|
||||
// 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;
|
||||
/** Default per op: damage → 'anyTarget'; pump → 'self'; draw/gainLife/createToken → 'controller'; drain → 'opponent'. */
|
||||
target?: TargetSpec;
|
||||
amount?: number;
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 tokenId (or a sample id in sims; `token:` ids for tokens). */
|
||||
cardId: string;
|
||||
pageId: number | null;
|
||||
revisionId?: number;
|
||||
title: string;
|
||||
/** Wikidata description ("American actor (1909–1994)"), for log first mentions. */
|
||||
description?: string;
|
||||
type: CardType;
|
||||
/** e.g. 'conflict', 'election', 'organisation', 'pathology'. */
|
||||
subtype?: string | null;
|
||||
portal: Portal;
|
||||
cost: 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: +N max Citations while controlled (all sources together ≤ territoryCap). */
|
||||
territory?: number;
|
||||
effects: EffectSpec[];
|
||||
/** Deterministic rules text (shared/duel/text.ts). Display only. */
|
||||
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;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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
|
||||
startingLife: number; // 20 Notability
|
||||
openingHand: number; // 7
|
||||
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
|
||||
secondPlayerCitations: number; // 1 (balance v1): extra Citations on the second player's first turn (designer's "Second Opinion" lever)
|
||||
maxCitations: number; // 10
|
||||
citationsPerTurn: number; // 1
|
||||
territoryCap: number; // 2
|
||||
locationsPerTurn: number; // 1
|
||||
libraryEmpty: LibraryEmpty; // 'lose'
|
||||
maxKeywords: number; // 2
|
||||
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
|
||||
timeoutsToConcede: number; // 3 consecutive timeouts lose
|
||||
/** 40 (balance v1); null = none. After this many turns in total, higher Notability wins, then higher power in play, then the second player. */
|
||||
turnCap: number | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// State
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** '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; "t:3" = token); 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;
|
||||
/** 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;
|
||||
/** Entry order (trigger order). */
|
||||
entered: number;
|
||||
/** Connected bonus already logged. */
|
||||
connectedLogged: boolean;
|
||||
}
|
||||
|
||||
export interface PlayerState {
|
||||
life: number;
|
||||
/** Citations available this turn. */
|
||||
citations: number;
|
||||
/** Base max (rises by citationsPerTurn to maxCitations). */
|
||||
baseCitations: number;
|
||||
library: CardInstance[]; // top = index 0. Hidden.
|
||||
hand: CardInstance[]; // hidden from the opponent
|
||||
graveyard: CardInstance[]; // "Deleted", public
|
||||
mulligansTaken: number;
|
||||
ready: boolean;
|
||||
locationsThisTurn: number;
|
||||
/** Remaining time bank in seconds (the host decrements it). */
|
||||
bankSeconds: number;
|
||||
/** Consecutive timeouts. */
|
||||
timeouts: number;
|
||||
/** libraryEmpty 'fatigue': damage of the last empty draw. */
|
||||
fatigue: number;
|
||||
}
|
||||
|
||||
export interface CombatState {
|
||||
attackers: string[];
|
||||
/** blocker uid → attacker uid. */
|
||||
blocks: Record<string, string>;
|
||||
}
|
||||
|
||||
export type EndReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap';
|
||||
|
||||
export interface DuelResult {
|
||||
winner: Seat | null; // null = draw
|
||||
reason: EndReason;
|
||||
}
|
||||
|
||||
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;
|
||||
/** Counters for token uids and entry order. */
|
||||
nextToken: number;
|
||||
nextEntry: 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' }
|
||||
/** 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; clients get logFor(state, seat); state.log is omniscient)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 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: 'turnStart'; seat: Seat; citations: number; life: [number, number] }
|
||||
/** card is omitted in the opponent's logFor (hidden draw). */
|
||||
| { kind: 'draw'; seat: Seat; card?: 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 }
|
||||
/** 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 }[] }
|
||||
/** 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 }
|
||||
| { kind: 'discard'; seat: Seat; card: CardRef }
|
||||
| { kind: 'fatigue'; seat: Seat; amount: number }
|
||||
| { kind: 'concede'; seat: Seat }
|
||||
| { kind: 'timeout'; seat: Seat }
|
||||
| { kind: 'gameOver'; winner: Seat | null; reason: EndReason; life: [number, number] }
|
||||
);
|
||||
|
||||
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 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 };
|
||||
}
|
||||
|
||||
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,161 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { DEFAULT_DUEL_RULESET, applyAction, createDuel, legalActions, statsOf, toAct, viewFor } from '../shared/duel/index.ts';
|
||||
import type { DuelAction, DuelCard, DuelState, Seat } from '../shared/duel/index.ts';
|
||||
import { fig } from './duel-core-fixtures.ts';
|
||||
|
||||
/**
|
||||
* Scenario harness: both players start with exactly `hands` in hand (rest of the
|
||||
* library is vanilla filler), seat 0 goes first, lots of Citations.
|
||||
*/
|
||||
function scenario(hands: [DuelCard[], DuelCard[]], over: Partial<typeof DEFAULT_DUEL_RULESET> = {}): DuelState {
|
||||
const rules = { ...DEFAULT_DUEL_RULESET, deckSize: 20, openingHand: 0, citationsPerTurn: 5, ...over };
|
||||
const filler = (seat: number) => Array.from({ length: 20 }, (_, i) => fig(`f${seat}-${i}`, 1, 1));
|
||||
const decks = [0, 1].map(seat => [...hands[seat], ...filler(seat)].slice(0, rules.deckSize)) as [DuelCard[], DuelCard[]];
|
||||
let s = structuredClone(createDuel(rules, decks, 'scenario'));
|
||||
s.firstSeat = 0; s.active = 0;
|
||||
for (const seat of [0, 1] as Seat[]) {
|
||||
const p = s.players[seat];
|
||||
const ids = new Set(hands[seat].map(c => c.cardId));
|
||||
p.hand = p.library.filter(c => ids.has(c.card.cardId));
|
||||
p.library = p.library.filter(c => !ids.has(c.card.cardId));
|
||||
}
|
||||
s = applyAction(s, 0, { type: 'keep' });
|
||||
return applyAction(s, 1, { type: 'keep' });
|
||||
}
|
||||
const uid = (s: DuelState, id: string) => [...s.players[0].hand, ...s.players[1].hand, ...s.battlefield].find(c => c.card.cardId === id)!.uid;
|
||||
const act = (s: DuelState, a: DuelAction) => applyAction(s, toAct(s)!, a);
|
||||
const pass = (s: DuelState) => act(act(s, { type: 'endPhase' }), { type: 'confirmAttack' });
|
||||
const ev = (id: string, effects: DuelCard['effects'], type: DuelCard['type'] = 'Event'): DuelCard => ({ ...fig(id, 0, 0), type, effects });
|
||||
|
||||
test('createToken, maxTokens, and tokens vanish', () => {
|
||||
const election = ev('election', [{ trigger: 'onPlay', op: 'createToken', amount: 2, token: { name: 'Elected Member', power: 1, toughness: 1, portal: 'Society' } }]);
|
||||
let s = scenario([[election], []]);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'election') });
|
||||
const tokens = s.battlefield.filter(p => p.card.token);
|
||||
assert.equal(tokens.length, 2);
|
||||
assert.equal(s.log.filter(e => e.kind === 'tokenCreated').length, 2);
|
||||
assert.ok(tokens.every(t => t.sick));
|
||||
});
|
||||
|
||||
test('T6 pump then fight uses both chosen targets', () => {
|
||||
const sport = ev('final', [
|
||||
{ trigger: 'onPlay', op: 'pump', target: 'ownFigure', power: 2, toughness: 0 },
|
||||
{ trigger: 'onPlay', op: 'fight', target: 'opponentFigure' },
|
||||
]);
|
||||
let s = scenario([[fig('mine', 2, 4), sport], [fig('theirs', 3, 3)]]);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'mine') });
|
||||
s = pass(s);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'theirs') });
|
||||
s = pass(s);
|
||||
const plays = legalActions(s, 0).filter(a => a.type === 'play' && a.uid === uid(s, 'final'));
|
||||
assert.deepEqual(plays, [{ type: 'play', uid: uid(s, 'final'), targets: [{ kind: 'card', uid: uid(s, 'mine') }, { kind: 'card', uid: uid(s, 'theirs') }] }]);
|
||||
s = act(s, plays[0]);
|
||||
assert.ok(!s.battlefield.some(p => p.card.cardId === 'theirs'), '4 power kills a 3/3');
|
||||
assert.equal(s.battlefield.find(p => p.card.cardId === 'mine')!.damage, 3);
|
||||
assert.equal(statsOf(s, uid(s, 'mine')).power, 4, 'pump lasts until end of turn');
|
||||
});
|
||||
|
||||
test('Doctrine attaches, buffs, and is Deleted when its Figure leaves', () => {
|
||||
const adopt = ev('monoid', [
|
||||
{ trigger: 'onPlay', op: 'attach', target: 'ownFigure' },
|
||||
{ trigger: 'static', op: 'pump', target: 'attached', power: 2, toughness: 2, grant: ['Featured'] },
|
||||
], 'Doctrine');
|
||||
const kill = ev('war', [{ trigger: 'onPlay', op: 'damage', target: 'figureOrLocation', amount: 5 }]);
|
||||
let s = scenario([[fig('host', 1, 1), adopt], [kill]]);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'host') });
|
||||
s = act(s, { type: 'play', uid: uid(s, 'monoid'), targets: [{ kind: 'card', uid: uid(s, 'host') }] });
|
||||
assert.deepEqual(statsOf(s, uid(s, 'host')), { power: 3, toughness: 3 });
|
||||
assert.ok(viewFor(s, 0).battlefield.find(p => p.card.cardId === 'host')!.keywords.includes('Featured'));
|
||||
assert.equal(s.log.filter(e => e.kind === 'adopt').length, 1);
|
||||
s = pass(s);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'war'), targets: [{ kind: 'card', uid: uid(s, 'host') }] });
|
||||
assert.equal(s.battlefield.length, 0, 'Figure destroyed, Doctrine Deleted with it');
|
||||
assert.equal(s.players[0].graveyard.length, 2);
|
||||
});
|
||||
|
||||
test('Doctrine with no legal target is not playable; Protected blocks opposing Events', () => {
|
||||
const adopt = ev('monoid', [{ trigger: 'onPlay', op: 'attach', target: 'ownFigure' }], 'Doctrine');
|
||||
const kill = ev('war', [{ trigger: 'onPlay', op: 'damage', target: 'figure', amount: 5 }]);
|
||||
let s = scenario([[adopt, fig('pol', 2, 2, ['Protected'])], [kill]]);
|
||||
assert.ok(!legalActions(s, 0).some(a => a.type === 'play' && a.uid === uid(s, 'monoid')));
|
||||
s = act(s, { type: 'play', uid: uid(s, 'pol') });
|
||||
s = pass(s);
|
||||
assert.ok(!legalActions(s, 1).some(a => a.type === 'play' && a.uid === uid(s, 'war')), 'Protected Figure is the only target');
|
||||
});
|
||||
|
||||
test('Well-sourced prevents 1; Stub grows to 2; Legacy draws', () => {
|
||||
const ping = ev('ping', [{ trigger: 'onPlay', op: 'damage', target: 'figure', amount: 2 }]);
|
||||
let s = scenario([[fig('ws', 1, 2, ['Well-sourced']), fig('stub', 1, 1, ['Stub']), fig('leg', 1, 1, ['Legacy'])], [ping, ev('ping2', ping.effects)]]);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'ws') });
|
||||
s = act(s, { type: 'play', uid: uid(s, 'stub') });
|
||||
s = act(s, { type: 'play', uid: uid(s, 'leg') });
|
||||
s = pass(s);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'ping'), targets: [{ kind: 'card', uid: uid(s, 'ws') }] });
|
||||
assert.equal(s.battlefield.find(p => p.card.cardId === 'ws')!.damage, 1, 'first point prevented');
|
||||
const hand0 = s.players[0].hand.length;
|
||||
s = act(s, { type: 'play', uid: uid(s, 'ping2'), targets: [{ kind: 'card', uid: uid(s, 'leg') }] });
|
||||
assert.equal(s.players[0].hand.length, hand0 + 1, 'Legacy drew');
|
||||
for (let i = 0; i < 6; i++) s = pass(s);
|
||||
assert.deepEqual(statsOf(s, uid(s, 'stub')), { power: 3, toughness: 3 }, 'Stub capped at 2 counters');
|
||||
});
|
||||
|
||||
test('one Location per turn; Territory raises max Citations up to the cap', () => {
|
||||
const loc = (id: string): DuelCard => ({ ...fig(id, 0, 2), type: 'Location', territory: 1 });
|
||||
let s = scenario([[loc('l1'), loc('l2'), loc('l3')], []], { citationsPerTurn: 1, maxCitations: 10 });
|
||||
s = act(s, { type: 'play', uid: uid(s, 'l1') });
|
||||
assert.ok(!legalActions(s, 0).some(a => a.type === 'play'), 'second Location not allowed (and no Citations left)');
|
||||
assert.equal(viewFor(s, 0).you.maxCitations, 2);
|
||||
s = pass(s); s = pass(s);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'l2') });
|
||||
s = pass(s); s = pass(s);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'l3') });
|
||||
assert.equal(viewFor(s, 0).you.maxCitations, 3 + 2, 'base 3 + Territory capped at 2');
|
||||
});
|
||||
|
||||
test('Garrison Location blocks; Featured needs a Featured/Translated/Multilingual blocker', () => {
|
||||
const garrison: DuelCard = { ...fig('fort', 0, 3), type: 'Location' };
|
||||
let s = scenario([[fig('grunt', 2, 2), fig('flyer', 2, 2, ['Featured'])], [garrison, fig('reach', 1, 3, ['Translated'])]]);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'grunt') });
|
||||
s = act(s, { type: 'play', uid: uid(s, 'flyer') });
|
||||
s = pass(s);
|
||||
s = act(s, { type: 'play', uid: uid(s, 'fort') });
|
||||
s = act(s, { type: 'play', uid: uid(s, 'reach') });
|
||||
s = pass(s);
|
||||
s = act(s, { type: 'endPhase' });
|
||||
s = act(s, { type: 'toggleAttacker', uid: uid(s, 'grunt') });
|
||||
s = act(s, { type: 'toggleAttacker', uid: uid(s, 'flyer') });
|
||||
s = act(s, { type: 'confirmAttack' });
|
||||
const blocks = legalActions(s, 1).filter(a => a.type === 'block');
|
||||
assert.deepEqual(blocks.map(b => b.type === 'block' ? `${b.blocker}>${b.attacker}` : ''), [
|
||||
`${uid(s, 'fort')}>${uid(s, 'grunt')}`, `${uid(s, 'reach')}>${uid(s, 'grunt')}`, `${uid(s, 'reach')}>${uid(s, 'flyer')}`,
|
||||
]);
|
||||
s = act(s, { type: 'block', blocker: uid(s, 'fort'), attacker: uid(s, 'grunt') });
|
||||
s = act(s, { type: 'block', blocker: uid(s, 'reach'), attacker: uid(s, 'flyer') });
|
||||
s = act(s, { type: 'confirmBlocks' });
|
||||
assert.equal(s.players[1].life, 20);
|
||||
assert.equal(s.battlefield.length, 4, 'nobody died: 2 vs 3 toughness, 1 vs 2');
|
||||
});
|
||||
|
||||
test('three consecutive timeouts lose; turnCap decides by Notability', () => {
|
||||
let s = scenario([[], []]);
|
||||
for (let i = 0; i < 5 && !s.result; i++) s = applyAction(s, toAct(s)!, { type: 'timeout' });
|
||||
assert.deepEqual(s.result, { winner: 1, reason: 'timeout' }, 'seat 0 timed out on turns 1, 3, 5');
|
||||
let c = scenario([[fig('a', 3, 3)], []], { turnCap: 4 });
|
||||
c = act(c, { type: 'play', uid: uid(c, 'a') });
|
||||
c = pass(c); c = pass(c);
|
||||
c = act(c, { type: 'endPhase' });
|
||||
c = act(c, { type: 'toggleAttacker', uid: uid(c, 'a') });
|
||||
c = act(c, { type: 'confirmAttack' });
|
||||
c = pass(c);
|
||||
assert.deepEqual(c.result, { winner: 0, reason: 'turnCap' });
|
||||
});
|
||||
|
||||
test('secondPlayerCitations gives the second player extra Citations on their first turn only', () => {
|
||||
let s = scenario([[], []], { citationsPerTurn: 1, secondPlayerCitations: 1 });
|
||||
assert.equal(s.players[0].citations, 1);
|
||||
s = pass(s);
|
||||
assert.equal(s.players[1].citations, 2);
|
||||
s = pass(s); s = pass(s);
|
||||
assert.equal(s.players[1].citations, 2, 'turn 4: base 2, no bonus');
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Rng } from '../shared/game/rng.ts';
|
||||
import {
|
||||
DEFAULT_DUEL_RULESET, applyAction, createDuel, deserialize, duelEnginePort, isOver, legalActions, logFor, replay,
|
||||
serialize, statsOf, toAct, validateDeck, viewFor,
|
||||
} from '../shared/duel/index.ts';
|
||||
import type { DuelAction, DuelCard, DuelState, Seat } from '../shared/duel/index.ts';
|
||||
import { POOL, fig, randomDeck } from './duel-core-fixtures.ts';
|
||||
|
||||
const rules = DEFAULT_DUEL_RULESET;
|
||||
|
||||
/** Random legal policy that prefers progress so games stay short. */
|
||||
function pick(rng: Rng, actions: DuelAction[]): DuelAction {
|
||||
const plays = actions.filter(a => a.type === 'play' || a.type === 'toggleAttacker' || a.type === 'block');
|
||||
if (plays.length && rng.next() < 0.75) return rng.pick(plays);
|
||||
return rng.pick(actions);
|
||||
}
|
||||
|
||||
function playOut(seed: string, maxActions = 3000) {
|
||||
const decks: [DuelCard[], DuelCard[]] = [randomDeck(`${seed}/a`, 0), randomDeck(`${seed}/b`, 1)];
|
||||
let state = createDuel(rules, decks, seed);
|
||||
const rng = Rng.fromSeed(`${seed}/policy`);
|
||||
const actions: { seat: Seat; action: DuelAction }[] = [];
|
||||
const views: DuelState[] = [];
|
||||
while (!isOver(state) && actions.length < maxActions) {
|
||||
const seat = toAct(state)!;
|
||||
assert.deepEqual(legalActions(state, (1 - seat) as Seat), [], 'non-acting seat has no actions');
|
||||
const legal = legalActions(state, seat);
|
||||
assert.ok(legal.length > 0, 'acting seat always has an action');
|
||||
const action = pick(rng, legal);
|
||||
actions.push({ seat, action });
|
||||
state = applyAction(state, seat, action);
|
||||
views.push(state);
|
||||
}
|
||||
return { decks, state, actions, views };
|
||||
}
|
||||
|
||||
test('validateDeck enforces 40 owned-style cards', () => {
|
||||
const deck = randomDeck('v', 0);
|
||||
validateDeck(rules, deck);
|
||||
assert.throws(() => validateDeck(rules, deck.slice(1)));
|
||||
assert.throws(() => validateDeck(rules, [...deck.slice(1), deck[0]].map((c, i) => (i === 39 ? { ...c, cardId: deck[1].cardId } : c))));
|
||||
assert.throws(() => validateDeck(rules, deck.map((c, i) => (i === 0 ? { ...c, keywords: ['Protected', 'Stub', 'Legacy'] } : c)) as DuelCard[]));
|
||||
assert.throws(() => validateDeck(rules, deck.map((c, i) => (i === 0 ? { ...c, type: 'Basic' } : c)) as unknown as DuelCard[]));
|
||||
});
|
||||
|
||||
test('createDuel deals 7 and starts in mulligan', () => {
|
||||
const s = createDuel(rules, [randomDeck('c', 0), randomDeck('d', 1)], 'seed-1');
|
||||
assert.equal(s.phase, 'mulligan');
|
||||
assert.equal(s.players[0].hand.length, 7);
|
||||
assert.equal(s.players[1].library.length, 33);
|
||||
assert.equal(toAct(s), 0);
|
||||
assert.deepEqual(legalActions(s, 0), [{ type: 'keep' }, { type: 'mulligan' }]);
|
||||
const m = applyAction(s, 0, { type: 'mulligan' });
|
||||
assert.deepEqual(legalActions(m, 0), [{ type: 'keep' }]);
|
||||
const k = applyAction(m, 0, { type: 'keep' });
|
||||
assert.equal(k.players[0].hand.length, 6, 'one card bottomed after one mulligan');
|
||||
assert.equal(k.players[0].library.length, 34);
|
||||
const both = applyAction(k, 1, { type: 'keep' });
|
||||
assert.equal(both.phase, 'main');
|
||||
assert.equal(both.turn, 1);
|
||||
const first = both.firstSeat;
|
||||
assert.equal(both.players[first].hand.length, first === 0 ? 6 : 7, 'first player skips the first draw');
|
||||
assert.equal(both.players[first].citations, 1);
|
||||
assert.equal(s.players[0].hand.length, 7, 'input not mutated');
|
||||
});
|
||||
|
||||
test('random legal games end, are deterministic and replay exactly', () => {
|
||||
for (let i = 0; i < 25; i++) {
|
||||
const seed = `prop-${i}`;
|
||||
const { decks, state, actions } = playOut(seed);
|
||||
assert.ok(isOver(state), `game ${seed} ended (${actions.length} actions, turn ${state.turn})`);
|
||||
const again = replay(rules, decks, seed, actions);
|
||||
assert.equal(serialize(again), serialize(state));
|
||||
assert.deepEqual(deserialize(serialize(state)), state);
|
||||
assert.ok(['life', 'library', 'concede', 'timeout', 'turnCap'].includes(state.result!.reason));
|
||||
}
|
||||
});
|
||||
|
||||
test('viewFor and logFor never leak hidden cards', () => {
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const { views } = playOut(`leak-${i}`);
|
||||
for (const s of views) {
|
||||
for (const seat of [0, 1] as Seat[]) {
|
||||
const opp = (1 - seat) as Seat;
|
||||
const hidden = new Set([...s.players[opp].hand, ...s.players[opp].library, ...s.players[seat].library].map(c => c.card.cardId));
|
||||
// Cards revealed publicly earlier (played then bounced, etc.) may legitimately be known.
|
||||
const publicIds = new Set(s.log.flatMap(e => {
|
||||
if (e.kind === 'draw') return [];
|
||||
return JSON.stringify(e).match(/sample-\d+#[01]/g) ?? [];
|
||||
}));
|
||||
const text = JSON.stringify(viewFor(s, seat)) + JSON.stringify(logFor(s, seat));
|
||||
for (const id of hidden) {
|
||||
if (publicIds.has(id)) continue;
|
||||
assert.ok(!text.includes(`"${id}"`), `seat ${seat} sees hidden ${id} at version ${s.version}`);
|
||||
}
|
||||
assert.ok(!('library' in viewFor(s, seat).opponent));
|
||||
assert.ok(!('rng' in viewFor(s, seat)));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('combat: simultaneous damage, one blocker, sickness, Featured evasion', () => {
|
||||
const filler = (seat: number) => Array.from({ length: 38 }, (_, i) => fig(`f${seat}-${i}`, 1, 1));
|
||||
const r = { ...rules, openingHand: 0 };
|
||||
let s = createDuel(r, [[fig('A', 3, 3), fig('Fly', 2, 2, ['Featured']), ...filler(0)], [fig('B', 2, 4), fig('C', 1, 1), ...filler(1)]], 'combat');
|
||||
// Stack the libraries deterministically for the test.
|
||||
s = structuredClone(s);
|
||||
const top = (seat: 0 | 1, ids: string[]) => {
|
||||
const lib = s.players[seat].library;
|
||||
for (const id of ids.reverse()) { const i = lib.findIndex(c => c.card.cardId === id); lib.unshift(...lib.splice(i, 1)); }
|
||||
};
|
||||
s.firstSeat = 0; s.active = 0;
|
||||
top(0, ['A', 'Fly']); top(1, ['B', 'C']);
|
||||
s.players[0].hand = s.players[0].library.splice(0, 2);
|
||||
s.players[1].hand = s.players[1].library.splice(0, 2);
|
||||
s = applyAction(s, 0, { type: 'keep' });
|
||||
s = applyAction(s, 1, { type: 'keep' });
|
||||
assert.equal(s.active, 0);
|
||||
const uidOf = (id: string) => [...s.players[0].hand, ...s.players[1].hand, ...s.battlefield].find(c => c.card.cardId === id)!.uid;
|
||||
s = applyAction(s, 0, { type: 'play', uid: uidOf('A') });
|
||||
s = applyAction(s, 0, { type: 'endPhase' });
|
||||
assert.deepEqual(legalActions(s, 0), [{ type: 'confirmAttack' }], 'summoning sickness');
|
||||
s = applyAction(s, 0, { type: 'confirmAttack' });
|
||||
assert.equal(s.active, 1);
|
||||
s = applyAction(s, 1, { type: 'play', uid: uidOf('B') });
|
||||
s = applyAction(s, 1, { type: 'endPhase' });
|
||||
s = applyAction(s, 1, { type: 'confirmAttack' });
|
||||
// Turn 3: seat 0 has 2 Citations: play Fly, attack with A; B blocks; 3 dmg vs 4 toughness, 2 vs 3.
|
||||
s = applyAction(s, 0, { type: 'play', uid: uidOf('Fly') });
|
||||
s = applyAction(s, 0, { type: 'endPhase' });
|
||||
s = applyAction(s, 0, { type: 'toggleAttacker', uid: uidOf('A') });
|
||||
s = applyAction(s, 0, { type: 'confirmAttack' });
|
||||
assert.equal(s.phase, 'block');
|
||||
assert.deepEqual(legalActions(s, 1), [{ type: 'block', blocker: uidOf('B'), attacker: uidOf('A') }, { type: 'confirmBlocks' }]);
|
||||
s = applyAction(s, 1, { type: 'block', blocker: uidOf('B'), attacker: uidOf('A') });
|
||||
s = applyAction(s, 1, { type: 'confirmBlocks' });
|
||||
assert.equal(s.battlefield.length, 3, 'nobody died');
|
||||
assert.equal(s.players[1].life, 20);
|
||||
const destroyedOrDamaged = s.log.filter(e => e.kind === 'combatDamage');
|
||||
assert.equal(destroyedOrDamaged.length, 2);
|
||||
// Seat 1 turn: pass. Seat 0: Fly attacks; B (no Featured/Translated) can't block it.
|
||||
s = applyAction(s, 1, { type: 'endPhase' });
|
||||
s = applyAction(s, 1, { type: 'confirmAttack' });
|
||||
s = applyAction(s, 0, { type: 'endPhase' });
|
||||
s = applyAction(s, 0, { type: 'toggleAttacker', uid: uidOf('Fly') });
|
||||
s = applyAction(s, 0, { type: 'confirmAttack' });
|
||||
assert.equal(s.players[1].life, 18, 'Featured unblockable by plain Figure: damage resolved without a block phase');
|
||||
assert.equal(s.active, 1);
|
||||
});
|
||||
|
||||
test('Connected bonus applies and is logged once', () => {
|
||||
const a = fig('obama', 1, 1, [], { pageId: 1, title: 'Barack Obama', connect: { countries: ['Q30'], centuries: [21], links: [2], p31: ['Q5'] } });
|
||||
const b: DuelCard = { ...fig('wh', 0, 0), pageId: 2, title: 'White House', type: 'Location', territory: 1, connect: { countries: ['Q30'], centuries: [19], links: [], p31: ['Q35112'] } };
|
||||
let s = createDuel({ ...rules, deckSize: 2, openingHand: 2, citationsPerTurn: 5 }, [[a, b], [{ ...a, cardId: 'x' }, { ...b, cardId: 'y' }]], 'conn');
|
||||
s = applyAction(s, 0, { type: 'keep' });
|
||||
s = applyAction(s, 1, { type: 'keep' });
|
||||
const me = s.active;
|
||||
const hand = s.players[me].hand;
|
||||
s = applyAction(s, me, { type: 'play', uid: hand.find(c => c.card.type === 'Figure')!.uid });
|
||||
s = applyAction(s, me, { type: 'play', uid: s.players[me].hand[0].uid });
|
||||
const figure = s.battlefield.find(p => p.card.type === 'Figure')!;
|
||||
assert.deepEqual(statsOf(s, figure.uid), { power: 3, toughness: 3 });
|
||||
assert.equal(s.log.filter(e => e.kind === 'connected').length, 1);
|
||||
assert.equal(viewFor(s, me).battlefield.find(p => p.uid === figure.uid)!.connected?.tier, 'Linked');
|
||||
});
|
||||
|
||||
test('empty library loses; concede and timeout', () => {
|
||||
const tiny = { ...rules, deckSize: 8, openingHand: 7 };
|
||||
const pool = POOL.slice(0, 16);
|
||||
let s = createDuel(tiny, [pool.slice(0, 8), pool.slice(8, 16).map(c => ({ ...c, cardId: c.cardId + 'b' }))], 'deckout');
|
||||
s = applyAction(s, 0, { type: 'keep' });
|
||||
s = applyAction(s, 1, { type: 'keep' });
|
||||
for (let i = 0; i < 20 && !isOver(s); i++) s = applyAction(s, toAct(s)!, { type: 'timeout' });
|
||||
assert.equal(s.result?.reason, 'library');
|
||||
const c = applyAction(createDuel(rules, [randomDeck('q', 0), randomDeck('r', 1)], 'c'), 1, { type: 'concede' });
|
||||
assert.deepEqual(c.result, { winner: 0, reason: 'concede' });
|
||||
assert.throws(() => applyAction(c, 0, { type: 'keep' }));
|
||||
});
|
||||
|
||||
test('illegal actions throw', () => {
|
||||
const s = createDuel(rules, [randomDeck('i', 0), randomDeck('j', 1)], 'illegal');
|
||||
assert.throws(() => applyAction(s, 1, { type: 'keep' }), /Not your turn/);
|
||||
assert.throws(() => applyAction(s, 0, { type: 'endPhase' }), /Illegal/);
|
||||
});
|
||||
|
||||
test('engine port binding is EnginePort-shaped', () => {
|
||||
const p = duelEnginePort;
|
||||
assert.equal(p.deckSize(p.defaultRuleset), 40);
|
||||
assert.throws(() => p.starterDeck());
|
||||
const live = p.applyLive(rules, POOL.find(c => c.type === 'Figure')!, { trendPercent: 25 });
|
||||
assert.ok(live.keywords.includes('Trending'));
|
||||
const s = p.createMatch(rules, [randomDeck('p', 0), randomDeck('q', 1)], 'port');
|
||||
assert.deepEqual(p.concedeAction(0), { type: 'concede' });
|
||||
assert.equal(p.result(s).winner, null);
|
||||
});
|
||||
|
||||
test('golden match', () => {
|
||||
const { state, actions } = playOut('golden-1');
|
||||
const digest = createHash('sha256').update(serialize(state)).digest('hex').slice(0, 16);
|
||||
const summary = { actions: actions.length, turn: state.turn, result: state.result, log: state.log.length, digest };
|
||||
assert.deepEqual(summary, GOLDEN);
|
||||
});
|
||||
|
||||
// Regenerate deliberately (an engine rule change) and say so in the PR.
|
||||
const GOLDEN = { actions: 72, turn: 13, result: { winner: 1, reason: 'life' }, log: 103, digest: 'e8bc8630d6f0ab0a' };
|
||||
@@ -0,0 +1,110 @@
|
||||
// Test-only deck builder for duel-core tests. NOT the real derivation (that is duel-cards'
|
||||
// shared/duel/derive.ts): a crude, deterministic mapping from docs/game/card-sample.json
|
||||
// so engine tests have 236 varied real cards. Zero network calls.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { Rng } from '../shared/game/rng.ts';
|
||||
import type { CardType, DuelCard, EffectSpec, Keyword, Portal } from '../shared/duel/index.ts';
|
||||
|
||||
interface SampleCard {
|
||||
pageId: number; title: string; description?: string; revisionId?: number; pageBytes: number; languageCount: number;
|
||||
categories: string[]; stats: { attention: number; depth: number; reach: number }; faction: string;
|
||||
instanceOf?: { id: string; label: string }[];
|
||||
}
|
||||
|
||||
const sample = JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8')) as { cards: SampleCard[] };
|
||||
|
||||
/** Effect templates shaped like DUEL_DESIGN §5 (k = magnitude). */
|
||||
const EVENTS = (k: number): EffectSpec[][] => [
|
||||
[{ trigger: 'onPlay', op: 'damage', target: 'figureOrLocation', amount: k + 1, template: 'T3' }],
|
||||
[{ trigger: 'onPlay', op: 'damageEach', target: 'each', amount: Math.max(1, k - 1), template: 'T4' }],
|
||||
[{ trigger: 'onPlay', op: 'createToken', amount: k, token: { name: 'Elected Member', power: 1, toughness: 1, portal: 'Society' }, template: 'T5' }],
|
||||
[{ trigger: 'onPlay', op: 'pump', target: 'ownFigure', power: k, toughness: 0, template: 'T6' }, { trigger: 'onPlay', op: 'fight', target: 'opponentFigure', template: 'T6' }],
|
||||
[{ trigger: 'onPlay', op: 'draw', amount: k, template: 'T7' }],
|
||||
[{ trigger: 'onPlay', op: 'damage', target: 'anyTarget', amount: k, template: 'X1' }],
|
||||
];
|
||||
const INSTITUTIONS = (k: number, cost: number): EffectSpec[][] => [
|
||||
cost >= 4
|
||||
? [{ trigger: 'startOfTurn', op: 'createToken', token: { name: 'Staff Member', power: 1, toughness: 1, portal: 'Society' }, condition: { maxTokens: 3 }, template: 'T8' }]
|
||||
: [{ trigger: 'onEnter', op: 'createToken', token: { name: 'Staff Member', power: 1, toughness: 1, portal: 'Society' }, template: 'T8' }],
|
||||
[{ trigger: 'onEnter', op: 'draw', amount: 1, template: 'T9' }, { trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 1, condition: { connected: true }, template: 'T9' }],
|
||||
[{ trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { maxPower: 2 }, template: 'T10' }],
|
||||
];
|
||||
const DOCTRINES = (k: number): EffectSpec[][] => [
|
||||
[{ trigger: 'onPlay', op: 'attach', target: 'ownFigure', template: 'T11' }, { trigger: 'static', op: 'pump', target: 'attached', power: k, toughness: k, template: 'T11' }],
|
||||
[{ trigger: 'onPlay', op: 'attach', target: 'ownFigure', template: 'T11' }, { trigger: 'static', op: 'pump', target: 'attached', power: k, toughness: k, grant: ['Well-sourced'], template: 'T11' }],
|
||||
[{ trigger: 'onPlay', op: 'attach', target: 'ownFigure', template: 'T11' }, { trigger: 'static', op: 'pump', target: 'attached', power: k, toughness: k, template: 'T11' }, { trigger: 'onCombatDamageToPlayer', op: 'draw', amount: 1, template: 'T11' }],
|
||||
[{ trigger: 'onPlay', op: 'attach', target: 'figure', template: 'T12' }, { trigger: 'static', op: 'pump', target: 'attached', power: -k, toughness: -k, template: 'T12' }],
|
||||
];
|
||||
|
||||
const PORTAL: Record<string, Portal> = {
|
||||
People: 'Society', Places: 'Earth', Nature: 'Earth', Structures: 'Arts', Works: 'Arts', Events: 'History', Organisations: 'Society',
|
||||
'Ideas & Tech': 'Science', Sport: 'Society', Other: 'Neutral',
|
||||
};
|
||||
|
||||
function typeOf(c: SampleCard, i: number): CardType {
|
||||
if (c.instanceOf?.some(x => x.id === 'Q5') || c.faction === 'Nature') return 'Figure';
|
||||
if (c.faction === 'Places' || c.faction === 'Structures') return i % 2 ? 'Location' : 'Figure';
|
||||
if (c.faction === 'Events') return 'Event';
|
||||
if (c.faction === 'Works' || c.faction === 'Organisations') return 'Institution';
|
||||
return (['Event', 'Doctrine', 'Figure', 'Institution'] as CardType[])[i % 4];
|
||||
}
|
||||
|
||||
const COUNTRIES = ['Q30', 'Q145', 'Q142', 'Q183', 'Q668', 'Q17', 'Q902', 'Q252'];
|
||||
|
||||
export function toDuelCard(c: SampleCard, i: number): DuelCard {
|
||||
const type = typeOf(c, i);
|
||||
const fame = Math.round((c.stats.attention + c.stats.depth + c.stats.reach) / 3);
|
||||
const cost = 1 + [26, 39, 51, 63, 78].filter(t => fame >= t).length;
|
||||
const k = Math.ceil(cost / 2);
|
||||
const keywords: Keyword[] = [];
|
||||
if (type === 'Figure') {
|
||||
const add = (kw: Keyword, ok: boolean) => { if (ok && keywords.length < 2) keywords.push(kw); };
|
||||
add('Protected', c.categories.includes('Living people'));
|
||||
add('Featured', c.stats.attention >= 85);
|
||||
add('Legacy', c.categories.some(x => /^\d+ deaths$/.test(x)));
|
||||
add('Multilingual', c.stats.reach >= 90);
|
||||
add('Translated', c.stats.reach >= 75 && c.stats.reach < 90);
|
||||
add('Well-sourced', c.stats.depth >= 85);
|
||||
add('Stub', c.pageBytes < 3000 || c.categories.some(x => /stubs$/.test(x)));
|
||||
add('Local', c.stats.reach === 0);
|
||||
}
|
||||
const budget = [3, 4, 6, 8, 10, 12][cost - 1] - keywords.filter(x => x !== 'Stub' && x !== 'Translated' && x !== 'Local').length;
|
||||
const a = c.stats.attention + 1, d = c.stats.depth + 1;
|
||||
const power = type === 'Figure' ? Math.min(budget - 1, Math.max(1, Math.round(budget * a / (a + d)))) : 0;
|
||||
const toughness = type === 'Figure' ? Math.max(1, budget - power) : type === 'Location' ? 1 + Math.floor(c.stats.depth / 25) : 0;
|
||||
const effects: EffectSpec[] =
|
||||
type === 'Event' ? EVENTS(k)[i % 6]
|
||||
: type === 'Doctrine' ? DOCTRINES(k)[i % 4]
|
||||
: type === 'Institution' ? INSTITUTIONS(k, cost)[i % 3]
|
||||
: [];
|
||||
return {
|
||||
cardId: `sample-${c.pageId}`, pageId: c.pageId, revisionId: c.revisionId, title: c.title, description: c.description, type,
|
||||
portal: PORTAL[c.faction] ?? 'Neutral', cost: type === 'Location' ? Math.ceil(cost / 2) : cost, power, toughness, keywords,
|
||||
...(type === 'Location' ? { territory: 1 } : {}), effects, rulesText: '', flavor: '',
|
||||
connect: {
|
||||
countries: [COUNTRIES[c.pageId % COUNTRIES.length]].filter((_, j) => (c.pageId >> 3) % 3 !== 0 || j > 0),
|
||||
centuries: [17 + (c.pageId % 5)],
|
||||
links: [],
|
||||
p31: (c.instanceOf ?? []).map(x => x.id),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const POOL: DuelCard[] = sample.cards.map(toDuelCard);
|
||||
|
||||
// A few direct links so the Linked tier gets exercised.
|
||||
for (let i = 0; i + 1 < POOL.length; i += 9) {
|
||||
const b = POOL[i + 1];
|
||||
if (b.pageId !== null) POOL[i].connect!.links.push(b.pageId);
|
||||
}
|
||||
|
||||
/** `size` distinct pool cards; cardIds suffixed per seat so the two decks never share ids. */
|
||||
export function randomDeck(seed: string, seat: 0 | 1, size = 40): DuelCard[] {
|
||||
const rng = Rng.fromSeed(seed);
|
||||
return rng.shuffle(POOL).slice(0, size).map(c => ({ ...structuredClone(c), cardId: `${c.cardId}#${seat}` }));
|
||||
}
|
||||
|
||||
/** Minimal vanilla Figure for hand-built scenarios. */
|
||||
export function fig(id: string, power: number, toughness: number, keywords: Keyword[] = [], extra: Partial<DuelCard> = {}): DuelCard {
|
||||
return { cardId: id, pageId: null, title: id, type: 'Figure', portal: 'Society', cost: 1, power, toughness, keywords, effects: [], rulesText: '', flavor: '', ...extra };
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
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, 40, 'balance v1 (#64)');
|
||||
assert.equal(rules.secondPlayerCitations, 1, 'balance v1 (#64)');
|
||||
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