forked from WikiDeck/wikideck
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e4dd72ca8 | ||
|
|
c0dd5b2e38 | ||
|
|
bf929e2575 | ||
|
|
ff6c93c808 | ||
|
|
4623930e8f | ||
|
|
0f924b7732 | ||
|
|
848cfbbaf1 | ||
|
|
5cd0ffb0c9 | ||
|
|
9c26b8d560 | ||
|
|
a57698a7e2 | ||
|
|
79041990ed | ||
|
|
75ce8f5ba5 | ||
|
|
a7e46583fb | ||
|
|
4160086d16 | ||
|
|
0fcf0b0a73 | ||
|
|
5d5eaa5488 | ||
|
|
0666b08829 | ||
|
|
2fe16a66c8 | ||
|
|
5a7cfba124 | ||
|
|
4daf87edde | ||
|
|
5365611c4a |
@@ -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 0).
|
||||
- **Turn:** refresh (base max +1 to 10, plus Territory ≤ 2; refill; untap; Pending review ends; Stub and `startOfTurn` triggers) → draw → **main** → **attack** → **block** → damage → end (damage and "until end of turn" clear; discard down to `handSize` 7, **highest cost first**, automatically).
|
||||
- Locations: `locationsPerTurn` (1), can't attack. Garrison Locations (toughness > 0) block as 0-power.
|
||||
- Combat: attack the opponent only; each blocker blocks one attacker, at most one blocker per attacker; simultaneous damage; destroy triggers after all combat damage. No trample, first strike, stack or instants.
|
||||
- **Connected** (engine, from `connect`, tiers in `connectedTiers`): Linked (either `links` contains the other's `pageId`, or either `cites` contains the other's `qid`), Compatriot (shared country), Contemporary (shared century, different types), Kin (shared P31, not Q5/Q16521). A Figure gets the single best bonus among other permanents its controller controls: `+linkedBonus` (2) if Linked, else `+connectedBonus` (1). Logged once (`connected`). Opposing Connected pairs are logged once as `rivalry`.
|
||||
- **Timeouts:** `timeout` passes (mulligan: keep; main/attack: end the turn without attacking; block: confirm current blocks). `timeoutsToConcede` (3) consecutive timeouts by one seat lose (`reason: 'timeout'`).
|
||||
- `turnCap` (null by default): after that many total turns, higher Notability wins, then higher total power in play, then the second player.
|
||||
|
||||
## Phases and actions
|
||||
| Phase | Who acts | Listed actions |
|
||||
|---|---|---|
|
||||
| `mulligan` | seat 0 until ready, then seat 1 | `keep`, `mulligan` |
|
||||
| `main` | active | `play {uid, targets?}`, `endPhase` |
|
||||
| `attack` | active | `toggleAttacker {uid}` (untapped, not Pending review, not yet declared), `confirmAttack` |
|
||||
| `block` | defender | `block {blocker, attacker}` (unassigned blocker, unblocked attacker, evasion allowing), `confirmBlocks` |
|
||||
| any | either seat | `concede` (not listed) |
|
||||
| any | host, for the seat to act | `timeout` (not listed) |
|
||||
|
||||
Declarations are **monotonic** (no un-declare), so every turn has a bounded number of actions; UIs stage choices locally and send them on confirm. If the defender has no legal block, damage resolves at `confirmAttack` with no block phase. `confirmAttack` with no attackers ends the turn.
|
||||
|
||||
## Views and log
|
||||
- `viewFor(state, seat): PlayerView`: your hand; the opponent's hand and library **sizes** only; both graveyards; the battlefield with current power/toughness, keywords and Connected badge; combat; `toAct`; `version`; `result`. Never the RNG or library order.
|
||||
- **The seed is secret until the match ends.** `seed` plus the deck lists reproduce every shuffle, so the host never sends `seed` or `rng` (or the raw `DuelState`) to clients before `gameOver`. Live log rendering picks template variants from a derived `storySeed = sha256(seed + ':story')`.
|
||||
- `state.log` is omniscient (server, and the recap after the match). Clients get **`logFor(state, seat)`**: the opponent's `draw` events have no `card`. Every other event is public information.
|
||||
- Every event has `seq` and `turn`. `CardRef` carries `uid, cardId, title, pageId, type` plus `power`/`toughness` right after the event.
|
||||
- Kinds (DUEL_DESIGN §10 names): `start, mulligan, keep, turnStart, draw, deploy, cast, adopt, tokenCreated, connected, rivalry, effect, attack, block, effectDamage, combatDamage, playerDamage, lifeGain, destroyed, bounced, discard, fatigue, concede, timeout, gameOver`. `destroyed` = the recap's casualties. Prose templates live with duel-design / ui-pvp, not in the engine.
|
||||
|
||||
## Host binding
|
||||
`duelEnginePort` (engine.ts) is structurally an `EnginePort<DuelRuleset, DuelCard, DuelState, DuelAction>` (`server/game/engine-port.ts`; `shared/` doesn't import `server/`, so host-pvp types it there). `concedeAction`, `timeoutAction`, `turnSeconds`, `turnOf`, `applyLive` included. `starterDeck` and `previewPool` throw: there are no starters (BRIEF decision 2); draft pools come from both players' collections.
|
||||
|
||||
## Stability
|
||||
These types are the contract for duel-cards, host-pvp, ui-duel, ui-pvp and sim-balance. Additive changes (optional fields, new log kinds) can land with the engine; breaking ones get a `[duel-core] contract change` comment on #55 first.
|
||||
@@ -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: 0,
|
||||
maxCitations: 10,
|
||||
citationsPerTurn: 1,
|
||||
territoryCap: 2,
|
||||
locationsPerTurn: 1,
|
||||
libraryEmpty: 'lose',
|
||||
maxKeywords: 2,
|
||||
stubMax: 2,
|
||||
trendingPower: 1,
|
||||
connectedTiers: ['Linked', 'Compatriot', 'Contemporary', 'Kin'],
|
||||
connectedBonus: 1,
|
||||
linkedBonus: 2,
|
||||
turnSeconds: 60,
|
||||
bankSeconds: 300,
|
||||
timeoutsToConcede: 3,
|
||||
turnCap: null,
|
||||
}) as DuelRuleset;
|
||||
|
||||
/** 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; // 0: 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
|
||||
/** Optional: 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,39 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { DuelAction, LogEvent, PlayerView } from './contract.ts';
|
||||
import { boardFromView, expand, legalFromActions, plainLog, type Articles } from './adapter.ts';
|
||||
import { DuelTable } from './DuelTable.tsx';
|
||||
import type { DuelUIAction } from './model.ts';
|
||||
|
||||
/**
|
||||
* The duel board on duel-core's types, for any controller (ui-pvp's OnlinePlay, the local bot match).
|
||||
* One board intent can be several atomic actions (toggleAttacker × N, confirmAttack): they go out
|
||||
* through `onAct` in order, each awaited, each an element of `legal` or legal once the previous ones apply.
|
||||
*/
|
||||
export function DuelBoard({ view, legal, onAct, opponentName, playerName = 'You', error, busy, log, logEvents, articles, clock, onExit, onRecap }: {
|
||||
view: PlayerView; legal: DuelAction[]; onAct: (a: DuelAction) => void | Promise<void>;
|
||||
opponentName: string; playerName?: string; error?: string; busy?: boolean;
|
||||
/** Rendered log lines (duel-design's story renderer). If absent, `logEvents` are shown with plain templates. */
|
||||
log?: string[]; logEvents?: LogEvent[];
|
||||
/** cardId → article image/url, from the chain. */
|
||||
articles?: Articles;
|
||||
clock?: { turn: number; bank: number };
|
||||
onExit?: () => void; onRecap?: () => void;
|
||||
}) {
|
||||
const [sending, setSending] = useState(false);
|
||||
const [sendError, setSendError] = useState<string>();
|
||||
const names = useMemo<[string, string]>(() => (view.seat === 0 ? [playerName, opponentName] : [opponentName, playerName]), [view.seat, playerName, opponentName]);
|
||||
const lines = useMemo(() => log ?? plainLog(logEvents ?? [], names), [log, logEvents, names]);
|
||||
const board = useMemo(() => boardFromView(view, names, lines, articles, clock), [view, names, lines, articles, clock]);
|
||||
const boardLegal = useMemo(() => legalFromActions(legal), [legal]);
|
||||
|
||||
const act = async (ui: DuelUIAction) => {
|
||||
const seq = expand(ui, legal);
|
||||
setSending(true); setSendError(undefined);
|
||||
try { for (const a of seq) await onAct(a); }
|
||||
catch (e) { setSendError(e instanceof Error ? e.message : 'That move was not accepted.'); }
|
||||
finally { setSending(false); }
|
||||
};
|
||||
|
||||
return <DuelTable view={board} legal={boardLegal} onAct={ui => { void act(ui); }} busy={busy || sending}
|
||||
error={error ?? sendError} onExit={onExit} onRecap={onRecap} />;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { DuelAction, DuelCard, DuelEngineLike, DuelRulesetLike, Seat } from './contract.ts';
|
||||
import type { Articles } from './adapter.ts';
|
||||
import { DuelBoard } from './DuelBoard.tsx';
|
||||
import { DuelGate } from './DuelGate.tsx';
|
||||
import { botDeck, hash, mulberry, playerDeck, type BotMatchCard, type DuelBot } from './decks.ts';
|
||||
|
||||
export type { BotMatchCard, DuelBot };
|
||||
|
||||
const HUMAN: Seat = 0, BOT: Seat = 1;
|
||||
const BOT_STEP_MS = 300;
|
||||
|
||||
/**
|
||||
* A bot match in the browser, for eligible players only (BRIEF decisions 2–3): the deck must be
|
||||
* exactly `deckSize` cards the player owns. Off-chain; nothing moves or burns.
|
||||
*/
|
||||
export function DuelBotMatch<S, R extends DuelRulesetLike>({ deck, cards, onExit, onFinish, engine, bot, botPool, rules, playerName = 'You', onMine }: {
|
||||
deck: string[]; cards: BotMatchCard[]; onExit: () => void; onFinish: (matchId?: string) => void;
|
||||
engine: DuelEngineLike<S, R>; bot: DuelBot; botPool: readonly DuelCard[]; rules: R; playerName?: string; onMine?: () => void;
|
||||
}) {
|
||||
const mine = useMemo(() => playerDeck(deck, cards, rules.deckSize), [deck, cards, rules.deckSize]);
|
||||
const [seed] = useState(() => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`);
|
||||
const [state, setState] = useState<S | null>(null);
|
||||
const [error, setError] = useState<string>();
|
||||
const rng = useRef(mulberry(hash(seed)));
|
||||
const current = useRef<S | null>(null);
|
||||
current.current = state;
|
||||
|
||||
useEffect(() => {
|
||||
if (!mine.cards.length) return;
|
||||
try { setState(engine.createDuel(rules, [mine.cards, botDeck(botPool, rules.deckSize, seed)], seed)); }
|
||||
catch (e) { setError(e instanceof Error ? e.message : 'This deck can’t be played.'); }
|
||||
}, [engine, rules, mine.cards, botPool, seed]);
|
||||
|
||||
// The bot moves one atomic action at a time, so the board shows its plays and declarations.
|
||||
useEffect(() => {
|
||||
if (!state || engine.toAct(state) !== BOT) return;
|
||||
const t = setTimeout(() => {
|
||||
const legal = engine.legalActions(state, BOT);
|
||||
if (!legal.length) return;
|
||||
let a: DuelAction;
|
||||
try { a = bot.choose(engine.viewFor(state, BOT), legal, rng.current); } catch { a = legal[0]; }
|
||||
if (!legal.some(l => JSON.stringify(l) === JSON.stringify(a))) a = legal[0];
|
||||
if (current.current !== state) return;
|
||||
const next = engine.applyAction(state, BOT, a);
|
||||
current.current = next;
|
||||
setState(next);
|
||||
}, BOT_STEP_MS);
|
||||
return () => clearTimeout(t);
|
||||
}, [state, engine, bot]);
|
||||
|
||||
// Applied synchronously through a ref, so a confirmed declaration (toggleAttacker × N, confirmAttack)
|
||||
// sees each previous action, and an illegal action throws back to DuelBoard, which shows the error.
|
||||
const onAct = useCallback((a: DuelAction) => {
|
||||
const s = current.current;
|
||||
if (!s) return;
|
||||
const next = engine.applyAction(s, HUMAN, a);
|
||||
current.current = next;
|
||||
setError(undefined);
|
||||
setState(next);
|
||||
}, [engine]);
|
||||
|
||||
const articles = useMemo<Articles>(() => Object.fromEntries(cards.map(c => [c.tokenId, { image: c.imageUrl, url: c.url, extract: c.extract }])), [cards]);
|
||||
|
||||
if (!mine.cards.length) {
|
||||
if (deck.length < rules.deckSize || mine.missing.length) return <DuelGate owned={deck.length - mine.missing.length} deckSize={rules.deckSize} onExit={onExit} onMine={onMine} />;
|
||||
return <section className="duel-gate"><h2>Card profiles pending</h2>
|
||||
<p className="muted">These cards don’t have a duel profile yet, so they can’t be played: {mine.pending.join(', ')}. Pick other cards for your deck, or try again shortly.</p>
|
||||
<div className="play-actions"><button className="button outline" onClick={onExit}>Back</button></div></section>;
|
||||
}
|
||||
if (!state) return error ? <section className="duel-gate"><h2>Can’t start this match</h2><p className="muted">{error}</p>
|
||||
<div className="play-actions"><button className="button outline" onClick={onExit}>Back</button></div></section> : null;
|
||||
|
||||
const view = engine.viewFor(state, HUMAN);
|
||||
return <DuelBoard view={view} legal={engine.legalActions(state, HUMAN)} onAct={onAct} opponentName={`Bot (${bot.name})`} playerName={playerName}
|
||||
logEvents={engine.logFor(state, HUMAN)} articles={articles} busy={engine.toAct(state) === BOT} error={error}
|
||||
onExit={engine.isOver(state) ? () => onFinish() : onExit} />;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { BookMarked, BookOpen, Building2, CalendarClock, Globe2, Home, Hourglass, Languages, Link2, MapPin, Shield, ShieldCheck, Sparkles, Sprout, Star, Swords, TrendingUp, UserRound } from 'lucide-react';
|
||||
import type { BoardCard, DuelCardType } from './model.ts';
|
||||
import { cardSummary, typeLine } from './model.ts';
|
||||
|
||||
const TYPE_ICONS: Record<DuelCardType, typeof UserRound> = {
|
||||
Figure: UserRound, Location: MapPin, Event: CalendarClock, Institution: Building2, Doctrine: BookOpen,
|
||||
};
|
||||
export const TypeIcon = ({ type, size = 12 }: { type: DuelCardType; size?: number }) => {
|
||||
const Icon = TYPE_ICONS[type] ?? BookOpen;
|
||||
return <Icon size={size} aria-hidden="true" />;
|
||||
};
|
||||
|
||||
/** Keyword icons for the board face, where a word doesn't fit 62 px. The words are in the label and the zoom face. */
|
||||
const KEYWORD_ICONS: Record<string, typeof Star> = {
|
||||
protected: ShieldCheck, featured: Star, translated: Languages, legacy: Hourglass, stub: Sprout,
|
||||
'well-sourced': BookMarked, multilingual: Globe2, local: Home, trending: TrendingUp, connected: Link2,
|
||||
};
|
||||
export const KeywordIcon = ({ keyword, size = 11 }: { keyword: string; size?: number }) => {
|
||||
const Icon = KEYWORD_ICONS[keyword.toLowerCase()] ?? Sparkles;
|
||||
return <Icon size={size} aria-hidden="true" />;
|
||||
};
|
||||
|
||||
export type FaceSize = 'board' | 'hand' | 'zoom';
|
||||
export type FaceState = { selected?: boolean; attacking?: boolean; blocking?: boolean; target?: boolean; dim?: boolean; fresh?: boolean };
|
||||
|
||||
const statClass = (now?: number, base?: number) => (now === undefined || base === undefined ? '' : now > base ? 'up' : now < base ? 'down' : '');
|
||||
|
||||
function Stats({ card }: { card: BoardCard }) {
|
||||
if (card.power === undefined) return null;
|
||||
const tough = (card.toughness ?? 0) - (card.damage ?? 0);
|
||||
return <span className="dface-pt" aria-hidden="true">
|
||||
<b className={statClass(card.power, card.basePower)}>{card.power}</b>/<b className={card.damage ? 'down' : statClass(card.toughness, card.baseToughness)}>{tough}</b>
|
||||
</span>;
|
||||
}
|
||||
|
||||
function Art({ card, iconSize }: { card: BoardCard; iconSize: number }) {
|
||||
return <span className="dface-art" aria-hidden="true">
|
||||
{card.image ? <img src={card.image} alt="" loading="lazy" decoding="async" referrerPolicy="no-referrer"
|
||||
onError={e => { e.currentTarget.style.display = 'none'; }} /> : null}
|
||||
<TypeIcon type={card.type} size={iconSize} />
|
||||
</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The duel card face (MTG layout). Board and hand faces show only what fits a phone: title (2-line
|
||||
* clamp), cost, type icon, P/T and keyword chips. Rules text and flavour live in the zoom face,
|
||||
* which the tap-to-zoom sheet shows (critic S4).
|
||||
*/
|
||||
export function DuelCardFace({ card, size = 'hand', state = {}, onClick, label, refNumber }: {
|
||||
card: BoardCard; size?: FaceSize; state?: FaceState; onClick?: () => void; label?: string; refNumber?: number;
|
||||
}) {
|
||||
const cls = ['dface', `dface-${size}`, `portal-${card.portal.toLowerCase()}`,
|
||||
card.tapped && 'is-tapped', card.pending && 'is-pending', state.selected && 'is-selected', state.attacking && 'is-attacking',
|
||||
state.blocking && 'is-blocking', state.target && 'is-target', state.dim && 'is-dim', state.fresh && 'is-fresh', card.token && 'is-token']
|
||||
.filter(Boolean).join(' ');
|
||||
|
||||
if (size === 'zoom') return <article className={cls} aria-label={cardSummary(card)}>
|
||||
<div className="dface-namebar"><h3 className="dface-name">{card.title}</h3><span className="dface-cost" aria-label={`Cost ${card.cost} Citations`}>{card.cost}</span></div>
|
||||
<Art card={card} iconSize={34} />
|
||||
<p className="dface-typeline"><TypeIcon type={card.type} size={13} /> {typeLine(card)}<span className="dface-portal">{card.portal}</span></p>
|
||||
<div className="dface-textbox">
|
||||
{card.keywords.length > 0 && !card.keywords.every(k => card.rulesText.includes(k)) && <p className="dface-keywords">{card.keywords.join('. ')}.</p>}
|
||||
{card.rulesText && <p className="dface-rules">{card.rulesText}</p>}
|
||||
{card.flavour && <p className="dface-flavour">{card.flavour}{card.url
|
||||
? <sup><a href={card.url} target="_blank" rel="noopener noreferrer" aria-label={`Wikipedia article: ${card.title}`}>[{refNumber ?? 1}]</a></sup>
|
||||
: null}</p>}
|
||||
</div>
|
||||
<div className="dface-footer">
|
||||
<span className="dface-rev">{card.revisionId ? `rev. ${card.revisionId}` : card.token ? 'Token' : ''}</span>
|
||||
<Stats card={card} />
|
||||
</div>
|
||||
</article>;
|
||||
|
||||
const kwShown = card.keywords.slice(0, 2);
|
||||
const Tag = onClick ? 'button' : 'div';
|
||||
return <Tag {...(onClick ? { type: 'button' as const, onClick, 'aria-pressed': state.selected || state.attacking || state.blocking || undefined } : { role: 'img' })}
|
||||
className={cls} aria-label={label ?? cardSummary(card)}>
|
||||
<Art card={card} iconSize={size === 'board' ? 14 : 18} />
|
||||
<span className="dface-cost" aria-hidden="true">{card.cost}</span>
|
||||
{state.attacking && <span className="dface-flag attack" aria-hidden="true"><Swords size={11} /></span>}
|
||||
{state.blocking && <span className="dface-flag block" aria-hidden="true"><Shield size={11} /></span>}
|
||||
<span className="dface-title">{card.title}</span>
|
||||
<span className="dface-bottom">
|
||||
{size === 'board' || kwShown.length > 1
|
||||
? kwShown.map(k => <span key={k} className="dface-kwicon" title={k}><KeywordIcon keyword={k} size={10} /></span>)
|
||||
: kwShown.map(k => <span key={k} className="dface-chip">{k}</span>)}
|
||||
<Stats card={card} />
|
||||
</span>
|
||||
</Tag>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Pickaxe } from 'lucide-react';
|
||||
import { eligibility } from './model.ts';
|
||||
import './duel.css';
|
||||
|
||||
/**
|
||||
* Shown instead of a board when the player doesn't own a full deck (BRIEF decisions 1–2). There is
|
||||
* no practice with borrowed cards: the only way forward is mining (or trading) for real cards.
|
||||
*/
|
||||
export function DuelGate({ owned, deckSize, onMine, onExit }: { owned: number; deckSize: number; onMine?: () => void; onExit?: () => void }) {
|
||||
const e = eligibility(owned, deckSize);
|
||||
const pct = Math.round((Math.min(owned, deckSize) / deckSize) * 100);
|
||||
return <section className="duel-gate" aria-labelledby="duel-gate-title">
|
||||
<div className="section-eyebrow">DUEL · {deckSize}-CARD DECKS</div>
|
||||
<h2 id="duel-gate-title">{e.label}</h2>
|
||||
<div className="duel-gate-bar" role="progressbar" aria-valuemin={0} aria-valuemax={deckSize} aria-valuenow={Math.min(owned, deckSize)} aria-label="Cards owned"><i style={{ width: `${pct}%` }} /></div>
|
||||
<p className="muted">A duel deck is exactly {deckSize} cards, and every one is an NFT you own. You need {e.needed} more.
|
||||
Each block you mine is a new card: a random Wikipedia article, frozen with its stats at the moment it was mined.
|
||||
Trades with other players count too. Matches never move or burn your cards.</p>
|
||||
<div className="play-actions">
|
||||
{onExit && <button className="button outline" onClick={onExit}>Back</button>}
|
||||
{onMine && <button className="button dark" onClick={onMine}><Pickaxe size={16} /> Mine cards</button>}
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useState } from 'react';
|
||||
import { DuelCardFace } from './DuelCardFace.tsx';
|
||||
import { DuelTable } from './DuelTable.tsx';
|
||||
import { PREVIEW_POOL, previewView } from './mock.ts';
|
||||
import type { DuelUIAction } from './model.ts';
|
||||
|
||||
type Scene = 'main' | 'attack' | 'block' | 'over' | 'cards';
|
||||
const SCENES: Scene[] = ['main', 'attack', 'block', 'over', 'cards'];
|
||||
const ZOOM = ['Jess Harnell', 'Agda (programming language)', "April 2021 nor'easter", 'Pathrail Mosque', 'Hiroshima Electric Railway', 'Heart rot'];
|
||||
|
||||
/** Static board scenes from card-sample.json, for screenshots and review (`#duel-preview/<scene>`). Not a match. */
|
||||
export function DuelPreview() {
|
||||
const initial = (location.hash.split('/')[1] as Scene) || 'main';
|
||||
const [scene, setScene] = useState<Scene>(SCENES.includes(initial) ? initial : 'main');
|
||||
const [acted, setActed] = useState<string[]>([]);
|
||||
const { view, legal } = previewView(scene === 'cards' ? 'main' : scene);
|
||||
const onAct = (a: DuelUIAction) => setActed(l => [...l, JSON.stringify(a)]);
|
||||
return <div className="duel-preview-page" style={{ padding: 0 }}>
|
||||
<nav className="category-tabs" aria-label="Preview scene" style={{ padding: '4px 8px', display: location.hash.includes('clean') ? 'none' : undefined }}>
|
||||
{SCENES.map(s => <button key={s} className={s === scene ? 'selected' : ''} onClick={() => { setScene(s); location.hash = `duel-preview/${s}`; }}>{s}</button>)}
|
||||
{acted.length > 0 && <small style={{ marginLeft: 8 }}>last action: {acted.at(-1)}</small>}
|
||||
</nav>
|
||||
{scene === 'cards' ? <div className="duel" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))', gap: 16, padding: 12 }}>
|
||||
{ZOOM.map(t => PREVIEW_POOL.find(c => c.title === t)).filter(c => !!c).map((c, i) => <DuelCardFace key={c.id} card={c} size="zoom" refNumber={i + 1} />)}
|
||||
</div> : <DuelTable key={scene} view={{ ...view, log: [...view.log, ...acted.map(a => `(preview) ${a}`)] }} legal={legal} onAct={onAct} />}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Award, Flag, Hand, Library, LoaderCircle, Quote, ScrollText, Shield, Swords, Timer, X } from 'lucide-react';
|
||||
import { DuelCardFace } from './DuelCardFace.tsx';
|
||||
import '../play.css';
|
||||
import './duel.css';
|
||||
import {
|
||||
EMPTY_DECL, blockList, isMyTurn, nextTargets, playerTarget, previewCombat, targetsComplete, tapAttacker, tapBlocker, toggleAttacker,
|
||||
type Attack, type BoardCard, type Seat, type BoardView, type Declaration, type DuelUIAction, type Legal, type SideView,
|
||||
} from './model.ts';
|
||||
|
||||
type Sheet =
|
||||
| { kind: 'card'; card: BoardCard; where: 'hand' | 'mine' | 'theirs' }
|
||||
| { kind: 'combat'; attacks: Attack[]; mode: 'attack' | 'block' }
|
||||
| { kind: 'log' } | { kind: 'concede' } | null;
|
||||
|
||||
const PHASE_LABEL: Record<BoardView['phase'], string> = {
|
||||
mulligan: 'Opening hand', main: 'Main', attack: 'Combat', block: 'Blocks', over: 'Match over',
|
||||
};
|
||||
|
||||
function SideBar({ side, who, active, target, onTarget }: { side: SideView; who: 'me' | 'opponent'; active: boolean; target?: boolean; onTarget?: () => void }) {
|
||||
const label = `${who === 'me' ? 'You' : side.name}: ${side.notability} Notability, ${side.citations} of ${side.maxCitations} Citations, ${side.library} in library, ${side.hand} in hand`;
|
||||
const Tag = target ? 'button' : 'div';
|
||||
return <Tag className={`duel-side ${who} ${active ? 'is-active' : ''} ${target ? 'is-target' : ''}`} {...(target ? { type: 'button' as const, onClick: onTarget } : { role: 'group' })} aria-label={target ? `Target ${who === 'me' ? 'yourself' : side.name}. ${label}` : label}>
|
||||
<span className="duel-side-name">{who === 'me' ? 'You' : side.name}</span>
|
||||
<span className={`duel-stat life ${side.notability <= 5 ? 'low' : ''}`} title="Notability"><Award size={14} aria-hidden="true" /><b>{side.notability}</b></span>
|
||||
<span className="duel-stat cites" title="Citations"><Quote size={13} aria-hidden="true" /><b>{side.citations}</b><small>/{side.maxCitations}</small></span>
|
||||
<span className="duel-stat" title="Library"><Library size={13} aria-hidden="true" />{side.library}</span>
|
||||
<span className="duel-stat" title="Hand"><Hand size={13} aria-hidden="true" />{side.hand}</span>
|
||||
</Tag>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The duel table (presentational), 360 × 740 first. Controllers (local bot, PvP host) feed it a BoardView and the
|
||||
* legal moves, and get DuelUIActions back. Attack: tap a Figure (1 tap). Block: tap your Figure,
|
||||
* then the attacker (2 taps). Both go through a preview → confirm sheet; no drawn arrows.
|
||||
*/
|
||||
export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }: {
|
||||
view: BoardView; legal: Legal; onAct: (a: DuelUIAction) => void; busy?: boolean; error?: string;
|
||||
onExit?: () => void; onRecap?: () => void;
|
||||
}) {
|
||||
const [sheet, setSheet] = useState<Sheet>(null);
|
||||
const [decl, setDecl] = useState<Declaration>(EMPTY_DECL);
|
||||
const [targeting, setTargeting] = useState<{ cardId: string; chosen: string[] }>();
|
||||
const logRef = useRef<HTMLOListElement>(null);
|
||||
// Hand overflow cue (QA #58): how many hand cards are past the right edge.
|
||||
const handRef = useRef<HTMLDivElement>(null);
|
||||
const [hiddenRight, setHiddenRight] = useState(0);
|
||||
useEffect(() => {
|
||||
const el = handRef.current;
|
||||
if (!el) return;
|
||||
const measure = () => {
|
||||
const edge = el.getBoundingClientRect().right;
|
||||
setHiddenRight([...el.children].filter(c => c.getBoundingClientRect().left > edge - 24).length);
|
||||
};
|
||||
measure();
|
||||
el.addEventListener('scroll', measure, { passive: true });
|
||||
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
|
||||
ro?.observe(el);
|
||||
return () => { el.removeEventListener('scroll', measure); ro?.disconnect(); };
|
||||
}, [view.hand.length]);
|
||||
|
||||
const mine = isMyTurn(view);
|
||||
const oppSeat = (1 - view.seat) as Seat;
|
||||
const attackMode = mine && view.phase === 'attack' && !busy;
|
||||
const blockMode = !mine && view.phase === 'block' && view.combat.length > 0 && !busy;
|
||||
const stepKey = `${view.turn}:${view.active}:${view.phase}`;
|
||||
useEffect(() => { setDecl(EMPTY_DECL); setTargeting(undefined); }, [stepKey]);
|
||||
useEffect(() => { logRef.current?.lastElementChild?.scrollIntoView?.({ block: 'nearest' }); }, [view.log.length]);
|
||||
|
||||
const cards = useMemo(() => new Map([...view.me.battlefield, ...view.opponent.battlefield, ...view.hand].map(c => [c.id, c])), [view]);
|
||||
const attackingIds = new Set(view.combat.map(a => a.attackerId));
|
||||
const targets = targeting ? nextTargets(legal.plays[targeting.cardId], targeting.chosen) : null;
|
||||
const refs = useMemo(() => { const m = new Map<string, number>(); for (const c of cards.values()) if (c.url && !m.has(c.url)) m.set(c.url, m.size + 1); return m; }, [cards]);
|
||||
|
||||
const play = (cardId: string, targetIds: string[]) => { setTargeting(undefined); setSheet(null); onAct({ type: 'play', cardId, targetIds }); };
|
||||
const startPlay = (card: BoardCard) => {
|
||||
const seqs = legal.plays[card.id];
|
||||
if (!seqs) return;
|
||||
if (targetsComplete(seqs, [])) play(card.id, []); else { setTargeting({ cardId: card.id, chosen: [] }); setSheet(null); }
|
||||
};
|
||||
const chooseTarget = (id: string) => {
|
||||
if (!targeting || !targets?.has(id)) return;
|
||||
const chosen = [...targeting.chosen, id];
|
||||
if (targetsComplete(legal.plays[targeting.cardId], chosen) && !nextTargets(legal.plays[targeting.cardId], chosen).size) play(targeting.cardId, chosen);
|
||||
else setTargeting({ ...targeting, chosen });
|
||||
};
|
||||
|
||||
const tapMine = (c: BoardCard) => {
|
||||
if (targets) { chooseTarget(c.id); return; }
|
||||
if (attackMode && legal.attackers.includes(c.id)) { setDecl(d => toggleAttacker(d, c.id, legal)); return; }
|
||||
if (blockMode && (legal.blockers[c.id]?.length || decl.blocks[c.id])) { setDecl(d => tapBlocker(d, c.id, legal)); return; }
|
||||
setSheet({ kind: 'card', card: c, where: 'mine' });
|
||||
};
|
||||
const tapTheirs = (c: BoardCard) => {
|
||||
if (targets) { chooseTarget(c.id); return; }
|
||||
if (blockMode && attackingIds.has(c.id) && (decl.picked || Object.values(decl.blocks).includes(c.id))) { setDecl(d => tapAttacker(d, c.id, legal)); return; }
|
||||
setSheet({ kind: 'card', card: c, where: 'theirs' });
|
||||
};
|
||||
|
||||
const blockedBy = (attackerId: string) => Object.entries(decl.blocks).find(([, a]) => a === attackerId)?.[0];
|
||||
const pendingAttacks: Attack[] = attackMode ? decl.attackers.map(attackerId => ({ attackerId }))
|
||||
: blockMode ? view.combat.map(a => ({ attackerId: a.attackerId, blockerId: blockedBy(a.attackerId) })) : view.combat;
|
||||
|
||||
const stateFor = (c: BoardCard, side: 'mine' | 'theirs') => {
|
||||
const t = targets?.has(c.id);
|
||||
if (side === 'mine') return {
|
||||
attacking: attackMode ? decl.attackers.includes(c.id) : attackingIds.has(c.id),
|
||||
blocking: !!decl.blocks[c.id] || view.combat.some(a => a.blockerId === c.id),
|
||||
selected: decl.picked === c.id,
|
||||
target: t,
|
||||
dim: (targets && !t) || (attackMode && c.type === 'Figure' && !legal.attackers.includes(c.id)) || (blockMode && !legal.blockers[c.id]?.length && !decl.blocks[c.id]),
|
||||
};
|
||||
const canBeBlocked = !!decl.picked && !!legal.blockers[decl.picked]?.includes(c.id);
|
||||
return { attacking: attackingIds.has(c.id), target: t || canBeBlocked, blocking: view.combat.some(a => a.blockerId === c.id), dim: (targets && !t) || (!!decl.picked && !canBeBlocked) };
|
||||
};
|
||||
|
||||
const row = (list: BoardCard[], side: 'mine' | 'theirs') => {
|
||||
const top = list.filter(c => !c.attachedTo);
|
||||
return <div className={`duel-row ${side}`} aria-label={side === 'mine' ? 'Your battlefield' : 'Opponent battlefield'}>
|
||||
{top.length ? top.map(c => <div key={c.id} className="duel-slot">
|
||||
<DuelCardFace card={c} size="board" state={stateFor(c, side)} onClick={() => (side === 'mine' ? tapMine(c) : tapTheirs(c))} />
|
||||
{!!c.attachments?.length && <span className="duel-attach" aria-label={`${c.attachments.length} Doctrine attached`}>+{c.attachments.length}</span>}
|
||||
{blockMode && side === 'theirs' && blockedBy(c.id) && <span className="duel-pair" aria-hidden="true">{cards.get(blockedBy(c.id)!)?.title}</span>}
|
||||
</div>) : <span className="duel-empty">No permanents</span>}
|
||||
</div>;
|
||||
};
|
||||
|
||||
// ---------- primary action ----------
|
||||
const nAtt = decl.attackers.length, nBlk = Object.keys(decl.blocks).length;
|
||||
let note: ReactNode = view.log.at(-1) ?? '';
|
||||
let primary: { label: string; run: () => void; disabled?: boolean } | null = null;
|
||||
let secondary: { label: string; run: () => void } | null = null;
|
||||
if (view.phase === 'over') {
|
||||
// The engine's own game-over sentence (DUEL_DESIGN §8.2); the board never writes story text itself.
|
||||
note = <span><b>{view.winner === 'draw' ? 'Draw.' : view.winner === view.seat ? 'You won.' : 'You lost.'}</b> {view.log.at(-1)}</span>;
|
||||
primary = onRecap ? { label: 'Battle recap', run: onRecap } : onExit ? { label: 'Done', run: onExit } : null;
|
||||
if (onRecap && onExit) secondary = { label: 'Done', run: onExit };
|
||||
} else if (busy) {
|
||||
note = <><LoaderCircle className="spin" size={14} /> {mine ? 'Resolving…' : `${view.opponent.name} is choosing…`}</>;
|
||||
} else if (legal.mulligan) {
|
||||
note = 'Keep this hand, or mulligan once: shuffle, draw 7, put 1 on the bottom.';
|
||||
primary = { label: 'Keep hand', run: () => onAct({ type: 'mulligan', keep: true }) };
|
||||
secondary = { label: 'Mulligan', run: () => onAct({ type: 'mulligan', keep: false }) };
|
||||
} else if (targeting) {
|
||||
const c = cards.get(targeting.cardId);
|
||||
note = <>{targeting.chosen.length ? 'Now choose the next target' : 'Choose a target'} for <b>{c?.title}</b>.</>;
|
||||
secondary = { label: 'Cancel', run: () => setTargeting(undefined) };
|
||||
} else if (attackMode) {
|
||||
note = nAtt ? `${nAtt} attacking. Tap a Figure to add or remove it.` : legal.attackers.length ? 'Tap Figures to attack with them.' : 'No Figure can attack.';
|
||||
primary = { label: nAtt ? `Attack with ${nAtt}` : 'No attack', run: () => (nAtt ? setSheet({ kind: 'combat', attacks: pendingAttacks, mode: 'attack' }) : onAct({ type: 'attack', attackerIds: [] })) };
|
||||
} else if (blockMode) {
|
||||
note = decl.picked ? <>Now tap the attacker <b>{cards.get(decl.picked)?.title}</b> blocks.</> : `${view.combat.length} attacking. Tap your Figure, then the attacker it blocks.`;
|
||||
primary = { label: nBlk ? `Review ${nBlk} block${nBlk > 1 ? 's' : ''}` : 'Review: no blocks', run: () => setSheet({ kind: 'combat', attacks: pendingAttacks, mode: 'block' }) };
|
||||
} else if (mine && view.phase === 'main') {
|
||||
note = Object.keys(legal.plays).length ? 'Tap a card in your hand to read or play it.' : note;
|
||||
if (legal.canGoToCombat && legal.attackers.length) { primary = { label: 'Combat', run: () => onAct({ type: 'toCombat' }) }; secondary = legal.canEndTurn ? { label: 'End turn', run: () => onAct({ type: 'endTurn' }) } : null; }
|
||||
else if (legal.canEndTurn) primary = { label: 'End turn', run: () => onAct({ type: 'endTurn' }) };
|
||||
} else if (mine && legal.canEndTurn) {
|
||||
primary = { label: 'End turn', run: () => onAct({ type: 'endTurn' }) };
|
||||
} else if (!mine) {
|
||||
note = <><LoaderCircle className="spin" size={14} /> {view.opponent.name}’s turn.</>;
|
||||
}
|
||||
|
||||
const outcome = sheet?.kind === 'combat' ? previewCombat(sheet.attacks, cards) : null;
|
||||
|
||||
return <section className="duel" aria-label={`Duel against ${view.opponent.name}`}>
|
||||
<header className="duel-bar">
|
||||
<span className="duel-turn">Turn <b>{view.turn}</b> · {PHASE_LABEL[view.phase]}{view.active !== view.seat && view.phase !== 'over' ? ` · ${view.opponent.name}` : ''}</span>
|
||||
{view.clock && view.phase !== 'over' && <span className={`duel-clock ${view.clock.turn <= 10 ? 'low' : ''}`} aria-label={`${view.clock.turn} seconds left this turn, ${view.clock.bank} in the bank`}><Timer size={13} aria-hidden="true" />{view.clock.turn}s<small>+{Math.floor(view.clock.bank / 60)}:{String(view.clock.bank % 60).padStart(2, '0')}</small></span>}
|
||||
<button className="icon-button duel-log-button" onClick={() => setSheet({ kind: 'log' })} aria-label="Match log"><ScrollText size={16} /></button>
|
||||
{view.phase !== 'over' && <button className="icon-button" onClick={() => setSheet({ kind: 'concede' })} aria-label="Concede match"><Flag size={16} /></button>}
|
||||
</header>
|
||||
|
||||
<div className="duel-main">
|
||||
<div className="duel-field">
|
||||
<SideBar side={view.opponent} who="opponent" active={view.active !== view.seat} target={targets?.has(playerTarget(oppSeat))} onTarget={() => chooseTarget(playerTarget(oppSeat))} />
|
||||
{row(view.opponent.battlefield, 'theirs')}
|
||||
<button className="duel-ticker" onClick={() => setSheet({ kind: 'log' })} aria-label="Open match log">
|
||||
{(attackMode || blockMode) && <span className="duel-ticker-phase">{attackMode ? <Swords size={12} /> : <Shield size={12} />}</span>}
|
||||
<span>{view.log.at(-1) ?? 'The match began.'}</span>
|
||||
</button>
|
||||
{row(view.me.battlefield, 'mine')}
|
||||
<SideBar side={view.me} who="me" active={view.active === view.seat} target={targets?.has(playerTarget(view.seat))} onTarget={() => chooseTarget(playerTarget(view.seat))} />
|
||||
</div>
|
||||
<aside className="duel-log-aside" aria-label="Match log">
|
||||
<h3>Log</h3>
|
||||
<ol ref={logRef} className="duel-log">{view.log.map((l, i) => <li key={i}>{l}</li>)}</ol>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<div className="duel-dock">
|
||||
<div className="duel-hand-wrap">
|
||||
<div ref={handRef} className={`duel-hand ${hiddenRight ? 'has-more' : ''}`} aria-label={`Your hand, ${view.hand.length} cards`}>
|
||||
{view.hand.length ? view.hand.map(c => {
|
||||
const playable = !!legal.plays[c.id] && !busy;
|
||||
return <DuelCardFace key={c.id} card={c} size="hand" state={{ dim: !playable || !!targeting, selected: targeting?.cardId === c.id }}
|
||||
onClick={() => setSheet({ kind: 'card', card: c, where: 'hand' })} />;
|
||||
}) : <span className="duel-empty">No cards in hand.</span>}
|
||||
</div>
|
||||
{hiddenRight > 0 && <button type="button" className="duel-hand-more" aria-label={`${hiddenRight} more cards in hand: scroll right`} onClick={() => handRef.current?.scrollBy({ left: handRef.current.clientWidth * 0.8, behavior: 'smooth' })}>+{hiddenRight}</button>}
|
||||
</div>
|
||||
<p className="duel-note" role="status" aria-live="polite">{error ? <span className="dock-error">{error}</span> : note}</p>
|
||||
<div className="duel-actions">
|
||||
{secondary && <button className="button outline" onClick={secondary.run}>{secondary.label}</button>}
|
||||
{primary && <button className="button dark duel-primary" onClick={primary.run} disabled={primary.disabled}>{primary.label}</button>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{sheet && <div className="sheet-backdrop" onClick={e => { if (e.target === e.currentTarget) setSheet(null); }}>
|
||||
<div className={`sheet duel-sheet ${sheet.kind}`} role="dialog" aria-modal="true" aria-label={sheet.kind === 'card' ? sheet.card.title : sheet.kind === 'log' ? 'Match log' : sheet.kind === 'combat' ? 'Combat preview' : 'Concede'}>
|
||||
<button className="modal-close" onClick={() => setSheet(null)} aria-label="Close"><X size={18} /></button>
|
||||
{sheet.kind === 'card' && <>
|
||||
<DuelCardFace card={sheet.card} size="zoom" refNumber={sheet.card.url ? refs.get(sheet.card.url) : undefined} />
|
||||
<p className="muted small duel-sheet-meta">{sheet.where === 'theirs' ? `${view.opponent.name}’s card` : sheet.where === 'hand' ? 'In your hand' : 'Your card'}
|
||||
{sheet.card.tapped ? ' · tapped' : ''}{sheet.card.pending ? ' · Pending review (can’t attack this turn)' : ''}{sheet.card.damage ? ` · ${sheet.card.damage} damage marked` : ''}</p>
|
||||
{sheet.card.connectedNote && <p className="small duel-sheet-meta">Connected: {sheet.card.connectedNote}</p>}
|
||||
{sheet.where === 'hand' && <div className="play-actions">
|
||||
{legal.plays[sheet.card.id] && !busy
|
||||
? <button className="button dark" onClick={() => startPlay(sheet.card)}>{targetsComplete(legal.plays[sheet.card.id], []) ? `Play for ${sheet.card.cost}` : `Play for ${sheet.card.cost}, then choose a target`}</button>
|
||||
: <p className="muted small">{!mine ? 'You can play cards on your turn.' : view.phase !== 'main' ? 'Cards are played in your main phase.' : sheet.card.cost > view.me.citations ? `Needs ${sheet.card.cost} Citations; you have ${view.me.citations}.` : 'No legal target.'}</p>}
|
||||
</div>}
|
||||
</>}
|
||||
{sheet.kind === 'combat' && outcome && <>
|
||||
<h3>{sheet.mode === 'attack' ? 'Declare attackers' : 'Declare blockers'}</h3>
|
||||
<ul className="duel-preview">
|
||||
{outcome.rows.map(r => <li key={r.attacker.id}>
|
||||
<span className={r.attackerDies ? 'gone' : ''}>{r.attacker.title} <small>{r.attacker.power}/{r.attacker.toughness}</small></span>
|
||||
<span className="vs">{r.blocker ? 'blocked by' : sheet.mode === 'attack' ? '→' : 'unblocked →'}</span>
|
||||
{r.blocker ? <span className={r.blockerDies ? 'gone' : ''}>{r.blocker.title} <small>{r.blocker.power}/{r.blocker.toughness}</small></span>
|
||||
: <span>{sheet.mode === 'attack' ? view.opponent.name : 'you'} −{r.attacker.power ?? 0}</span>}
|
||||
</li>)}
|
||||
</ul>
|
||||
<p className="muted small">{sheet.mode === 'attack'
|
||||
? `If unblocked: ${outcome.toPlayer} damage to ${view.opponent.name} (${view.opponent.notability} → ${Math.max(0, view.opponent.notability - outcome.toPlayer)}). ${view.opponent.name} chooses blocks next.`
|
||||
: `You take ${outcome.toPlayer} (${view.me.notability} → ${Math.max(0, view.me.notability - outcome.toPlayer)}).${outcome.destroyed.length ? ` Struck through: destroyed.` : ''}`}</p>
|
||||
<div className="play-actions">
|
||||
<button className="button outline" onClick={() => setSheet(null)}>Change</button>
|
||||
<button className="button dark" onClick={() => { setSheet(null); onAct(sheet.mode === 'attack' ? { type: 'attack', attackerIds: decl.attackers } : { type: 'block', blocks: blockList(decl) }); }}>
|
||||
{sheet.mode === 'attack' ? <><Swords size={15} /> Confirm attack</> : <><Shield size={15} /> Confirm blocks</>}
|
||||
</button>
|
||||
</div>
|
||||
</>}
|
||||
{sheet.kind === 'log' && <><h3>Match log</h3>
|
||||
<ol className="duel-log full">{view.log.map((l, i) => <li key={i}>{l}</li>)}</ol></>}
|
||||
{sheet.kind === 'concede' && <><h3>Concede this match?</h3><p className="muted">It counts as a loss. Nothing on-chain changes.</p>
|
||||
<div className="play-actions"><button className="button outline" onClick={() => setSheet(null)}>Keep playing</button>
|
||||
<button className="button dark" onClick={() => { setSheet(null); onAct({ type: 'concede' }); }}><Flag size={15} /> Concede</button></div></>}
|
||||
</div>
|
||||
</div>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// QA ONLY (branch night2/ui-duel/engine-preview, never merged): a real bot match on duel-core's
|
||||
// engine-wip with duel-cards' derived sample. The player's "deck" is 40 sample cards, because QA has no
|
||||
// wallet here; the real DuelBotMatch only takes owned cards. Route: #duel-live[/<easy|normal>].
|
||||
import sample from '../../../docs/game/duel-card-sample.json';
|
||||
import { duelEngine, DEFAULT_DUEL_RULESET } from '../../../shared/duel/index.ts';
|
||||
import type { DuelCard } from './contract.ts';
|
||||
import { EASY_BOT, NORMAL_BOT } from './bots.ts';
|
||||
import { DuelBotMatch } from './DuelBotMatch.tsx';
|
||||
|
||||
const POOL = (sample as unknown as { cards: DuelCard[] }).cards;
|
||||
const mine = POOL.slice(0, 40);
|
||||
const cards = mine.map(c => ({ tokenId: c.cardId, title: c.title, duel: c }));
|
||||
const botPool = POOL.slice(40);
|
||||
|
||||
export function LivePreview() {
|
||||
const bot = location.hash.includes('easy') ? EASY_BOT : NORMAL_BOT;
|
||||
return <DuelBotMatch deck={cards.map(c => c.tokenId)} cards={cards} engine={duelEngine} rules={DEFAULT_DUEL_RULESET} bot={bot} botPool={botPool}
|
||||
playerName="QA" onExit={() => { location.hash = '#duel-live'; location.reload(); }} onFinish={() => { location.hash = '#duel-live'; location.reload(); }} />;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// duel-core (shared/duel) ↔ the board's view model. The only file that knows engine shapes.
|
||||
import type { DuelAction, LogEvent, PermanentView, PlayerView, Seat, TargetRef } from './contract.ts';
|
||||
import { boardCard, type ArticleBits } from './cards.ts';
|
||||
import type { Attack, BoardCard, BoardView, DuelUIAction, Legal, SideView } from './model.ts';
|
||||
import { NO_LEGAL } from './model.ts';
|
||||
|
||||
export const targetId = (t: TargetRef) => (t.kind === 'card' ? t.uid : `player:${t.seat}`);
|
||||
const targetRef = (id: string): TargetRef => (id.startsWith('player:') ? { kind: 'player', seat: Number(id.slice(7)) as Seat } : { kind: 'card', uid: id });
|
||||
|
||||
export type Articles = Record<string, ArticleBits | undefined>;
|
||||
|
||||
function permanentCard(p: PermanentView, all: PermanentView[], articles: Articles): BoardCard {
|
||||
const keywords: string[] = [...p.keywords];
|
||||
if (p.connected) keywords.push('Connected');
|
||||
return boardCard(p.card, articles[p.card.cardId], {
|
||||
id: p.uid, power: p.card.type === 'Figure' || (p.card.toughness ?? 0) > 0 ? p.power : undefined,
|
||||
toughness: p.card.type === 'Figure' || (p.card.toughness ?? 0) > 0 ? p.toughness : undefined,
|
||||
keywords, tapped: p.tapped, pending: p.card.type === 'Figure' && p.sick, damage: p.damage || undefined,
|
||||
attachedTo: p.attachedTo, attachments: all.filter(x => x.attachedTo === p.uid).map(x => x.uid), token: p.card.token,
|
||||
connectedNote: p.connected ? `${p.connected.tier} (${p.connected.via}): +${p.connected.bonus}/+${p.connected.bonus}` : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
export function boardFromView(v: PlayerView, names: [string, string], log: string[], articles: Articles = {}, clock?: BoardView['clock']): BoardView {
|
||||
const opp = (1 - v.seat) as Seat;
|
||||
const side = (s: PlayerView['opponent'], name: string, seat: Seat): SideView => ({
|
||||
name, notability: s.life, citations: s.citations, maxCitations: s.maxCitations, library: s.librarySize, hand: s.handSize,
|
||||
battlefield: v.battlefield.filter(p => p.controller === seat).map(p => permanentCard(p, v.battlefield, articles)), graveyard: s.graveyard.length,
|
||||
});
|
||||
const blockerOf = Object.fromEntries(Object.entries(v.combat.blocks).map(([b, a]) => [a, b]));
|
||||
const combat: Attack[] = v.combat.attackers.map(a => ({ attackerId: a, blockerId: blockerOf[a] }));
|
||||
return {
|
||||
seat: v.seat, turn: v.turn, active: v.active, phase: v.phase,
|
||||
me: side(v.you, names[v.seat], v.seat), opponent: side(v.opponent, names[opp], opp),
|
||||
hand: v.you.hand.map(i => boardCard(i.card, articles[i.card.cardId], { id: i.uid })),
|
||||
combat, log, winner: v.result ? (v.result.winner ?? 'draw') : undefined, clock,
|
||||
};
|
||||
}
|
||||
|
||||
export function legalFromActions(actions: DuelAction[]): Legal {
|
||||
if (!actions.length) return NO_LEGAL;
|
||||
const legal: Legal = { plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false };
|
||||
for (const a of actions) {
|
||||
switch (a.type) {
|
||||
case 'play': (legal.plays[a.uid] ??= []).push((a.targets ?? []).map(targetId)); break;
|
||||
case 'endPhase': legal.canGoToCombat = true; legal.canEndTurn = true; break;
|
||||
case 'toggleAttacker': legal.attackers.push(a.uid); break;
|
||||
case 'confirmAttack': legal.canEndTurn = true; break;
|
||||
case 'block': (legal.blockers[a.blocker] ??= []).push(a.attacker); break;
|
||||
case 'keep': case 'mulligan': legal.mulligan = true; break;
|
||||
}
|
||||
}
|
||||
return legal;
|
||||
}
|
||||
|
||||
/**
|
||||
* One board intent → duel-core's atomic actions, in send order. Single-step intents return the exact
|
||||
* element of `legal` (so the host's deep-equal check passes); declarations are staged on the board and
|
||||
* sent here as toggle/block × N then confirm (DUEL_API: declarations are monotonic).
|
||||
*/
|
||||
export function expand(ui: DuelUIAction, legal: DuelAction[]): DuelAction[] {
|
||||
const find = (pred: (a: DuelAction) => boolean) => legal.find(pred);
|
||||
switch (ui.type) {
|
||||
case 'mulligan': return [ui.keep ? { type: 'keep' } : { type: 'mulligan' }];
|
||||
case 'play': {
|
||||
const want = ui.targetIds.join('|');
|
||||
const a = find(x => x.type === 'play' && x.uid === ui.cardId && (x.targets ?? []).map(targetId).join('|') === want);
|
||||
return a ? [a] : [{ type: 'play', uid: ui.cardId, ...(ui.targetIds.length ? { targets: ui.targetIds.map(targetRef) } : {}) }];
|
||||
}
|
||||
case 'toCombat': return [{ type: 'endPhase' }];
|
||||
case 'endTurn': return find(x => x.type === 'endPhase') ? [{ type: 'endPhase' }, { type: 'confirmAttack' }] : [{ type: 'confirmAttack' }];
|
||||
case 'attack': return [...ui.attackerIds.map(uid => ({ type: 'toggleAttacker', uid }) as DuelAction), { type: 'confirmAttack' }];
|
||||
case 'block': return [...ui.blocks.map(b => ({ type: 'block', blocker: b.blockerId, attacker: b.attackerId }) as DuelAction), { type: 'confirmBlocks' }];
|
||||
case 'concede': return [{ type: 'concede' }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback log text, used only until duel-design's story renderer (shared/duel/story, DUEL_DESIGN §8.2)
|
||||
* can read engine events. First variant of each §8.2 template, real card and match data only.
|
||||
*/
|
||||
export function plainLog(events: LogEvent[], names: [string, string]): string[] {
|
||||
const out: string[] = [];
|
||||
for (const e of events) {
|
||||
const n = (s: Seat) => names[s];
|
||||
switch (e.kind) {
|
||||
case 'turnStart': out.push(`Turn ${e.turn}.`); break;
|
||||
case 'mulligan': out.push(`${n(e.seat)} took a mulligan.`); break;
|
||||
case 'deploy': out.push(`${n(e.seat)} deployed ${e.card.title}.`); break;
|
||||
case 'cast': out.push(`${n(e.seat)} cited ${e.card.title}.`); break;
|
||||
case 'adopt': out.push(`${e.to.title} adopted ${e.card.title}.`); break;
|
||||
case 'tokenCreated': out.push(`${e.source.title} created ${e.card.title}.`); break;
|
||||
case 'attack': out.push(`${e.attackers.map(a => `${a.title} (${a.power}/${a.toughness})`).join(', ')} attacked.`); break;
|
||||
case 'block': for (const b of e.blocks) out.push(`${b.blocker.title} blocked ${b.attacker.title}.`); break;
|
||||
case 'playerDamage': out.push(`${n(e.seat)} lost ${e.amount} Notability (${e.life} remaining).`); break;
|
||||
case 'lifeGain': out.push(`${n(e.seat)} gained ${e.amount} Notability (${e.life}).`); break;
|
||||
case 'destroyed': out.push(`${e.card.title} was moved to Deleted.`); break;
|
||||
case 'bounced': out.push(`${e.card.title} was returned to ${n(e.owner)}'s hand.`); break;
|
||||
case 'connected': out.push(`${e.card.title} was Connected to ${e.with.title} (${e.tier}).`); break;
|
||||
case 'concede': out.push(`${n(e.seat)} withdrew.`); break;
|
||||
case 'gameOver': out.push(e.winner === null ? `The match ended in a draw on turn ${e.turn}.`
|
||||
: e.reason === 'life' ? `${n((1 - e.winner) as Seat)} was nominated for deletion. The result was delete.`
|
||||
: e.reason === 'library' ? `${n((1 - e.winner) as Seat)} could not draw a card and lost.`
|
||||
: `${n(e.winner)} won on turn ${e.turn}.`); break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// View-only fallback duel bots for the browser bot match. They see only `viewFor` output (Night 1 rule, #5).
|
||||
// sim-balance owns the real duel bots (shared/bots/duel-bots.ts); these are swapped for its heuristic
|
||||
// once a PlayerView lens exists (#64). Deterministic given the rng.
|
||||
import type { DuelAction, PermanentView, PlayerView, Seat } from './contract.ts';
|
||||
import type { DuelBot } from './decks.ts';
|
||||
|
||||
const value = (p: PermanentView) => p.power + p.toughness + p.keywords.length;
|
||||
const opp = (s: Seat) => (1 - s) as Seat;
|
||||
|
||||
function chooseNormal(v: PlayerView, legal: DuelAction[], rng: () => number): DuelAction {
|
||||
const me = v.seat, them = opp(me);
|
||||
const mine = v.battlefield.filter(p => p.controller === me), theirs = v.battlefield.filter(p => p.controller === them);
|
||||
const find = <T extends DuelAction['type']>(t: T) => legal.filter((a): a is Extract<DuelAction, { type: T }> => a.type === t);
|
||||
|
||||
if (find('keep').length) return find('keep')[0];
|
||||
|
||||
const plays = find('play');
|
||||
if (plays.length) {
|
||||
const hand = new Map(v.you.hand.map(i => [i.uid, i.card]));
|
||||
// Prefer the most expensive card. Targets: harmful effects (damage, destroy, bounce, tap, fight, a
|
||||
// negative pump) aim at the opponent's side; everything else (pumps, Adopt) at ours.
|
||||
const owner = (uid: string) => v.battlefield.find(p => p.uid === uid)?.controller;
|
||||
const harmful = (effects: unknown[]) => effects.some(e => {
|
||||
const x = e as { op?: string; power?: number; amount?: number };
|
||||
return ['damage', 'damageEach', 'destroy', 'bounce', 'tap', 'fight', 'drain'].includes(x.op ?? '') || (x.op === 'pump' && ((x.power ?? x.amount ?? 0) < 0));
|
||||
});
|
||||
const score = (a: Extract<DuelAction, { type: 'play' }>) => {
|
||||
const c = hand.get(a.uid);
|
||||
if (!c) return -1;
|
||||
const hostile = harmful(c.effects);
|
||||
let s = c.cost * 10 + rng();
|
||||
for (const t of a.targets ?? []) s += ((t.kind === 'card' ? owner(t.uid) : t.seat) === them) === hostile ? 3 : -3;
|
||||
return s;
|
||||
};
|
||||
return plays.reduce((b, a) => (score(a) > score(b) ? a : b));
|
||||
}
|
||||
|
||||
const toggles = find('toggleAttacker');
|
||||
if (toggles.length || find('confirmAttack').length) {
|
||||
const blockers = theirs.filter(p => !p.tapped && (p.card.type === 'Figure' || p.toughness > 0));
|
||||
const ready = mine.filter(p => v.combat.attackers.includes(p.uid) || toggles.some(t => t.uid === p.uid));
|
||||
const lethal = ready.map(p => p.power).sort((a, b) => b - a).slice(blockers.length).reduce((t, x) => t + x, 0) >= v.opponent.life;
|
||||
const want = toggles.find(t => {
|
||||
const c = mine.find(p => p.uid === t.uid)!;
|
||||
if (v.combat.attackers.includes(c.uid)) return false;
|
||||
if (lethal) return true;
|
||||
return c.power > 0 && !blockers.some(b => b.power >= c.toughness && b.toughness > c.power);
|
||||
});
|
||||
return want ?? find('confirmAttack')[0] ?? legal[0];
|
||||
}
|
||||
|
||||
const blocks = find('block');
|
||||
if (blocks.length || find('confirmBlocks').length) {
|
||||
const used = new Set(Object.keys(v.combat.blocks)), covered = new Set(Object.values(v.combat.blocks));
|
||||
const incoming = v.combat.attackers.filter(a => !covered.has(a)).reduce((t, a) => t + (theirs.find(p => p.uid === a)?.power ?? 0), 0);
|
||||
const lethal = incoming >= v.you.life;
|
||||
let best: DuelAction | undefined, bestScore = 0;
|
||||
for (const b of blocks) {
|
||||
if (used.has(b.blocker) || covered.has(b.attacker)) continue;
|
||||
const B = mine.find(p => p.uid === b.blocker), A = theirs.find(p => p.uid === b.attacker);
|
||||
if (!A || !B) continue;
|
||||
const kills = B.power >= A.toughness, dies = A.power >= B.toughness;
|
||||
const s = kills && !dies ? 10 + value(A) : kills ? (value(A) > value(B) ? 5 : lethal ? 3 : 0) : !dies ? 2 : lethal ? 1 : 0;
|
||||
if (s > bestScore) { bestScore = s; best = b; }
|
||||
}
|
||||
return best ?? find('confirmBlocks')[0] ?? legal[0];
|
||||
}
|
||||
|
||||
return find('endPhase')[0] ?? legal[0];
|
||||
}
|
||||
|
||||
/** Chance that Easy makes a random legal move (never concede) instead of Normal's. */
|
||||
export const EASY_BLUNDER_RATE = 0.3;
|
||||
|
||||
export const NORMAL_BOT: DuelBot = { name: 'Normal', choose: chooseNormal };
|
||||
export const EASY_BOT: DuelBot = {
|
||||
name: 'Easy',
|
||||
choose(v, legal, rng) {
|
||||
if (rng() < EASY_BLUNDER_RATE) return legal[Math.floor(rng() * legal.length)];
|
||||
return chooseNormal(v, legal, rng);
|
||||
},
|
||||
};
|
||||
export const DUEL_BOTS: DuelBot[] = [EASY_BOT, NORMAL_BOT];
|
||||
@@ -0,0 +1,50 @@
|
||||
// DuelCard (duel-cards, shared/duel/derive.ts) → BoardCard. Declared structurally so this file doesn't
|
||||
// depend on an unmerged branch; once shared/duel/derive.ts is on the integration branch, `DuelCardLike`
|
||||
// can become `DuelCard` with no other change.
|
||||
import type { BoardCard, DuelCardType, Portal } from './model.ts';
|
||||
import { firstSentence } from './model.ts';
|
||||
|
||||
export type DuelCardLike = {
|
||||
cardId: string; pageId: number | null; revisionId?: number; title: string; type: DuelCardType; subtype?: string | null;
|
||||
description?: string; token?: boolean;
|
||||
portal: Portal; cost: number; power: number | null; toughness: number | null; keywords: readonly string[];
|
||||
rulesText: string; flavor: string;
|
||||
};
|
||||
|
||||
/** What the chain (not the derivation) knows about the card's article: art and link. */
|
||||
export type ArticleBits = { image?: string; url?: string; extract?: string };
|
||||
|
||||
export const articleUrl = (title: string) => `https://en.wikipedia.org/wiki/${encodeURIComponent(title.replace(/ /g, '_'))}`;
|
||||
|
||||
const SUBTYPE_LABEL: Record<string, string> = {
|
||||
organisation: 'Organisation', work: 'Work', sport: 'Sport', election: 'Election', conflict: 'Conflict', disaster: 'Disaster',
|
||||
period: 'Period', mathematics: 'Mathematics', pathology: 'Pathology', language: 'Language', ideology: 'Ideology', team: 'Team', vehicle: 'Vehicle',
|
||||
};
|
||||
/** "(1909–1994)", "(born 1963)", "(c.1872–1919)" in the description → "1909–1994", "1963–", "1872–1919". */
|
||||
export function lifespan(text: string | undefined): string | undefined {
|
||||
const m = text?.match(/\((?:c\.\s?)?(\d{3,4})\s?[–-]\s?(?:c\.\s?)?(\d{3,4})(?!\d)[^)]*\)|\(born (\d{3,4})\)/);
|
||||
if (!m) return undefined;
|
||||
return m[3] ? `${m[3]}–` : `${m[1]}–${m[2]}`;
|
||||
}
|
||||
|
||||
/** The part after the em dash: "History · 1530–1537", "Society · Election". */
|
||||
export function subtypeLine(card: Pick<DuelCardLike, 'type' | 'subtype' | 'portal' | 'flavor'>): string {
|
||||
const extra = card.type === 'Figure' ? lifespan(card.flavor) : card.subtype ? SUBTYPE_LABEL[card.subtype] : undefined;
|
||||
return extra ? `${card.portal} · ${extra}` : card.portal;
|
||||
}
|
||||
|
||||
export function boardCard(card: DuelCardLike, article: ArticleBits = {}, live: Partial<BoardCard> = {}): BoardCard {
|
||||
// Figures show P/T; Locations only when they have a Garrison (0/T); other types never.
|
||||
const body = card.type === 'Figure' || (card.type === 'Location' && (card.toughness ?? 0) > 0);
|
||||
const power = body ? card.power ?? 0 : undefined, toughness = body ? card.toughness ?? 0 : undefined;
|
||||
return {
|
||||
id: card.cardId, title: card.title, type: card.type,
|
||||
subtype: subtypeLine(card),
|
||||
portal: card.portal, cost: card.cost, power, toughness, basePower: power, baseToughness: toughness,
|
||||
keywords: [...card.keywords], rulesText: card.rulesText,
|
||||
flavour: firstSentence(card.flavor || article.extract || card.description),
|
||||
// Tokens are not articles: no link.
|
||||
image: article.image, url: card.token ? undefined : article.url ?? articleUrl(card.title), revisionId: card.revisionId, token: card.token,
|
||||
...live,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* The part of duel-core's contract (shared/duel/types.ts and index.ts, PR #72 at 7904199) that the
|
||||
* board uses, mirrored so this PR doesn't stack on #72 (HANDBOOK: stub the interface). Field names
|
||||
* and unions are copied verbatim; engine-only details are widened to `unknown`, so real engine values
|
||||
* are assignable here. When #72 is on night/2026-11-17 this file becomes re-exports of shared/duel.
|
||||
*/
|
||||
export type Seat = 0 | 1;
|
||||
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
|
||||
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
|
||||
export type Keyword = 'Protected' | 'Featured' | 'Legacy' | 'Multilingual' | 'Translated' | 'Well-sourced' | 'Stub' | 'Local' | 'Trending';
|
||||
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
|
||||
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
|
||||
export type EndReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap';
|
||||
|
||||
export interface DuelCard {
|
||||
cardId: string;
|
||||
pageId: number | null;
|
||||
revisionId?: number;
|
||||
title: string;
|
||||
description?: string;
|
||||
type: CardType;
|
||||
subtype?: string | null;
|
||||
portal: Portal;
|
||||
cost: number;
|
||||
power: number | null;
|
||||
toughness: number | null;
|
||||
keywords: Keyword[];
|
||||
territory?: number;
|
||||
effects: unknown[];
|
||||
rulesText: string;
|
||||
flavor: string;
|
||||
connect?: unknown;
|
||||
rarity?: 'Common' | 'Rare' | 'Epic' | 'Legendary';
|
||||
deriveVersion?: string;
|
||||
token?: boolean;
|
||||
}
|
||||
|
||||
/** Only deckSize is read here; the engine validates the rest. */
|
||||
export interface DuelRulesetLike { deckSize: number }
|
||||
|
||||
export interface CardInstance { uid: string; owner: Seat; card: DuelCard }
|
||||
export interface CombatState { attackers: string[]; blocks: Record<string, string> }
|
||||
export interface DuelResult { winner: Seat | null; reason: EndReason }
|
||||
|
||||
export type TargetRef = { kind: 'card'; uid: string } | { kind: 'player'; seat: Seat };
|
||||
|
||||
export type DuelAction =
|
||||
| { type: 'keep' }
|
||||
| { type: 'mulligan' }
|
||||
| { type: 'play'; uid: string; targets?: TargetRef[] }
|
||||
| { type: 'endPhase' }
|
||||
| { type: 'toggleAttacker'; uid: string }
|
||||
| { type: 'confirmAttack' }
|
||||
| { type: 'block'; blocker: string; attacker: string }
|
||||
| { type: 'confirmBlocks' }
|
||||
| { type: 'concede' }
|
||||
| { type: 'timeout' };
|
||||
|
||||
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] }
|
||||
| { kind: 'draw'; seat: Seat; card?: CardRef }
|
||||
| { kind: 'deploy'; seat: Seat; card: CardRef }
|
||||
| { kind: 'cast'; seat: Seat; card: CardRef; targets: TargetRef[] }
|
||||
| { kind: 'adopt'; seat: Seat; card: CardRef; to: CardRef }
|
||||
| { kind: 'tokenCreated'; seat: Seat; card: CardRef; source: CardRef }
|
||||
| { kind: 'connected'; seat: Seat; card: CardRef; with: CardRef; tier: ConnectedTier; via: string; bonus: number }
|
||||
| { kind: 'rivalry'; card: CardRef; with: CardRef; tier: ConnectedTier; via: string }
|
||||
| { kind: 'effect'; seat: Seat; source: CardRef; op: string; template?: string; targets: TargetRef[] }
|
||||
| { kind: 'attack'; seat: Seat; attackers: CardRef[] }
|
||||
| { kind: 'block'; seat: Seat; blocks: { blocker: CardRef; attacker: CardRef }[] }
|
||||
| { kind: 'effectDamage'; source: CardRef; target: CardRef; amount: number }
|
||||
| { kind: 'combatDamage'; source: CardRef; target: CardRef; amount: number }
|
||||
| { 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 interface PermanentView {
|
||||
uid: string;
|
||||
owner: Seat;
|
||||
controller: Seat;
|
||||
card: DuelCard;
|
||||
tapped: boolean;
|
||||
sick: boolean;
|
||||
damage: number;
|
||||
counters: number;
|
||||
attachedTo?: string;
|
||||
power: number;
|
||||
toughness: number;
|
||||
keywords: Keyword[];
|
||||
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;
|
||||
toAct: Seat | null;
|
||||
you: SideView & { hand: CardInstance[] };
|
||||
opponent: SideView;
|
||||
battlefield: PermanentView[];
|
||||
combat: CombatState;
|
||||
result: DuelResult | null;
|
||||
version: number;
|
||||
rules: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* The slice of `DuelEngineApi` (shared/duel/index.ts) the bot match calls. Method syntax on purpose:
|
||||
* the real engine (typed on the full DuelState/DuelRuleset/DuelCard) is assignable to it.
|
||||
*/
|
||||
export interface DuelEngineLike<S = unknown, R = unknown> {
|
||||
createDuel(rules: R, decks: [DuelCard[], DuelCard[]], seed: string): S;
|
||||
legalActions(state: S, seat: Seat): DuelAction[];
|
||||
applyAction(state: S, seat: Seat, action: DuelAction): S;
|
||||
toAct(state: S): Seat | null;
|
||||
isOver(state: S): boolean;
|
||||
viewFor(state: S, seat: Seat): PlayerView;
|
||||
logFor(state: S, seat: Seat): LogEvent[];
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Local (in-browser) match driver, engine-agnostic. ./adapter.ts binds it to duel-core's shared/duel.
|
||||
// The bot gets only its own seat's view (viewFor), never the full state (Night 1 rule, #5).
|
||||
import type { BoardView, DuelUIAction, Legal, Seat } from './model.ts';
|
||||
|
||||
/** The engine as the board needs it. `A` is the engine's atomic action; `S` its state. */
|
||||
export interface DuelEnginePort<S, A> {
|
||||
legal(s: S, seat: Seat): A[];
|
||||
apply(s: S, seat: Seat, a: A): S;
|
||||
/** Whose input the engine is waiting for, or null when the match is over. */
|
||||
toAct(s: S): Seat | null;
|
||||
board(s: S, seat: Seat, names: [string, string]): BoardView;
|
||||
legalForBoard(actions: A[], view: BoardView): Legal;
|
||||
/** One board-level intent → the engine's atomic actions, in order. Each must be legal when sent. */
|
||||
expand(ui: DuelUIAction, actions: A[], view: BoardView): A[];
|
||||
}
|
||||
|
||||
export type BotChoose<S, A> = (s: S, seat: Seat, legal: A[], rng: () => number) => A;
|
||||
|
||||
/** Applies a sequence for one seat, re-checking legality at every step. Throws on the first illegal action. */
|
||||
export function applySequence<S, A>(port: DuelEnginePort<S, A>, s: S, seat: Seat, seq: A[], same: (a: A, b: A) => boolean): S {
|
||||
for (const a of seq) {
|
||||
const legal = port.legal(s, seat);
|
||||
if (!legal.some(l => same(l, a))) throw new Error('That move is no longer legal.');
|
||||
s = port.apply(s, seat, a);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Runs bot moves until the human must act or the match ends. Bounded, so a broken bot can't hang the tab. */
|
||||
export function runBot<S, A>(port: DuelEnginePort<S, A>, s: S, human: Seat, choose: BotChoose<S, A>, rng: () => number, maxSteps = 500): S {
|
||||
const bot = (human === 0 ? 1 : 0) as Seat;
|
||||
for (let i = 0; i < maxSteps; i++) {
|
||||
if (port.toAct(s) !== bot) return s;
|
||||
const legal = port.legal(s, bot);
|
||||
if (!legal.length) return s;
|
||||
s = port.apply(s, bot, choose(s, bot, legal, rng));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Stable structural equality for plain JSON actions. */
|
||||
export const sameAction = (a: unknown, b: unknown): boolean => stable(a) === stable(b);
|
||||
const stable = (v: unknown): string => JSON.stringify(v, (_k, x) =>
|
||||
x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([p], [q]) => p.localeCompare(q))) : x);
|
||||
@@ -0,0 +1,40 @@
|
||||
// Pure deck helpers for the bot match (no React, no CSS), so they are unit-tested under Node.
|
||||
import type { DuelAction, DuelCard, PlayerView } from './contract.ts';
|
||||
|
||||
/** A collection card as ui-pvp passes it (ownership's ChainCard satisfies this). `duel` is the server-derived frozen profile. */
|
||||
export type BotMatchCard = { tokenId: string; title: string; url?: string; imageUrl?: string; extract?: string; duel?: unknown };
|
||||
|
||||
const TYPES = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine'];
|
||||
/** Shape check for a profile that arrives untyped over the wire (the engine's validateDeck does the rest). */
|
||||
export function isDuelCard(v: unknown): v is DuelCard {
|
||||
const c = v as Partial<DuelCard> | null;
|
||||
return !!c && typeof c === 'object' && typeof c.title === 'string' && TYPES.includes(c.type as string) && typeof c.cost === 'number'
|
||||
&& Array.isArray(c.keywords) && Array.isArray(c.effects) && typeof c.rulesText === 'string';
|
||||
}
|
||||
/** The bot sees only its own seat's view (Night 1 rule, #5). */
|
||||
export type DuelBot = { name: string; choose(view: PlayerView, legal: DuelAction[], rng: () => number): DuelAction };
|
||||
|
||||
export function mulberry(seed: number) {
|
||||
return () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
|
||||
}
|
||||
export const hash = (s: string) => { let h = 2166136261; for (const c of s) h = Math.imul(h ^ c.charCodeAt(0), 16777619); return h >>> 0; };
|
||||
|
||||
/** The bot's own deck: `size` distinct cards from a pool (the 236 real sample cards), seeded, within the copy limit. */
|
||||
export function botDeck(pool: readonly DuelCard[], size: number, seed: string): DuelCard[] {
|
||||
const rng = mulberry(hash(`bot-deck:${seed}`));
|
||||
const shuffled = [...pool].sort((a, b) => a.cardId.localeCompare(b.cardId));
|
||||
for (let i = shuffled.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; }
|
||||
return shuffled.slice(0, size).map(c => ({ ...c, cardId: `bot:${c.cardId}` }));
|
||||
}
|
||||
|
||||
/** Resolves the player's deck: exactly `deckSize` owned cards, each with a frozen profile. Returns problems instead of a partial deck. */
|
||||
export function playerDeck(deck: string[], cards: BotMatchCard[], deckSize: number): { cards: DuelCard[]; pending: string[]; missing: string[] } {
|
||||
const byId = new Map(cards.map(c => [c.tokenId, c]));
|
||||
const out: DuelCard[] = [], pending: string[] = [], missing: string[] = [];
|
||||
for (const id of deck) {
|
||||
const c = byId.get(id);
|
||||
if (!c) missing.push(id); else if (!isDuelCard(c.duel)) pending.push(c.title); else out.push({ ...c.duel, cardId: id });
|
||||
}
|
||||
return { cards: out.length === deckSize && deck.length === deckSize ? out : [], pending, missing };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/* Duel board (ui-duel, #58). Mobile-first: everything must read at 360 × 740 with a full 5 + 5 board.
|
||||
Portals take MTG colour analogues: Arts red, Earth green, History black, Science blue, Society white. */
|
||||
.duel{--gap:6px;display:flex;flex-direction:column;gap:var(--gap);max-width:1180px;margin:0 auto;padding:6px 8px 0;color:var(--ctp-text);background:var(--ctp-mantle);border:1px solid var(--theme-border);border-radius:12px;min-height:min(100dvh,980px);font-size:13px}
|
||||
.duel button{font:inherit;color:inherit;cursor:pointer}
|
||||
.duel-bar{display:flex;align-items:center;gap:6px;min-height:36px}
|
||||
.duel-turn{font-size:12px;color:var(--ctp-subtext1);margin-right:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.duel-clock{display:inline-flex;align-items:center;gap:3px;font-size:12px;font-variant-numeric:tabular-nums;color:var(--ctp-subtext1)}
|
||||
.duel-clock small{color:var(--ctp-overlay1);font-size:10px}
|
||||
.duel-clock.low{color:var(--ctp-red)}
|
||||
.duel .icon-button{min-width:36px;min-height:36px}
|
||||
|
||||
.duel-main{display:flex;gap:10px;flex:1 1 auto;min-height:0}
|
||||
.duel-field{display:flex;flex-direction:column;gap:var(--gap);flex:1 1 auto;min-width:0}
|
||||
|
||||
/* Player bars: Notability, Citations, library and hand are always visible. */
|
||||
.duel-side{display:flex;align-items:center;gap:10px;padding:5px 8px;border-radius:8px;background:var(--ctp-base);border:1px solid var(--ctp-surface0);font-size:12px;font-variant-numeric:tabular-nums}
|
||||
.duel-side.is-target{width:100%;text-align:left;box-shadow:0 0 0 2px var(--ctp-yellow);animation:dface-pulse 1.1s ease-in-out infinite}
|
||||
.duel-side.is-active{border-color:var(--theme-accent);box-shadow:inset 3px 0 0 var(--theme-accent)}
|
||||
.duel-side-name{font-weight:700;margin-right:auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.duel-stat{display:inline-flex;align-items:center;gap:3px;color:var(--ctp-subtext1)}
|
||||
.duel-stat b{font-size:15px;color:var(--ctp-text)}
|
||||
.duel-stat small{color:var(--ctp-overlay1)}
|
||||
.duel-stat.life svg{color:var(--ctp-yellow)}
|
||||
.duel-stat.life.low b{color:var(--ctp-red)}
|
||||
.duel-stat.cites svg{color:var(--ctp-blue)}
|
||||
|
||||
/* Battlefields: one scrollable row per side; 5 cards fit 344 px without scrolling. */
|
||||
.duel-row{display:flex;gap:4px;overflow-x:auto;overscroll-behavior-x:contain;scrollbar-width:none;min-height:102px;padding:4px 0;align-items:flex-start}
|
||||
.duel-zoomgrid .dface-zoom{align-self:start}
|
||||
.duel-row::-webkit-scrollbar{display:none}
|
||||
.duel-row.theirs{align-items:flex-end}
|
||||
.duel-slot{position:relative;display:flex;flex-direction:column;align-items:stretch;flex:1 1 0;min-width:62px;max-width:110px}
|
||||
.duel-empty{flex:1;align-self:center;text-align:center;font-size:12px;color:var(--ctp-overlay1);padding:8px}
|
||||
.duel-attach{position:absolute;top:-5px;right:-3px;z-index:3;font-size:12px;font-weight:800;padding:1px 5px;border-radius:8px;background:var(--ctp-mauve);color:var(--ctp-crust)}
|
||||
.duel-pair{font-size:9px;line-height:1.2;color:var(--ctp-green);text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:2px}
|
||||
|
||||
.duel-ticker{display:flex;align-items:center;gap:6px;width:100%;min-height:36px;padding:6px 10px;border-radius:8px;background:var(--ctp-crust);border:1px dashed var(--ctp-surface1);text-align:left;font-size:12px;line-height:1.35;color:var(--ctp-subtext1)}
|
||||
.duel-ticker>span:last-child{overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
|
||||
.duel-ticker-phase{display:inline-flex;color:var(--theme-accent);flex:0 0 auto}
|
||||
|
||||
.duel-log-aside{display:none}
|
||||
.duel-log{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px;font-size:13px;line-height:1.5;color:var(--ctp-subtext1)}
|
||||
.duel-log li{padding-left:10px;border-left:2px solid var(--ctp-surface1)}
|
||||
.duel-log li:last-child{border-left-color:var(--theme-accent);color:var(--ctp-text)}
|
||||
.duel-log.full{max-height:60vh;overflow:auto}
|
||||
|
||||
/* Dock: hand, status line, actions. Sticky so the thumb always reaches it. */
|
||||
.duel-dock{position:sticky;bottom:0;z-index:5;margin:0 -8px;padding:6px 8px calc(8px + env(safe-area-inset-bottom));background:var(--ctp-mantle);border-top:1px solid var(--theme-border);border-radius:0 0 12px 12px;display:flex;flex-direction:column;gap:6px}
|
||||
.duel-hand{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;padding:6px 0 2px;min-height:112px}
|
||||
.duel-hand::-webkit-scrollbar{display:none}
|
||||
.duel-hand-wrap{position:relative}
|
||||
.duel-hand.has-more{-webkit-mask-image:linear-gradient(to right,#000 78%,transparent);mask-image:linear-gradient(to right,#000 78%,transparent)}
|
||||
.duel-hand-more{position:absolute;right:0;top:50%;transform:translateY(-50%);min-width:40px;min-height:40px;border-radius:20px;background:var(--ctp-surface1);color:var(--ctp-text);font-weight:800;font-size:13px;box-shadow:0 2px 8px rgb(0 0 0/.4)}
|
||||
.duel-note{margin:0;min-height:18px;font-size:12px;line-height:1.35;color:var(--ctp-subtext1);display:flex;align-items:center;gap:6px}
|
||||
.duel-actions{display:flex;gap:8px;justify-content:flex-end}
|
||||
.duel-actions .button{min-height:46px;font-size:13px;padding:10px 16px}
|
||||
.duel-actions .duel-primary{flex:1 1 auto;max-width:280px}
|
||||
|
||||
/* ---------- card faces ---------- */
|
||||
.dface{--portal:var(--ctp-overlay1);--portal-ink:var(--ctp-crust);position:relative;display:flex;flex-direction:column;align-items:stretch;text-align:left;padding:0;background:var(--ctp-base);color:var(--ctp-text);border:1.5px solid color-mix(in srgb,var(--portal) 65%,var(--ctp-surface1));border-radius:8px;overflow:hidden;transition:transform .15s ease,box-shadow .15s ease,opacity .15s ease}
|
||||
.dface.portal-arts{--portal:var(--ctp-red)}
|
||||
.dface.portal-earth{--portal:var(--ctp-green)}
|
||||
.dface.portal-history{--portal:var(--ctp-surface2);--portal-ink:var(--ctp-text)}
|
||||
.dface.portal-science{--portal:var(--ctp-blue)}
|
||||
.dface.portal-society{--portal:var(--ctp-rosewater)}
|
||||
.dface.portal-neutral{--portal:var(--ctp-overlay0);--portal-ink:var(--ctp-text)}
|
||||
.dface-art{position:relative;display:flex;align-items:center;justify-content:center;height:32px;overflow:hidden;color:var(--portal);background:color-mix(in srgb,var(--portal) 25%,var(--ctp-surface0))}
|
||||
.dface-art img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
|
||||
.dface-art svg{position:relative;opacity:.9}
|
||||
.dface-art:has(img:not([style*="none"])) svg{position:absolute;right:3px;bottom:3px;width:14px;height:14px;padding:2px;border-radius:4px;background:rgb(0 0 0/.55);color:#fff;box-sizing:content-box}
|
||||
.dface-cost{position:absolute;top:3px;left:3px;z-index:2;min-width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:12px;background:var(--ctp-blue);color:var(--ctp-crust);box-shadow:0 1px 3px rgb(0 0 0/.4)}
|
||||
.dface-title{font-size:10.5px;font-weight:700;line-height:1.2;padding:3px 4px 0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;min-height:2.4em;overflow-wrap:break-word;hyphens:auto}
|
||||
.dface-bottom{display:flex;align-items:center;gap:2px;padding:2px 2px 3px;margin-top:auto;min-width:0}
|
||||
.dface-type{display:inline-flex;color:var(--portal);flex:0 0 auto}
|
||||
.dface-kwicon{display:inline-flex;align-items:center;justify-content:center;width:15px;height:16px;border-radius:4px;flex:0 0 auto;background:color-mix(in srgb,var(--portal) 30%,var(--ctp-surface0));color:var(--ctp-text)}
|
||||
.dface-chip{font-size:9px;font-weight:700;padding:1px 3px;border-radius:3px;background:color-mix(in srgb,var(--portal) 30%,var(--ctp-surface0));color:var(--ctp-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
|
||||
.dface-pt{margin-left:auto;flex:0 0 auto;font-size:12px;font-weight:800;padding:0 3px;letter-spacing:-.3px;border-radius:4px;background:var(--ctp-surface0);font-variant-numeric:tabular-nums}
|
||||
.dface-pt .up{color:var(--ctp-green)}.dface-pt .down{color:var(--ctp-red)}
|
||||
.dface-flag{position:absolute;top:3px;right:3px;z-index:2;display:flex;padding:3px;border-radius:50%}
|
||||
.dface-flag.attack{background:var(--ctp-red);color:var(--ctp-crust)}
|
||||
.dface-flag.block{background:var(--ctp-green);color:var(--ctp-crust)}
|
||||
|
||||
.dface-board{width:100%;min-height:90px}
|
||||
.dface-hand{flex:0 0 80px;width:80px;min-height:106px}
|
||||
.dface-hand .dface-art{height:42px}
|
||||
.dface-hand .dface-title{font-size:11px}
|
||||
|
||||
.dface.is-tapped{opacity:.62;filter:saturate(.6)}
|
||||
.dface.is-tapped::after{content:'';position:absolute;inset:0;background:repeating-linear-gradient(135deg,transparent 0 6px,rgb(0 0 0/.12) 6px 8px);pointer-events:none}
|
||||
.dface.is-pending .dface-art{filter:grayscale(.7)}
|
||||
.dface.is-selected{box-shadow:0 0 0 2px var(--theme-accent);transform:translateY(-4px)}
|
||||
.dface.is-attacking{box-shadow:0 0 0 2px var(--ctp-red);transform:translateY(-4px)}
|
||||
.duel-row.theirs .dface.is-attacking{transform:translateY(4px)}
|
||||
.dface.is-blocking{box-shadow:0 0 0 2px var(--ctp-green)}
|
||||
.dface.is-target{box-shadow:0 0 0 2px var(--ctp-yellow);animation:dface-pulse 1.1s ease-in-out infinite}
|
||||
.dface.is-dim{opacity:.42}
|
||||
.dface.is-token{border-style:dashed}
|
||||
.dface.is-fresh{animation:dface-in .4s ease-out}
|
||||
.dface:focus-visible{outline:2px solid var(--theme-accent);outline-offset:2px}
|
||||
@keyframes dface-pulse{50%{box-shadow:0 0 0 4px color-mix(in srgb,var(--ctp-yellow) 55%,transparent)}}
|
||||
@keyframes dface-in{from{transform:scale(.7);opacity:0}to{transform:none;opacity:1}}
|
||||
@media (prefers-reduced-motion:reduce){.dface{transition:none}.dface.is-target,.dface.is-fresh{animation:none}}
|
||||
|
||||
/* Zoom face: the full MTG layout, in the tap-to-zoom sheet. */
|
||||
.dface-zoom{width:min(300px,100%);margin:0 auto;border-width:3px;border-radius:14px;background:color-mix(in srgb,var(--portal) 10%,var(--ctp-base));padding:8px;gap:6px}
|
||||
.dface-namebar{display:flex;align-items:center;gap:8px;padding:4px 8px;border-radius:7px;background:var(--ctp-surface0)}
|
||||
.dface-name{font-family:Georgia,'Times New Roman',serif;font-size:17px !important;font-weight:700;line-height:1.2;margin:0 !important;flex:1 1 auto;min-width:0}
|
||||
.dface-zoom .dface-cost{position:static;min-width:26px;height:26px;font-size:15px}
|
||||
.dface-zoom .dface-art{height:150px;border-radius:6px}
|
||||
.dface-typeline{display:flex;align-items:center;gap:6px;margin:0;padding:4px 8px;border-radius:7px;background:var(--ctp-surface0);font-size:13px !important;font-weight:600}
|
||||
.dface-portal{margin-left:auto;font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;padding:2px 6px;border-radius:4px;background:var(--portal);color:var(--portal-ink)}
|
||||
.dface-textbox{padding:8px 10px;border-radius:7px;background:var(--ctp-crust);display:flex;flex-direction:column;gap:6px;min-height:88px}
|
||||
.dface-textbox p{margin:0;font-size:13.5px !important;line-height:1.45 !important}
|
||||
.dface-keywords{font-weight:700}
|
||||
.dface-flavour{font-family:Georgia,'Times New Roman',serif;font-style:italic;color:var(--ctp-subtext0);border-top:1px solid var(--ctp-surface0);padding-top:6px}
|
||||
.dface-flavour sup a{font-style:normal;font-family:inherit;color:var(--ctp-blue);text-decoration:none;margin-left:1px;padding:4px 2px}
|
||||
.dface-footer{display:flex;align-items:center;gap:6px}
|
||||
.dface-rev{font-size:10px;color:var(--ctp-overlay1);font-variant-numeric:tabular-nums}
|
||||
.dface-zoom .dface-pt{font-size:18px;padding:2px 10px;border:2px solid var(--portal);background:var(--ctp-base)}
|
||||
|
||||
.duel-sheet .duel-sheet-meta{text-align:center;margin:8px 0}
|
||||
.duel-preview{list-style:none;padding:0;margin:8px 0;display:flex;flex-direction:column;gap:6px}
|
||||
.duel-preview li{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px;font-size:14px;padding:8px 10px;border-radius:8px;background:var(--ctp-base)}
|
||||
.duel-preview small{color:var(--ctp-overlay1);font-variant-numeric:tabular-nums}
|
||||
.duel-preview .vs{color:var(--ctp-subtext0);font-size:12px}
|
||||
.duel-preview .gone{text-decoration:line-through;color:var(--ctp-red)}
|
||||
|
||||
/* Eligibility gate */
|
||||
.duel-gate{max-width:560px;margin:0 auto;padding:22px 16px;border:1px solid var(--theme-border);border-radius:12px;background:var(--ctp-mantle);color:var(--ctp-text)}
|
||||
.duel-gate h2{font-size:22px;margin:0 0 8px}
|
||||
.duel-gate-bar{height:10px;border-radius:5px;background:var(--ctp-surface0);overflow:hidden;margin:12px 0 6px}
|
||||
.duel-gate-bar i{display:block;height:100%;background:var(--theme-accent)}
|
||||
|
||||
/* Tall phones (≥ 720 px): give the spare height to the cards, with 3-line titles (QA #58). */
|
||||
@media (max-width:899px) and (min-height:720px){
|
||||
.dface-board{min-height:112px}
|
||||
.dface-board .dface-art{height:42px}
|
||||
.dface-board .dface-title{-webkit-line-clamp:3;min-height:3.6em}
|
||||
.dface-hand{min-height:128px}
|
||||
.dface-hand .dface-art{height:52px}
|
||||
.dface-hand .dface-title{-webkit-line-clamp:3;min-height:3.6em}
|
||||
.duel-hand{min-height:134px}
|
||||
}
|
||||
|
||||
/* Desktop: bigger cards, log always visible beside the field. */
|
||||
@media (min-width:900px){
|
||||
.duel{padding:10px 14px 0;font-size:14px}
|
||||
.duel-log-button{display:none}
|
||||
.duel-log-aside{display:flex;flex-direction:column;flex:0 0 300px;max-height:calc(100dvh - 240px);min-height:380px;padding:10px 12px;border-radius:10px;background:var(--ctp-base);border:1px solid var(--ctp-surface0)}
|
||||
.duel-log-aside h3{font-size:12px;letter-spacing:1px;text-transform:uppercase;color:var(--ctp-subtext0);margin:0 0 8px}
|
||||
.duel-log-aside .duel-log{overflow:auto}
|
||||
.duel-ticker{display:none}
|
||||
.duel-row{justify-content:center;min-height:150px;gap:8px}
|
||||
.duel-slot{min-width:96px;max-width:120px}
|
||||
.dface-board{min-height:140px}
|
||||
.dface-board .dface-art{height:62px}
|
||||
.dface-board .dface-title{font-size:12.5px}
|
||||
.dface-board .dface-chip{font-size:9px}
|
||||
.dface-board .dface-kwicon{width:20px;height:20px}
|
||||
.dface-board .dface-pt{font-size:14px}
|
||||
.dface-board .dface-cost{min-width:24px;height:24px;font-size:13px}
|
||||
.dface-hand{flex-basis:104px;width:104px;min-height:138px}
|
||||
.dface-hand .dface-art{height:60px}
|
||||
.dface-hand .dface-title{font-size:12.5px}
|
||||
.duel-hand{justify-content:center;min-height:146px}
|
||||
.duel-dock{margin:0 -14px;padding:8px 14px 12px}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Preview data for the duel board: real cards from docs/game/card-sample.json, with a deliberately
|
||||
// crude stand-in derivation so the board can be built and screenshotted before duel-cards' real
|
||||
// shared/duel/derive.ts lands. Never used for real matches. No network calls.
|
||||
import sample from '../../../docs/game/card-sample.json';
|
||||
import type { BoardCard, BoardView, DuelCardType, Legal, Portal } from './model.ts';
|
||||
|
||||
type SampleCard = {
|
||||
pageId: number; title: string; description?: string | null; revisionId: number; pageBytes: number; languageCount: number;
|
||||
categories: string[]; instanceOf?: { id: string; label: string }[]; tiers: { attention: number; depth: number; reach: number };
|
||||
};
|
||||
const CARDS = (sample as unknown as { cards: SampleCard[] }).cards;
|
||||
|
||||
function previewType(c: SampleCard): DuelCardType {
|
||||
const labels = (c.instanceOf ?? []).map(i => i.label).join(' ');
|
||||
const d = c.description ?? '';
|
||||
if (c.instanceOf?.some(i => i.id === 'Q5') || /\btaxon\b/.test(labels) || /^(Species|Genus) of/.test(d)) return 'Figure';
|
||||
if (/commune|municipality|village|town|river|settlement|mosque|parish|area/i.test(labels + d)) return 'Location';
|
||||
if (/election|storm|nor.easter|battle|match|final|season|war/i.test(labels + d)) return 'Event';
|
||||
if (/company|band|group|film|team|organi[sz]ation|party/i.test(labels + d)) return 'Institution';
|
||||
return 'Doctrine';
|
||||
}
|
||||
function previewPortal(c: SampleCard, t: DuelCardType): Portal {
|
||||
const s = `${c.description ?? ''} ${c.categories.join(' ')}`;
|
||||
if (/century|deaths|sultan|empire|medieval|monarch|queen|king/i.test(s)) return 'History';
|
||||
if (/mathemat|algebra|programming|gene|disease|scientist|botanist|archaeolog/i.test(s)) return 'Science';
|
||||
if (/actor|singer|film|band|music|novel|television/i.test(s)) return 'Arts';
|
||||
if (/species|genus|river|fungus|plant|orchid|commune|village/i.test(s)) return 'Earth';
|
||||
if (/politic|election|protest|footballer|team|government/i.test(s)) return 'Society';
|
||||
return t === 'Figure' ? 'Society' : t === 'Location' ? 'Earth' : 'Neutral';
|
||||
}
|
||||
const years = (d?: string | null) => d?.match(/\(([^)]*\d{3,4}[^)]*)\)/)?.[1]?.replace(/^(c\.|born )/, '').replace('born ', '');
|
||||
|
||||
export function previewCard(c: SampleCard, suffix = ''): BoardCard {
|
||||
const type = previewType(c), portal = previewPortal(c, type);
|
||||
const fame = Math.round((c.tiers.attention * 2 + c.tiers.depth + c.tiers.reach) / 4);
|
||||
const cost = Math.max(1, Math.min(6, Math.ceil(fame * 0.6)));
|
||||
const keywords: string[] = [];
|
||||
if (c.categories.includes('Living people')) keywords.push('Protected');
|
||||
if (c.tiers.attention >= 9) keywords.push('Featured');
|
||||
if (c.languageCount >= 20 && keywords.length < 2) keywords.push('Translated');
|
||||
if (c.categories.some(x => /\d+ deaths/.test(x)) && keywords.length < 2) keywords.push('Legacy');
|
||||
if ((c.pageBytes < 3000 || c.categories.some(x => /stubs/.test(x))) && keywords.length < 2) keywords.push('Stub');
|
||||
const k = Math.ceil(cost / 2);
|
||||
let power: number | undefined, toughness: number | undefined, rulesText = '';
|
||||
if (type === 'Figure') {
|
||||
const b = 2 * cost + 1, s = Math.min(0.7, Math.max(0.3, c.tiers.attention / (c.tiers.attention + c.tiers.depth || 1)));
|
||||
power = Math.max(1, Math.round(b * s)) - (keywords.length > 1 ? 1 : 0); toughness = Math.max(1, b - Math.round(b * s));
|
||||
} else if (type === 'Location') {
|
||||
power = 0; toughness = 1 + Math.floor(c.tiers.depth / 3);
|
||||
rulesText = `Territory. Garrison 0/${toughness}.`;
|
||||
} else if (type === 'Event') {
|
||||
rulesText = /storm|nor.easter/i.test(c.description ?? '') ? `Deal ${Math.max(1, k - 1)} damage to each Figure and each Location.`
|
||||
: /election/i.test(c.description ?? '') ? `Create ${k} 1/1 Society Figure tokens named Elected Member.`
|
||||
: `Target Figure you control gets +${k}/+0 until end of turn, then fights target Figure you don't control.`;
|
||||
} else if (type === 'Institution') {
|
||||
rulesText = cost >= 4 ? 'At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.' : 'Figures you control with power 2 or less get +1/+0.';
|
||||
} else {
|
||||
rulesText = /disease/i.test(c.description ?? '') ? `Attach to target Figure. It gets −${k}/−${k}.` : `Adopt. Adopted Figure gets +${k}/+${k}.`;
|
||||
}
|
||||
const sub = type === 'Figure' ? [portal, years(c.description)].filter(Boolean).join(' · ') : portal;
|
||||
return {
|
||||
id: `${c.pageId}${suffix}`, title: c.title, type, subtype: sub, portal, cost, power, toughness, basePower: power, baseToughness: toughness,
|
||||
keywords: type === 'Figure' ? keywords.slice(0, 2) : [], rulesText, flavour: c.description ? `${c.description}.` : undefined,
|
||||
url: `https://en.wikipedia.org/wiki/${encodeURIComponent(c.title.replace(/ /g, '_'))}`, revisionId: c.revisionId,
|
||||
};
|
||||
}
|
||||
|
||||
export const PREVIEW_POOL: BoardCard[] = CARDS.map(c => previewCard(c));
|
||||
const byTitle = (t: string) => PREVIEW_POOL.find(c => c.title === t) ?? PREVIEW_POOL[0];
|
||||
const figures = PREVIEW_POOL.filter(c => c.type === 'Figure');
|
||||
|
||||
/** A full 5 + 5 board for screenshots and tests. `scene` picks whose step it is. */
|
||||
export function previewView(scene: 'main' | 'attack' | 'block' | 'over' = 'main'): { view: BoardView; legal: Legal } {
|
||||
const mine = [byTitle('Jess Harnell'), byTitle('Dichromorpha viridis'), byTitle('Salahuddin of Aceh'), byTitle('Pathrail Mosque'), byTitle('Hiroshima Electric Railway')]
|
||||
.map((c, i) => ({ ...c, pending: i === 1 && scene === 'main' }));
|
||||
const theirs = [byTitle('Isabella of Aragon, Queen of Portugal'), byTitle('Miloje Vasić'), figures[12], byTitle('Topusko'), byTitle('Zbyszek Godlewski')]
|
||||
.map((c, i) => ({ ...c, id: `${c.id}-o`, damage: i === 1 ? 1 : 0 }));
|
||||
mine[0] = { ...mine[0], attachments: ['doc-1'], power: (mine[0].power ?? 0) + 2, toughness: (mine[0].toughness ?? 0) + 2 };
|
||||
const hand = [byTitle('Agda (programming language)'), byTitle('April 2021 nor\'easter'), byTitle('Mary Sophie Young'), byTitle('Charmont-en-Beauce'), byTitle('Heart rot'), byTitle('Joseph Ujlaki')];
|
||||
const log = [
|
||||
'Turn 1. Bot (Normal) kept a hand of seven.',
|
||||
'Turn 3. You cited Pathrail Mosque. Maximum Citations rose to 4.',
|
||||
'Turn 4. Isabella of Aragon, Queen of Portugal (6/5) attacked. Dichromorpha viridis (4/2) blocked and was reverted.[2]',
|
||||
'Turn 5. You deployed Jess Harnell. Bot (Normal) lost 3 Notability.',
|
||||
'Turn 6. Miloje Vasić was assigned 1 damage.',
|
||||
];
|
||||
const view: BoardView = {
|
||||
seat: 0, turn: 6, active: scene === 'block' ? 1 : 0, phase: scene === 'main' ? 'main' : scene === 'attack' ? 'attack' : scene === 'block' ? 'block' : 'over',
|
||||
me: { name: 'You', notability: 14, citations: scene === 'main' ? 4 : 1, maxCitations: 6, library: 27, hand: hand.length, battlefield: mine, graveyard: 3 },
|
||||
opponent: { name: 'Bot (Normal)', notability: scene === 'over' ? 0 : 11, citations: 0, maxCitations: 6, library: 26, hand: 4, battlefield: theirs, graveyard: 2 },
|
||||
hand, combat: scene === 'block' ? [{ attackerId: theirs[0].id }, { attackerId: theirs[1].id }, { attackerId: theirs[2].id }] : [],
|
||||
log, winner: scene === 'over' ? 0 : undefined, clock: { turn: 42, bank: 251 },
|
||||
};
|
||||
const myFigs = mine.filter(c => c.type === 'Figure' && !c.pending).map(c => c.id);
|
||||
const legal: Legal = scene === 'main' ? {
|
||||
...emptyLegal(), canGoToCombat: true, canEndTurn: true, attackers: myFigs,
|
||||
plays: Object.fromEntries(hand.filter(c => c.cost <= 4).map(c => [c.id,
|
||||
c.type === 'Doctrine' ? mine.filter(m => m.type === 'Figure').map(m => [m.id])
|
||||
: c.type === 'Event' ? mine.filter(m => m.type === 'Figure').flatMap(m => theirs.filter(t => t.type === 'Figure').map(t => [m.id, t.id])) : [[]]])),
|
||||
} : scene === 'attack' ? { ...emptyLegal(), attackers: myFigs, canEndTurn: true }
|
||||
: scene === 'block' ? { ...emptyLegal(), blockers: Object.fromEntries(mine.filter(c => c.type === 'Figure' || c.type === 'Location').map(c => [c.id, view.combat.map(a => a.attackerId)])) }
|
||||
: emptyLegal();
|
||||
return { view, legal };
|
||||
}
|
||||
const emptyLegal = (): Legal => ({ plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false });
|
||||
@@ -0,0 +1,235 @@
|
||||
// ui-duel (#58): the duel board's own view model. Board components read only these types, so the
|
||||
// engine contract (duel-core, mirrored in ./contract.ts) is mapped in exactly one place: ./adapter.ts.
|
||||
// Nothing here moves cards on-chain; matches are off-chain and never burn or transfer.
|
||||
|
||||
export type DuelCardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
|
||||
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
|
||||
export type Seat = 0 | 1;
|
||||
/** duel-core's phases (refresh, draw, damage and end are automatic). */
|
||||
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
|
||||
|
||||
/** One card as the board shows it. Hidden cards never reach the board (opponent's hand is a count). */
|
||||
export type BoardCard = {
|
||||
id: string;
|
||||
title: string;
|
||||
type: DuelCardType;
|
||||
/** The line after the em dash, e.g. "People · 1961–". */
|
||||
subtype?: string;
|
||||
portal: Portal;
|
||||
cost: number;
|
||||
power?: number;
|
||||
toughness?: number;
|
||||
/** Base stats, to colour buffs and debuffs. */
|
||||
basePower?: number;
|
||||
baseToughness?: number;
|
||||
/** Damage marked this turn. */
|
||||
damage?: number;
|
||||
keywords: string[];
|
||||
rulesText: string;
|
||||
/** First sentence of the on-chain extract. */
|
||||
flavour?: string;
|
||||
image?: string;
|
||||
url?: string;
|
||||
revisionId?: number;
|
||||
tapped?: boolean;
|
||||
/** "Pending review": entered this turn, can't attack. */
|
||||
pending?: boolean;
|
||||
/** Doctrine attached to this card (ids), or the Figure a Doctrine is attached to. */
|
||||
attachments?: string[];
|
||||
attachedTo?: string;
|
||||
token?: boolean;
|
||||
/** Active Connected bonus, e.g. "Compatriot (Portugal): +1/+1". */
|
||||
connectedNote?: string;
|
||||
};
|
||||
|
||||
export type SideView = {
|
||||
name: string;
|
||||
notability: number;
|
||||
citations: number;
|
||||
maxCitations: number;
|
||||
library: number;
|
||||
hand: number;
|
||||
battlefield: BoardCard[];
|
||||
graveyard: number;
|
||||
};
|
||||
|
||||
export type Attack = { attackerId: string; blockerId?: string };
|
||||
|
||||
export type BoardView = {
|
||||
seat: Seat;
|
||||
turn: number;
|
||||
/** Whose turn it is. */
|
||||
active: Seat;
|
||||
phase: Phase;
|
||||
me: SideView;
|
||||
opponent: SideView;
|
||||
hand: BoardCard[];
|
||||
/** Current combat: attackers (opponent's when I'm blocking) and any blocks already declared. */
|
||||
combat: Attack[];
|
||||
log: string[];
|
||||
winner?: Seat | 'draw';
|
||||
/** Seconds left this turn, and in the bank, for the player to act. */
|
||||
clock?: { turn: number; bank: number };
|
||||
};
|
||||
|
||||
/** What the board can ask the controller to do. The adapter turns these into engine actions. */
|
||||
export type DuelUIAction =
|
||||
| { type: 'mulligan'; keep: boolean }
|
||||
/** targetIds: card uids or `player:<seat>`, one per chosen-target effect, in order. */
|
||||
| { type: 'play'; cardId: string; targetIds: string[] }
|
||||
| { type: 'toCombat' }
|
||||
| { type: 'attack'; attackerIds: string[] }
|
||||
| { type: 'block'; blocks: { blockerId: string; attackerId: string }[] }
|
||||
| { type: 'endTurn' }
|
||||
| { type: 'concede' };
|
||||
|
||||
/** What the engine says is legal right now, in board terms. */
|
||||
export type Legal = {
|
||||
/** Hand card id → every legal target sequence ([[]] = needs no target). Absent = can't be played now. */
|
||||
plays: Record<string, string[][]>;
|
||||
canGoToCombat: boolean;
|
||||
/** Figures that may be declared as attackers. */
|
||||
attackers: string[];
|
||||
/** blocker id → attacker ids it may block (Featured, Translated and Garrison are the engine's call). */
|
||||
blockers: Record<string, string[]>;
|
||||
canEndTurn: boolean;
|
||||
mulligan: boolean;
|
||||
};
|
||||
|
||||
export const NO_LEGAL: Legal = { plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false };
|
||||
|
||||
// ---------- targeting (multi-step: e.g. a sport Event picks your Figure, then theirs) ----------
|
||||
|
||||
export const playerTarget = (seat: Seat) => `player:${seat}`;
|
||||
|
||||
/** Ids that may be chosen next, given the targets already chosen for this card. */
|
||||
export function nextTargets(seqs: string[][] | undefined, chosen: string[]): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const q of seqs ?? []) if (q.length > chosen.length && chosen.every((t, i) => q[i] === t)) out.add(q[chosen.length]);
|
||||
return out;
|
||||
}
|
||||
/** True when `chosen` is a complete legal sequence. */
|
||||
export const targetsComplete = (seqs: string[][] | undefined, chosen: string[]) =>
|
||||
!!seqs?.some(q => q.length === chosen.length && q.every((t, i) => t === chosen[i]));
|
||||
|
||||
// ---------- combat declaration (pure, so it is unit-tested) ----------
|
||||
|
||||
/**
|
||||
* Attack: one tap toggles a Figure in or out. Block: tap your blocker (1), then the attacker it
|
||||
* blocks (2). Tapping an assigned blocker again removes it. At most one blocker per attacker and
|
||||
* one attacker per blocker (BRIEF: single blocks).
|
||||
*/
|
||||
export type Declaration = { attackers: string[]; blocks: Record<string, string>; picked?: string };
|
||||
export const EMPTY_DECL: Declaration = { attackers: [], blocks: {} };
|
||||
|
||||
export function toggleAttacker(d: Declaration, id: string, legal: Legal): Declaration {
|
||||
if (!legal.attackers.includes(id)) return d;
|
||||
const attackers = d.attackers.includes(id) ? d.attackers.filter(a => a !== id) : [...d.attackers, id];
|
||||
return { ...d, attackers };
|
||||
}
|
||||
|
||||
/** Tap on one of my cards during blocks. */
|
||||
export function tapBlocker(d: Declaration, blockerId: string, legal: Legal): Declaration {
|
||||
if (d.blocks[blockerId]) { const blocks = { ...d.blocks }; delete blocks[blockerId]; return { ...d, blocks, picked: undefined }; }
|
||||
if (!legal.blockers[blockerId]?.length) return d;
|
||||
return { ...d, picked: d.picked === blockerId ? undefined : blockerId };
|
||||
}
|
||||
|
||||
/** Tap on an attacker during blocks. With a blocker picked, assign it; the attacker's old blocker is freed. */
|
||||
export function tapAttacker(d: Declaration, attackerId: string, legal: Legal): Declaration {
|
||||
const picked = d.picked;
|
||||
if (!picked) {
|
||||
// No blocker picked: tapping a blocked attacker clears its block.
|
||||
const owner = Object.entries(d.blocks).find(([, a]) => a === attackerId)?.[0];
|
||||
if (!owner) return d;
|
||||
const blocks = { ...d.blocks }; delete blocks[owner]; return { ...d, blocks };
|
||||
}
|
||||
if (!legal.blockers[picked]?.includes(attackerId)) return d;
|
||||
const blocks = Object.fromEntries(Object.entries(d.blocks).filter(([, a]) => a !== attackerId));
|
||||
blocks[picked] = attackerId;
|
||||
return { ...d, blocks, picked: undefined };
|
||||
}
|
||||
|
||||
export const blockList = (d: Declaration) => Object.entries(d.blocks).map(([blockerId, attackerId]) => ({ blockerId, attackerId }));
|
||||
|
||||
// ---------- combat preview ----------
|
||||
|
||||
export type CombatOutcome = {
|
||||
/** Damage the defending player takes. */
|
||||
toPlayer: number;
|
||||
/** Card ids that would be destroyed. */
|
||||
destroyed: string[];
|
||||
rows: { attacker: BoardCard; blocker?: BoardCard; attackerDies: boolean; blockerDies: boolean }[];
|
||||
};
|
||||
|
||||
const has = (c: BoardCard | undefined, kw: string) => !!c?.keywords.some(k => k.toLowerCase() === kw.toLowerCase());
|
||||
/** Damage a card takes from one source, after Well-sourced (prevent the first 1 each turn). */
|
||||
const taken = (c: BoardCard, dmg: number) => Math.max(0, dmg - (has(c, 'Well-sourced') && !(c.damage ?? 0) ? 1 : 0));
|
||||
const dies = (c: BoardCard, dmg: number) => c.toughness !== undefined && (c.damage ?? 0) + taken(c, dmg) >= c.toughness && dmg > 0;
|
||||
|
||||
/**
|
||||
* A preview for the confirm sheet: simultaneous damage, single blocks, no trample or first strike
|
||||
* (BRIEF). The engine resolves for real; this is only so the player sees what they are confirming.
|
||||
*/
|
||||
export function previewCombat(attacks: Attack[], cards: Map<string, BoardCard>): CombatOutcome {
|
||||
const out: CombatOutcome = { toPlayer: 0, destroyed: [], rows: [] };
|
||||
for (const { attackerId, blockerId } of attacks) {
|
||||
const attacker = cards.get(attackerId);
|
||||
if (!attacker) continue;
|
||||
const blocker = blockerId ? cards.get(blockerId) : undefined;
|
||||
if (!blocker) { out.toPlayer += attacker.power ?? 0; out.rows.push({ attacker, attackerDies: false, blockerDies: false }); continue; }
|
||||
const attackerDies = dies(attacker, blocker.power ?? 0);
|
||||
const blockerDies = dies(blocker, attacker.power ?? 0);
|
||||
if (attackerDies) out.destroyed.push(attacker.id);
|
||||
if (blockerDies) out.destroyed.push(blocker.id);
|
||||
out.rows.push({ attacker, blocker, attackerDies, blockerDies });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------- eligibility (BRIEF decisions 1–3) ----------
|
||||
|
||||
export const DEFAULT_DECK_SIZE = 40;
|
||||
|
||||
export type Eligibility = { eligible: boolean; owned: number; needed: number; label: string };
|
||||
|
||||
/** Bot and PvP matches are only for players who own a full deck. There is no borrowed-card play. */
|
||||
export function eligibility(owned: number, deckSize = DEFAULT_DECK_SIZE): Eligibility {
|
||||
const needed = Math.max(0, deckSize - owned);
|
||||
return { eligible: needed === 0, owned, needed, label: `${Math.min(owned, deckSize)} / ${deckSize} cards` };
|
||||
}
|
||||
|
||||
// ---------- text helpers ----------
|
||||
|
||||
/**
|
||||
* First sentence of an extract, for flavour text. Doesn't split on initials ("J. R. R."), common
|
||||
* abbreviations or decimals. Falls back to the whole (trimmed) text.
|
||||
*/
|
||||
export function firstSentence(text: string | undefined, max = 220): string | undefined {
|
||||
const t = text?.replace(/\s+/g, ' ').trim();
|
||||
if (!t) return undefined;
|
||||
const re = /[.!?](?=\s+[A-Z0-9"“(])/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(t))) {
|
||||
const before = t.slice(0, m.index);
|
||||
const word = before.split(' ').at(-1) ?? '';
|
||||
if (/^[A-Z]$/.test(word) || /^(Mr|Mrs|Ms|Dr|St|Jr|Sr|No|Mt|Ft|vs|c|ca|approx|e\.g|i\.e|U\.S|U\.K)$/i.test(word)) continue;
|
||||
return clip(t.slice(0, m.index + 1), max);
|
||||
}
|
||||
return clip(t, max);
|
||||
}
|
||||
const clip = (s: string, max: number) => (s.length <= max ? s : `${s.slice(0, max - 1).replace(/\s+\S*$/, '')}…`);
|
||||
|
||||
/** "Figure — People · 1961–" */
|
||||
export const typeLine = (c: Pick<BoardCard, 'type' | 'subtype' | 'portal'>) =>
|
||||
`${c.type} — ${c.subtype ?? c.portal}`;
|
||||
|
||||
/** Accessible one-line summary of a card. */
|
||||
export function cardSummary(c: BoardCard): string {
|
||||
const stats = c.power !== undefined ? `, ${c.power}/${c.toughness ?? 0}` : '';
|
||||
const kw = c.keywords.length ? `, ${c.keywords.join(', ')}` : '';
|
||||
const state = `${c.tapped ? ', tapped' : ''}${c.pending ? ', pending review' : ''}${c.damage ? `, ${c.damage} damage` : ''}`;
|
||||
return `${c.title}, ${typeLine(c)}, cost ${c.cost}${stats}${kw}${state}`;
|
||||
}
|
||||
|
||||
export const isMyTurn = (v: BoardView) => v.active === v.seat && v.phase !== 'over';
|
||||
+12
-8
@@ -1,8 +1,12 @@
|
||||
import './native.ts';
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App.tsx';
|
||||
import './index.css';
|
||||
import './themes.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode><App /></React.StrictMode>);
|
||||
import './native.ts';
|
||||
import React, { Suspense, lazy } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App.tsx';
|
||||
import './index.css';
|
||||
import './themes.css';
|
||||
|
||||
// ui-duel review aid: `#duel-preview` renders static duel board scenes from card-sample.json.
|
||||
const DuelPreview = lazy(() => import('./game/duel/DuelPreview.tsx').then(m => ({ default: m.DuelPreview })));
|
||||
const LivePreview = lazy(() => import('./game/duel/LivePreview.tsx').then(m => ({ default: m.LivePreview })));
|
||||
const root = location.hash.startsWith('#duel-live') ? <Suspense fallback={null}><LivePreview /></Suspense> : location.hash.startsWith('#duel-preview') ? <Suspense fallback={null}><DuelPreview /></Suspense> : <App />;
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode>{root}</React.StrictMode>);
|
||||
|
||||
@@ -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: 60, turn: 11, result: { winner: 1, reason: 'life' }, log: 83, digest: '4f4296d6951a616b' };
|
||||
@@ -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,40 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { DEFAULT_DUEL_RULESET, mergeDuelRuleset, parseDuelRuleset, CARD_TYPES, KEYWORDS } from '../shared/duel/index.ts';
|
||||
import { DEFAULT_RULESET } from '../shared/game/index.ts';
|
||||
|
||||
test('duel default ruleset matches the BRIEF', () => {
|
||||
const rules = parseDuelRuleset({ ...DEFAULT_DUEL_RULESET });
|
||||
assert.equal(rules.deckSize, 40);
|
||||
assert.equal(rules.startingLife, 20);
|
||||
assert.equal(rules.maxCitations, 10);
|
||||
assert.equal(rules.handSize, 7);
|
||||
assert.equal(rules.openingHand, 7);
|
||||
assert.equal(rules.mulligans, 1);
|
||||
assert.equal(rules.libraryEmpty, 'lose');
|
||||
assert.equal(rules.firstPlayerDraws, false);
|
||||
assert.equal(rules.turnSeconds, 60);
|
||||
assert.equal(rules.bankSeconds, 300);
|
||||
assert.equal(rules.turnCap, null);
|
||||
assert.equal(rules.territoryCap, 2);
|
||||
});
|
||||
|
||||
test('duel ruleset merges overrides and rejects unknown keys', () => {
|
||||
assert.equal(mergeDuelRuleset({ deckSize: 20 }).deckSize, 20);
|
||||
assert.equal(mergeDuelRuleset({ turnCap: 30 }).turnCap, 30);
|
||||
assert.throws(() => mergeDuelRuleset({ topicCount: 3 }));
|
||||
assert.throws(() => mergeDuelRuleset({ libraryEmpty: 'shrug' }));
|
||||
assert.throws(() => mergeDuelRuleset({ deckSize: 0 }));
|
||||
assert.throws(() => mergeDuelRuleset([1]));
|
||||
});
|
||||
|
||||
test('Night 1 Edit War rulesets are rejected cleanly', () => {
|
||||
assert.throws(() => parseDuelRuleset(DEFAULT_RULESET));
|
||||
});
|
||||
|
||||
test('card types and keywords are the BRIEF set', () => {
|
||||
assert.deepEqual([...CARD_TYPES], ['Figure', 'Location', 'Event', 'Institution', 'Doctrine']);
|
||||
for (const k of ['Protected', 'Featured', 'Translated', 'Legacy', 'Stub', 'Well-sourced', 'Multilingual', 'Local']) {
|
||||
assert.ok((KEYWORDS as readonly string[]).includes(k), k);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { DuelAction, DuelCard, LogEvent, PermanentView, PlayerView, SideView } from '../src/game/duel/contract.ts';
|
||||
import { boardFromView, expand, legalFromActions, plainLog } from '../src/game/duel/adapter.ts';
|
||||
|
||||
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
|
||||
cardId: id, pageId: 1, revisionId: 100, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2,
|
||||
keywords: [], effects: [], rulesText: '', flavor: 'A thing. More.', ...extra,
|
||||
});
|
||||
const perm = (uid: string, controller: 0 | 1, c: DuelCard, extra: Partial<PermanentView> = {}): PermanentView => ({
|
||||
uid, owner: controller, controller, card: c, tapped: false, sick: false, damage: 0, counters: 0,
|
||||
power: c.power ?? 0, toughness: c.toughness ?? 0, keywords: c.keywords, ...extra,
|
||||
});
|
||||
const side = (seat: 0 | 1, extra: Partial<SideView> = {}): SideView => ({
|
||||
seat, life: 20, citations: 3, maxCitations: 4, handSize: 2, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0, ...extra,
|
||||
});
|
||||
|
||||
function view(): PlayerView {
|
||||
const fig = card('fig', { keywords: ['Legacy'] });
|
||||
return {
|
||||
engine: 'duel', seat: 1, turn: 5, active: 0, phase: 'block', toAct: 1,
|
||||
you: { ...side(1), hand: [{ uid: '1:7', owner: 1, card: card('ev', { type: 'Event', power: null, toughness: null }) }] },
|
||||
opponent: side(0, { life: 12 }),
|
||||
battlefield: [
|
||||
perm('0:1', 0, fig, { tapped: true, power: 4, toughness: 3 }),
|
||||
perm('0:2', 0, card('loc', { type: 'Location', power: 0, toughness: 0 })),
|
||||
perm('1:3', 1, card('mine'), { sick: true, connected: { with: '1:4', tier: 'Compatriot', via: 'Portugal', bonus: 1 } }),
|
||||
perm('1:4', 1, card('gar', { type: 'Location', power: 0, toughness: 3 })),
|
||||
perm('1:5', 1, card('doc', { type: 'Doctrine', power: null, toughness: null }), { attachedTo: '1:3' }),
|
||||
],
|
||||
combat: { attackers: ['0:1'], blocks: {} }, result: null, version: 9, rules: {},
|
||||
};
|
||||
}
|
||||
|
||||
test('PlayerView → board: sides from my seat, current stats, Garrison only when T > 0, attachments, Connected', () => {
|
||||
const b = boardFromView(view(), ['alice', 'bob'], ['Turn 5.']);
|
||||
assert.equal(b.me.name, 'bob');
|
||||
assert.equal(b.opponent.name, 'alice');
|
||||
assert.equal(b.opponent.notability, 12);
|
||||
assert.deepEqual(b.combat, [{ attackerId: '0:1', blockerId: undefined }]);
|
||||
const att = b.opponent.battlefield.find(c => c.id === '0:1')!;
|
||||
assert.equal(att.power, 4); assert.equal(att.basePower, 2); assert.equal(att.tapped, true);
|
||||
assert.equal(b.opponent.battlefield.find(c => c.id === '0:2')!.power, undefined);
|
||||
assert.equal(b.me.battlefield.find(c => c.id === '1:4')!.toughness, 3);
|
||||
const mine = b.me.battlefield.find(c => c.id === '1:3')!;
|
||||
assert.deepEqual(mine.attachments, ['1:5']);
|
||||
assert.ok(mine.keywords.includes('Connected'));
|
||||
assert.equal(mine.pending, true);
|
||||
assert.equal(mine.connectedNote, 'Compatriot (Portugal): +1/+1');
|
||||
assert.equal(b.hand[0].id, '1:7');
|
||||
assert.equal(b.hand[0].flavour, 'A thing.');
|
||||
});
|
||||
|
||||
test('legal actions → board legality, and board intents → atomic action sequences', () => {
|
||||
const legal: DuelAction[] = [
|
||||
{ type: 'block', blocker: '1:3', attacker: '0:1' }, { type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' },
|
||||
];
|
||||
const l = legalFromActions(legal);
|
||||
assert.deepEqual(l.blockers, { '1:3': ['0:1'], '1:4': ['0:1'] });
|
||||
assert.deepEqual(expand({ type: 'block', blocks: [{ blockerId: '1:4', attackerId: '0:1' }] }, legal),
|
||||
[{ type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' }]);
|
||||
|
||||
const main: DuelAction[] = [
|
||||
{ type: 'play', uid: 'h1' },
|
||||
{ type: 'play', uid: 'h2', targets: [{ kind: 'card', uid: 'a' }, { kind: 'card', uid: 'x' }] },
|
||||
{ type: 'play', uid: 'h3', targets: [{ kind: 'player', seat: 0 }] },
|
||||
{ type: 'endPhase' },
|
||||
];
|
||||
const m = legalFromActions(main);
|
||||
assert.deepEqual(m.plays, { h1: [[]], h2: [['a', 'x']], h3: [['player:0']] });
|
||||
assert.equal(m.canGoToCombat, true);
|
||||
// The exact legal element comes back, so the host's deep-equal check passes (no `targets: []`).
|
||||
assert.strictEqual(expand({ type: 'play', cardId: 'h1', targetIds: [] }, main)[0], main[0]);
|
||||
assert.strictEqual(expand({ type: 'play', cardId: 'h3', targetIds: ['player:0'] }, main)[0], main[2]);
|
||||
assert.deepEqual(expand({ type: 'endTurn' }, main), [{ type: 'endPhase' }, { type: 'confirmAttack' }]);
|
||||
assert.deepEqual(expand({ type: 'attack', attackerIds: ['a', 'b'] }, [{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]),
|
||||
[{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]);
|
||||
assert.deepEqual(expand({ type: 'mulligan', keep: true }, [{ type: 'keep' }, { type: 'mulligan' }]), [{ type: 'keep' }]);
|
||||
assert.equal(legalFromActions([]).canEndTurn, false);
|
||||
});
|
||||
|
||||
test('fallback log: real names and titles only, no adjectives', () => {
|
||||
const ref = (title: string) => ({ uid: title, cardId: title, title, pageId: 1, type: 'Figure' as const, power: 3, toughness: 2 });
|
||||
const events: LogEvent[] = [
|
||||
{ seq: 1, turn: 3, kind: 'turnStart', seat: 0, citations: 3, life: [20, 20] },
|
||||
{ seq: 2, turn: 3, kind: 'deploy', seat: 0, card: ref('Cho Yang-ho') },
|
||||
{ seq: 3, turn: 3, kind: 'attack', seat: 0, attackers: [ref('Cho Yang-ho')] },
|
||||
{ seq: 4, turn: 3, kind: 'playerDamage', source: ref('Cho Yang-ho'), seat: 1, amount: 3, life: 17, combat: true },
|
||||
{ seq: 5, turn: 3, kind: 'destroyed', card: ref('Dichromorpha viridis'), owner: 1 },
|
||||
{ seq: 6, turn: 9, kind: 'gameOver', winner: 0, reason: 'life', life: [12, 0] },
|
||||
];
|
||||
assert.deepEqual(plainLog(events, ['Eric', 'Bot (Normal)']), [
|
||||
'Turn 3.', 'Eric deployed Cho Yang-ho.', 'Cho Yang-ho (3/2) attacked.', 'Bot (Normal) lost 3 Notability (17 remaining).',
|
||||
'Dichromorpha viridis was moved to Deleted.', 'Bot (Normal) was nominated for deletion. The result was delete.',
|
||||
]);
|
||||
});
|
||||
|
||||
test('bot match decks: exactly deckSize owned, profiled cards; the bot deck is its own and deterministic', async () => {
|
||||
const { botDeck, playerDeck } = await import('../src/game/duel/decks.ts');
|
||||
const cards = Array.from({ length: 41 }, (_, i) => ({ tokenId: `t${i}`, title: `Card ${i}`, duel: card(`d${i}`, { pageId: i }) }));
|
||||
const ids = cards.slice(0, 40).map(c => c.tokenId);
|
||||
const ok = playerDeck(ids, cards, 40);
|
||||
assert.equal(ok.cards.length, 40);
|
||||
assert.equal(ok.cards[0].cardId, 't0'); // the NFT tokenId, not the profile id
|
||||
assert.equal(playerDeck(ids.slice(0, 39), cards, 40).cards.length, 0); // no partial decks, no filler
|
||||
assert.deepEqual(playerDeck([...ids.slice(0, 39), 'nope'], cards, 40).missing, ['nope']);
|
||||
const noProfile = cards.map((c, i) => (i === 3 ? { tokenId: c.tokenId, title: c.title } : c));
|
||||
assert.deepEqual(playerDeck(ids, noProfile, 40).pending, ['Card 3']);
|
||||
const pool = Array.from({ length: 236 }, (_, i) => card(`s${i}`, { pageId: i }));
|
||||
const a = botDeck(pool, 40, 'seed'), b = botDeck(pool, 40, 'seed');
|
||||
assert.deepEqual(a, b);
|
||||
assert.equal(new Set(a.map(c => c.cardId)).size, 40);
|
||||
assert.ok(a.every(c => c.cardId.startsWith('bot:')));
|
||||
assert.notDeepEqual(botDeck(pool, 40, 'other').map(c => c.cardId), a.map(c => c.cardId));
|
||||
});
|
||||
|
||||
test('bot match: untyped profiles from the wire are shape-checked', async () => {
|
||||
const { playerDeck, isDuelCard } = await import('../src/game/duel/decks.ts');
|
||||
assert.equal(isDuelCard(card('x')), true);
|
||||
assert.equal(isDuelCard({ title: 'x' }), false);
|
||||
assert.equal(isDuelCard(null), false);
|
||||
const cards = Array.from({ length: 40 }, (_, i) => ({ tokenId: `t${i}`, title: `C${i}`, duel: i === 5 ? { junk: true } : card(`d${i}`) }));
|
||||
assert.deepEqual(playerDeck(cards.map(c => c.tokenId), cards, 40).pending, ['C5']);
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EASY_BOT, NORMAL_BOT } from '../src/game/duel/bots.ts';
|
||||
import type { DuelAction, DuelCard, PermanentView, PlayerView } from '../src/game/duel/contract.ts';
|
||||
|
||||
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
|
||||
cardId: id, pageId: 1, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2, keywords: [], effects: [], rulesText: '', flavor: '', ...extra,
|
||||
});
|
||||
const perm = (uid: string, controller: 0 | 1, power: number, toughness: number, extra: Partial<PermanentView> = {}): PermanentView => ({
|
||||
uid, owner: controller, controller, card: card(uid, { power, toughness }), tapped: false, sick: false, damage: 0, counters: 0, power, toughness, keywords: [], ...extra,
|
||||
});
|
||||
const side = (seat: 0 | 1, life = 20) => ({ seat, life, citations: 3, maxCitations: 3, handSize: 0, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0 });
|
||||
const view = (p: Partial<PlayerView>): PlayerView => ({
|
||||
engine: 'duel', seat: 1, turn: 4, active: 1, phase: 'main', toAct: 1, you: { ...side(1), hand: [] }, opponent: side(0),
|
||||
battlefield: [], combat: { attackers: [], blocks: {} }, result: null, version: 1, rules: {}, ...p,
|
||||
});
|
||||
const rng = () => 0.5;
|
||||
|
||||
test('normal bot: plays the priciest card, harmful effects at the opponent', () => {
|
||||
const hand = [{ uid: '1:1', owner: 1 as const, card: card('cheap', { cost: 1 }) },
|
||||
{ uid: '1:2', owner: 1 as const, card: card('bolt', { type: 'Event', cost: 3, power: null, toughness: null, effects: [{ op: 'damage', amount: 3 }] }) }];
|
||||
const v = view({ you: { ...side(1), hand }, battlefield: [perm('0:9', 0, 3, 3), perm('1:8', 1, 2, 2)] });
|
||||
const legal: DuelAction[] = [{ type: 'play', uid: '1:1' },
|
||||
{ type: 'play', uid: '1:2', targets: [{ kind: 'card', uid: '1:8' }] }, { type: 'play', uid: '1:2', targets: [{ kind: 'card', uid: '0:9' }] }, { type: 'endPhase' }];
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[2]);
|
||||
});
|
||||
|
||||
test('normal bot: attacks unless a blocker eats it, all-in on lethal, then confirms', () => {
|
||||
const bf = [perm('1:1', 1, 3, 3), perm('1:2', 1, 1, 1), perm('0:1', 0, 2, 4)];
|
||||
const legal: DuelAction[] = [{ type: 'toggleAttacker', uid: '1:1' }, { type: 'toggleAttacker', uid: '1:2' }, { type: 'confirmAttack' }];
|
||||
// 1:1 (3/3) faces a 2/4 that survives but doesn't kill: attack. 1:2 (1/1) would die to it for nothing.
|
||||
const v = view({ phase: 'attack', battlefield: bf });
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[0]);
|
||||
const after = view({ phase: 'attack', battlefield: bf, combat: { attackers: ['1:1'], blocks: {} } });
|
||||
assert.deepEqual(NORMAL_BOT.choose(after, legal.slice(1), rng), { type: 'confirmAttack' });
|
||||
const lethal = view({ phase: 'attack', battlefield: bf, opponent: side(0, 1), combat: { attackers: ['1:1'], blocks: {} } });
|
||||
assert.deepEqual(NORMAL_BOT.choose(lethal, legal.slice(1), rng), legal[1]);
|
||||
});
|
||||
|
||||
test('normal bot: takes the kill-and-survive block, otherwise no block', () => {
|
||||
const bf = [perm('0:1', 0, 2, 2), perm('1:1', 1, 3, 3), perm('1:2', 1, 1, 1)];
|
||||
const v = view({ phase: 'block', active: 0, battlefield: bf, combat: { attackers: ['0:1'], blocks: {} } });
|
||||
const legal: DuelAction[] = [{ type: 'block', blocker: '1:1', attacker: '0:1' }, { type: 'block', blocker: '1:2', attacker: '0:1' }, { type: 'confirmBlocks' }];
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[0]);
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal.slice(1), rng), { type: 'confirmBlocks' });
|
||||
});
|
||||
|
||||
test('bots always return a listed action and keep their opening hand', () => {
|
||||
const legal: DuelAction[] = [{ type: 'keep' }, { type: 'mulligan' }];
|
||||
assert.deepEqual(NORMAL_BOT.choose(view({ phase: 'mulligan' }), legal, rng), { type: 'keep' });
|
||||
let x = 1; const r = () => ((x = (x * 48271) % 2147483647) / 2147483647);
|
||||
for (let i = 0; i < 50; i++) assert.ok(legal.includes(EASY_BOT.choose(view({ phase: 'mulligan' }), legal, r)));
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
EMPTY_DECL, NO_LEGAL, blockList, cardSummary, eligibility, firstSentence, previewCombat, tapAttacker, tapBlocker, toggleAttacker, typeLine,
|
||||
type BoardCard, type Legal,
|
||||
} from '../src/game/duel/model.ts';
|
||||
import { PREVIEW_POOL, previewView } from '../src/game/duel/mock.ts';
|
||||
|
||||
const fig = (id: string, power: number, toughness: number, extra: Partial<BoardCard> = {}): BoardCard =>
|
||||
({ id, title: id, type: 'Figure', portal: 'Society', cost: 2, power, toughness, keywords: [], rulesText: '', ...extra });
|
||||
|
||||
test('attack declaration: one tap toggles a legal attacker, illegal ones are ignored', () => {
|
||||
const legal: Legal = { ...NO_LEGAL, attackers: ['a', 'b'] };
|
||||
let d = toggleAttacker(EMPTY_DECL, 'a', legal);
|
||||
assert.deepEqual(d.attackers, ['a']);
|
||||
d = toggleAttacker(d, 'z', legal);
|
||||
assert.deepEqual(d.attackers, ['a']);
|
||||
d = toggleAttacker(d, 'b', legal);
|
||||
d = toggleAttacker(d, 'a', legal);
|
||||
assert.deepEqual(d.attackers, ['b']);
|
||||
});
|
||||
|
||||
test('block declaration: two taps per blocker, single blocks, re-tap clears', () => {
|
||||
const legal: Legal = { ...NO_LEGAL, blockers: { x: ['A', 'B'], y: ['A'], z: [] } };
|
||||
let d = tapBlocker(EMPTY_DECL, 'x', legal);
|
||||
assert.equal(d.picked, 'x');
|
||||
d = tapAttacker(d, 'A', legal);
|
||||
assert.deepEqual(blockList(d), [{ blockerId: 'x', attackerId: 'A' }]);
|
||||
assert.equal(d.picked, undefined);
|
||||
// y takes over A; x is freed (at most one blocker per attacker).
|
||||
d = tapAttacker(tapBlocker(d, 'y', legal), 'A', legal);
|
||||
assert.deepEqual(blockList(d), [{ blockerId: 'y', attackerId: 'A' }]);
|
||||
// y can't block B: the tap is ignored and y stays picked.
|
||||
d = tapAttacker(tapBlocker(EMPTY_DECL, 'y', legal), 'B', legal);
|
||||
assert.deepEqual(blockList(d), []);
|
||||
// A blocker with no legal attacker can't be picked.
|
||||
assert.equal(tapBlocker(EMPTY_DECL, 'z', legal).picked, undefined);
|
||||
// Re-tapping an assigned blocker removes the block; so does tapping its attacker with nothing picked.
|
||||
d = tapAttacker(tapBlocker(EMPTY_DECL, 'x', legal), 'B', legal);
|
||||
assert.deepEqual(blockList(tapBlocker(d, 'x', legal)), []);
|
||||
assert.deepEqual(blockList(tapAttacker(d, 'B', legal)), []);
|
||||
// One blocker per attacker, and one attacker per blocker.
|
||||
d = tapAttacker(tapBlocker(d, 'x', legal), 'A', legal);
|
||||
assert.equal(blockList(d).length <= 1, true);
|
||||
});
|
||||
|
||||
test('combat preview: simultaneous damage, single blocks, Well-sourced, marked damage', () => {
|
||||
const cards = new Map([fig('a', 3, 3), fig('b', 2, 2), fig('c', 4, 1), fig('w', 1, 3, { keywords: ['Well-sourced'] }), fig('d', 2, 3, { damage: 1 })].map(c => [c.id, c]));
|
||||
const out = previewCombat([{ attackerId: 'a', blockerId: 'b' }, { attackerId: 'c' }], cards);
|
||||
assert.equal(out.toPlayer, 4);
|
||||
assert.deepEqual(out.destroyed.sort(), ['b']);
|
||||
// Well-sourced prevents the first 1: a 3-power attacker deals 2 to a 1/3, which survives.
|
||||
assert.deepEqual(previewCombat([{ attackerId: 'a', blockerId: 'w' }], cards).destroyed, []);
|
||||
// Damage already marked counts: 2 more kills a 2/3 with 1 damage.
|
||||
assert.deepEqual(previewCombat([{ attackerId: 'b', blockerId: 'd' }], cards).destroyed.sort(), ['b', 'd']);
|
||||
});
|
||||
|
||||
test('eligibility: exactly the deck size, no borrowed cards, progress label', () => {
|
||||
assert.deepEqual(eligibility(23), { eligible: false, owned: 23, needed: 17, label: '23 / 40 cards' });
|
||||
assert.equal(eligibility(40).eligible, true);
|
||||
assert.equal(eligibility(57).label, '40 / 40 cards');
|
||||
assert.equal(eligibility(12, 12).eligible, true); // testnet mode file may lower deckSize
|
||||
});
|
||||
|
||||
test('flavour: first sentence of the extract, not split on initials or abbreviations', () => {
|
||||
assert.equal(firstSentence('J. R. R. Tolkien was an English writer. He wrote books.'), 'J. R. R. Tolkien was an English writer.');
|
||||
assert.equal(firstSentence('St. Georgen am Längsee is a town. It is in Austria.'), 'St. Georgen am Längsee is a town.');
|
||||
assert.equal(firstSentence('Pi is about 3.14 in value. More.'), 'Pi is about 3.14 in value.');
|
||||
assert.equal(firstSentence('No full stop here'), 'No full stop here');
|
||||
assert.equal(firstSentence(''), undefined);
|
||||
assert.ok((firstSentence('word '.repeat(100)) ?? '').length <= 220);
|
||||
});
|
||||
|
||||
test('type line and accessible summary', () => {
|
||||
const c = fig('Barack Obama', 3, 4, { subtype: 'People · 1961–', keywords: ['Protected'], tapped: true });
|
||||
assert.equal(typeLine(c), 'Figure — People · 1961–');
|
||||
assert.equal(cardSummary(c), 'Barack Obama, Figure — People · 1961–, cost 2, 3/4, Protected, tapped');
|
||||
});
|
||||
|
||||
test('preview scenes: a full 5 + 5 board with every card from the real sample', () => {
|
||||
assert.equal(PREVIEW_POOL.length, 236);
|
||||
for (const scene of ['main', 'attack', 'block', 'over'] as const) {
|
||||
const { view } = previewView(scene);
|
||||
assert.equal(view.me.battlefield.length, 5);
|
||||
assert.equal(view.opponent.battlefield.length, 5);
|
||||
}
|
||||
for (const c of PREVIEW_POOL) {
|
||||
assert.ok(c.keywords.length <= 2, c.title);
|
||||
assert.ok(c.cost >= 1 && c.cost <= 6, c.title);
|
||||
}
|
||||
});
|
||||
|
||||
test('DuelCard → board card: type line from real data only, flavour is one sentence', async () => {
|
||||
const { boardCard, lifespan } = await import('../src/game/duel/cards.ts');
|
||||
assert.equal(lifespan('Sultan of Aceh (1530–1537/9)'), '1530–1537');
|
||||
assert.equal(lifespan('American voice actor and singer (born 1963)'), '1963–');
|
||||
assert.equal(lifespan('American botanist (c.1872–1919)'), '1872–1919');
|
||||
assert.equal(lifespan('Species of grasshopper'), undefined);
|
||||
const c = boardCard({ cardId: 't', pageId: 1, revisionId: 9, title: 'Salahuddin of Aceh', type: 'Figure', subtype: null, portal: 'History',
|
||||
cost: 4, power: 4, toughness: 3, keywords: ['Legacy'], rulesText: 'Legacy.', flavor: 'Sultan of Aceh (1530–1537/9). Second sentence.' });
|
||||
assert.equal(typeLine(c), 'Figure — History · 1530–1537');
|
||||
assert.equal(c.flavour, 'Sultan of Aceh (1530–1537/9).');
|
||||
assert.equal(c.url, 'https://en.wikipedia.org/wiki/Salahuddin_of_Aceh');
|
||||
const e = boardCard({ cardId: 'e', pageId: 2, revisionId: 9, title: '1954 Gold Coast general election', type: 'Event', subtype: 'election', portal: 'Society',
|
||||
cost: 4, power: null, toughness: null, keywords: [], rulesText: 'x', flavor: '' });
|
||||
assert.equal(typeLine(e), 'Event — Society · Election');
|
||||
assert.equal(e.power, undefined);
|
||||
});
|
||||
|
||||
test('targeting: multi-step sequences (own Figure, then theirs), players as targets', async () => {
|
||||
const { nextTargets, targetsComplete, playerTarget } = await import('../src/game/duel/model.ts');
|
||||
const seqs = [['a', 'x'], ['a', 'y'], ['b', 'x']];
|
||||
assert.deepEqual([...nextTargets(seqs, [])].sort(), ['a', 'b']);
|
||||
assert.deepEqual([...nextTargets(seqs, ['a'])].sort(), ['x', 'y']);
|
||||
assert.deepEqual([...nextTargets(seqs, ['b'])], ['x']);
|
||||
assert.equal(targetsComplete(seqs, ['a']), false);
|
||||
assert.equal(targetsComplete(seqs, ['a', 'y']), true);
|
||||
assert.equal(targetsComplete([[]], []), true);
|
||||
assert.equal(nextTargets([[playerTarget(1)], ['c']], []).has('player:1'), true);
|
||||
});
|
||||
Reference in New Issue
Block a user