From 5cd0ffb0c9b78e663a7df278b9db2f813cf17172 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:53:15 -0500 Subject: [PATCH 1/3] duel-core: engine alpha (createDuel, legalActions, applyAction, viewFor, logFor, replay, duelEnginePort) Effect interpreter for DUEL_DESIGN T1-T12, keywords, Connected/rivalry, tokens, fight, Doctrines, Garrisons, turnCap, timeouts. Structural clone-on-apply (~0.05 ms/action). Refs #55. Co-Authored-By: Claude Opus 5.5 --- shared/duel/engine.ts | 907 ++++++++++++++++++++++++++++++++ shared/duel/index.ts | 5 + tests/duel-core-effects.test.ts | 152 ++++++ tests/duel-core-engine.test.ts | 209 ++++++++ tests/duel-core-fixtures.ts | 110 ++++ 5 files changed, 1383 insertions(+) create mode 100644 shared/duel/engine.ts create mode 100644 tests/duel-core-effects.test.ts create mode 100644 tests/duel-core-engine.test.ts create mode 100644 tests/duel-core-fixtures.ts diff --git a/shared/duel/engine.ts b/shared/duel/engine.ts new file mode 100644 index 0000000..b7dd247 --- /dev/null +++ b/shared/duel/engine.ts @@ -0,0 +1,907 @@ +/** + * 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 : 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 = 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(); + const pages = new Map(); + 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([...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); + 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 +// (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, +}; diff --git a/shared/duel/index.ts b/shared/duel/index.ts index af9f705..ddf719b 100644 --- a/shared/duel/index.ts +++ b/shared/duel/index.ts @@ -6,6 +6,7 @@ */ 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'; @@ -33,3 +34,7 @@ export interface DuelEngineApi { /** 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; diff --git a/tests/duel-core-effects.test.ts b/tests/duel-core-effects.test.ts new file mode 100644 index 0000000..f54db54 --- /dev/null +++ b/tests/duel-core-effects.test.ts @@ -0,0 +1,152 @@ +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 = {}): 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' }); +}); diff --git a/tests/duel-core-engine.test.ts b/tests/duel-core-engine.test.ts new file mode 100644 index 0000000..b717c5e --- /dev/null +++ b/tests/duel-core-engine.test.ts @@ -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: 'eb83865b9b4e30c9' }; diff --git a/tests/duel-core-fixtures.ts b/tests/duel-core-fixtures.ts new file mode 100644 index 0000000..8c6f692 --- /dev/null +++ b/tests/duel-core-fixtures.ts @@ -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 = { + 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 { + return { cardId: id, pageId: null, title: id, type: 'Figure', portal: 'Society', cost: 1, power, toughness, keywords, effects: [], rulesText: '', flavor: '', ...extra }; +} From 4623930e8f43f12faec324d1f635218cb4365c39 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:08:53 -0500 Subject: [PATCH 2/3] duel-core: secondPlayerCitations ruleset lever (default 0) for first-player balance Co-Authored-By: Claude Opus 5.5 --- docs/game/DUEL_API.md | 2 +- shared/duel/engine.ts | 1 + shared/duel/ruleset.ts | 2 ++ shared/duel/types.ts | 1 + tests/duel-core-effects.test.ts | 9 +++++++++ tests/duel-core-engine.test.ts | 2 +- 6 files changed, 15 insertions(+), 2 deletions(-) diff --git a/docs/game/DUEL_API.md b/docs/game/DUEL_API.md index 511c5eb..5f73396 100644 --- a/docs/game/DUEL_API.md +++ b/docs/game/DUEL_API.md @@ -55,7 +55,7 @@ Built by duel-cards (`derive()`), frozen by the host at match start. Shape agree ## 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. +- 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. diff --git a/shared/duel/engine.ts b/shared/duel/engine.ts index b7dd247..3dba767 100644 --- a/shared/duel/engine.ts +++ b/shared/duel/engine.ts @@ -623,6 +623,7 @@ function startTurn(state: DuelState, seat: Seat): void { 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; } diff --git a/shared/duel/ruleset.ts b/shared/duel/ruleset.ts index 8c7e2a3..2aa7942 100644 --- a/shared/duel/ruleset.ts +++ b/shared/duel/ruleset.ts @@ -18,6 +18,7 @@ export const DuelRulesetSchema = z.object({ 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), @@ -46,6 +47,7 @@ export const DEFAULT_DUEL_RULESET: DuelRuleset = Object.freeze({ handSize: 7, mulligans: 1, firstPlayerDraws: false, + secondPlayerCitations: 0, maxCitations: 10, citationsPerTurn: 1, territoryCap: 2, diff --git a/shared/duel/types.ts b/shared/duel/types.ts index 96e4742..1c81a23 100644 --- a/shared/duel/types.ts +++ b/shared/duel/types.ts @@ -166,6 +166,7 @@ export interface DuelRuleset { 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 diff --git a/tests/duel-core-effects.test.ts b/tests/duel-core-effects.test.ts index f54db54..b59f38d 100644 --- a/tests/duel-core-effects.test.ts +++ b/tests/duel-core-effects.test.ts @@ -150,3 +150,12 @@ test('three consecutive timeouts lose; turnCap decides by Notability', () => { 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'); +}); diff --git a/tests/duel-core-engine.test.ts b/tests/duel-core-engine.test.ts index b717c5e..2f26686 100644 --- a/tests/duel-core-engine.test.ts +++ b/tests/duel-core-engine.test.ts @@ -206,4 +206,4 @@ test('golden match', () => { }); // 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: 'eb83865b9b4e30c9' }; +const GOLDEN = { actions: 60, turn: 11, result: { winner: 1, reason: 'life' }, log: 83, digest: '4f4296d6951a616b' }; From 0eb80d23d7be0a957e46fdf597a01bd6f120cc89 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:12:25 -0500 Subject: [PATCH 3/3] duel-core: balance v1 defaults from sim-balance (#64): secondPlayerCitations 1, turnCap 40 Co-Authored-By: Claude Opus 5.5 --- docs/game/DUEL_API.md | 4 ++-- shared/duel/ruleset.ts | 4 ++-- shared/duel/types.ts | 4 ++-- tests/duel-core-engine.test.ts | 2 +- tests/duel-core-ruleset.test.ts | 3 ++- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/game/DUEL_API.md b/docs/game/DUEL_API.md index 5f73396..c9f8d54 100644 --- a/docs/game/DUEL_API.md +++ b/docs/game/DUEL_API.md @@ -55,13 +55,13 @@ Built by duel-cards (`derive()`), frozen by the host at match start. Shape agree ## 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). +- First player (from the seed) skips their first draw. Balance levers (data only): `firstPlayerDraws`, and `secondPlayerCitations` (extra Citations on the second player's first turn; default 1 from balance v1, #64). - **Turn:** refresh (base max +1 to 10, plus Territory ≤ 2; refill; untap; Pending review ends; Stub and `startOfTurn` triggers) → draw → **main** → **attack** → **block** → damage → end (damage and "until end of turn" clear; discard down to `handSize` 7, **highest cost first**, automatically). - Locations: `locationsPerTurn` (1), can't attack. Garrison Locations (toughness > 0) block as 0-power. - Combat: attack the opponent only; each blocker blocks one attacker, at most one blocker per attacker; simultaneous damage; destroy triggers after all combat damage. No trample, first strike, stack or instants. - **Connected** (engine, from `connect`, tiers in `connectedTiers`): Linked (either `links` contains the other's `pageId`, or either `cites` contains the other's `qid`), Compatriot (shared country), Contemporary (shared century, different types), Kin (shared P31, not Q5/Q16521). A Figure gets the single best bonus among other permanents its controller controls: `+linkedBonus` (2) if Linked, else `+connectedBonus` (1). Logged once (`connected`). Opposing Connected pairs are logged once as `rivalry`. - **Timeouts:** `timeout` passes (mulligan: keep; main/attack: end the turn without attacking; block: confirm current blocks). `timeoutsToConcede` (3) consecutive timeouts by one seat lose (`reason: 'timeout'`). -- `turnCap` (null by default): after that many total turns, higher Notability wins, then higher total power in play, then the second player. +- `turnCap` (default 40 total turns from balance v1, #64; `null` = none): after that many total turns, higher Notability wins, then higher total power in play, then the second player. ## Phases and actions | Phase | Who acts | Listed actions | diff --git a/shared/duel/ruleset.ts b/shared/duel/ruleset.ts index 2aa7942..3094183 100644 --- a/shared/duel/ruleset.ts +++ b/shared/duel/ruleset.ts @@ -47,7 +47,7 @@ export const DEFAULT_DUEL_RULESET: DuelRuleset = Object.freeze({ handSize: 7, mulligans: 1, firstPlayerDraws: false, - secondPlayerCitations: 0, + secondPlayerCitations: 1, // balance v1 (#64): first player 60.1% → 54.7% maxCitations: 10, citationsPerTurn: 1, territoryCap: 2, @@ -62,7 +62,7 @@ export const DEFAULT_DUEL_RULESET: DuelRuleset = Object.freeze({ turnSeconds: 60, bankSeconds: 300, timeoutsToConcede: 3, - turnCap: null, + turnCap: 40, // balance v1 (#64): 3.9% of games decided at the cap }) as DuelRuleset; /** Validate a full ruleset. Throws (ZodError) on anything invalid or unknown. */ diff --git a/shared/duel/types.ts b/shared/duel/types.ts index 1c81a23..7c01e04 100644 --- a/shared/duel/types.ts +++ b/shared/duel/types.ts @@ -166,7 +166,7 @@ export interface DuelRuleset { 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) + secondPlayerCitations: number; // 1 (balance v1): extra Citations on the second player's first turn (designer's "Second Opinion" lever) maxCitations: number; // 10 citationsPerTurn: number; // 1 territoryCap: number; // 2 @@ -181,7 +181,7 @@ export interface DuelRuleset { 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. */ + /** 40 (balance v1); null = none. After this many turns in total, higher Notability wins, then higher power in play, then the second player. */ turnCap: number | null; } diff --git a/tests/duel-core-engine.test.ts b/tests/duel-core-engine.test.ts index 2f26686..d6ede24 100644 --- a/tests/duel-core-engine.test.ts +++ b/tests/duel-core-engine.test.ts @@ -206,4 +206,4 @@ test('golden match', () => { }); // 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' }; +const GOLDEN = { actions: 72, turn: 13, result: { winner: 1, reason: 'life' }, log: 103, digest: 'e8bc8630d6f0ab0a' }; diff --git a/tests/duel-core-ruleset.test.ts b/tests/duel-core-ruleset.test.ts index 5121474..d648610 100644 --- a/tests/duel-core-ruleset.test.ts +++ b/tests/duel-core-ruleset.test.ts @@ -15,7 +15,8 @@ test('duel default ruleset matches the BRIEF', () => { assert.equal(rules.firstPlayerDraws, false); assert.equal(rules.turnSeconds, 60); assert.equal(rules.bankSeconds, 300); - assert.equal(rules.turnCap, null); + assert.equal(rules.turnCap, 40, 'balance v1 (#64)'); + assert.equal(rules.secondPlayerCitations, 1, 'balance v1 (#64)'); assert.equal(rules.territoryCap, 2); });