import type { Ability, Condition, Cost, Duration, Effect, ManaSpec, ObjectSelector, PlayerRef, StaticEffect, Target, TokenSpec, TriggerEvent, Value, Zone, } from '../effects/types.js' import type { ActionOptions, CardDefinition, CombatAttack, CombatBlock, GameObject, GameConfig, ManaColor, ManaPool, MulliganState, PendingChoice, PendingSearch, Phase, PlayerState, StackItem, Step, TargetChoice, } from './types.js' import { CREATURE_TYPES } from './creature-types.js' export class GameError extends Error {} type ResolvedTarget = | { kind: 'player'; id: string } | { kind: 'object'; object: GameObject } | { kind: 'stack'; item: StackItem } interface EventContext { kind: TriggerEvent['kind'] player?: string subject?: GameObject amount?: number counter?: string ordinal?: number mode?: 'gain' | 'lose' recipient?: 'player' | 'creature' | 'permanent' | 'any' combat?: boolean spell?: GameObject spellItem?: StackItem } interface EffectContext { source: GameObject controller: string targets: TargetChoice[] lastTarget?: ResolvedTarget triggerSubject?: GameObject eventPlayer?: string eventAmount?: number x: number mode: number } interface ContinuousEffect { id: string sourceId: string controller: string effect: Extract affectedIds: string[] duration: Duration createdTurn: number } interface ManaCost { generic: number colored: ManaColor[] hybrid: { colors: ManaColor[]; life: number }[] } const MANA_COLORS: ManaColor[] = ['W', 'U', 'B', 'R', 'G', 'C'] const COLOR_NAMES: Record = { white: 'W', blue: 'U', black: 'B', red: 'R', green: 'G', colorless: 'C', } function emptyPool(): ManaPool { return { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 } } function parseManaCost(symbols: string, x = 0): ManaCost { const cost: ManaCost = { generic: 0, colored: [], hybrid: [] } for (const match of symbols.matchAll(/\{([^}]+)\}/g)) { const symbol = match[1].toUpperCase() if (/^\d+$/.test(symbol)) { cost.generic += Number(symbol) } else if (symbol === 'X') { cost.generic += x } else if (symbol === 'S') { cost.colored.push('C') } else if (/^[WUBRGC]$/.test(symbol)) { cost.colored.push(symbol as ManaColor) } else if (symbol.includes('/')) { const parts = symbol.split('/') const colors = parts .filter(part => /^[WUBRG]$/.test(part)) .map(part => part as ManaColor) if (colors.length) cost.hybrid.push({ colors, life: parts.includes('P') ? 2 : 0 }) else cost.generic += 1 } else { cost.generic += 1 } } return cost } interface CostReduction { generic: number colored: ManaColor[] } /** * Generic reductions only remove generic mana; colored ones remove matching pips. * shortcut: hybrid and phyrexian pips are not reduced; upgrade when a card needs it. */ function reduceManaSymbols(symbols: string, reduction: CostReduction): string { let generic = reduction.generic const colored = [...reduction.colored] const result: string[] = [] for (const match of symbols.matchAll(/\{([^}]+)\}/g)) { const symbol = match[1].toUpperCase() if (/^\d+$/.test(symbol) && generic > 0) { const remaining = Math.max(0, Number(symbol) - generic) generic = Math.max(0, generic - Number(symbol)) if (remaining > 0) result.push(`{${remaining}}`) continue } const index = colored.indexOf(symbol as ManaColor) if (index >= 0) { colored.splice(index, 1) continue } result.push(`{${match[1]}}`) } return result.join('') } function manaValueOf(definition: CardDefinition): number { if (definition.manaValue !== undefined) return definition.manaValue const cost = parseManaCost(definition.manaCost ?? '') return cost.generic + cost.colored.length + cost.hybrid.length } function colorOfSymbol(symbol: string): ManaColor { const bare = symbol.replace(/[{}]/g, '').toUpperCase() if (bare === 'S') return 'C' if (/^[WUBRGC]$/.test(bare)) return bare as ManaColor return 'C' } function tokenCard(token: { types: string[]; subtypes: string[]; name?: string; colors: string[]; power?: number; toughness?: number; keywords?: string[] }): CardDefinition { return { oracleId: `token:${token.name ?? (token.subtypes.join(' ') || token.types.join(' '))}`, name: token.name ?? (token.subtypes.map(word => word[0]?.toUpperCase() + word.slice(1)).join(' ') || 'Token'), typeLine: [token.types.join(' '), token.subtypes.length ? `— ${token.subtypes.join(' ')}` : ''].join(' ').trim(), manaValue: 0, colors: token.colors, power: token.power, toughness: token.toughness, abilities: (token.keywords ?? []).map(keyword => ({ kind: 'keyword', keyword })), } } /** * A deliberately small but real Magic rules engine: zones, priority, the stack, * turn phases, combat, state-based actions, mana, triggered/activated/static * abilities, and an interpreter for the compiled card-effect AST. */ export class Game { readonly players: PlayerState[] readonly objects = new Map() readonly stack: StackItem[] = [] readonly log: string[] = [] turn = 0 activePlayer = '' phase: Phase = 'beginning' step: Step = 'untap' priority = '' status: 'not_started' | 'mulligan' | 'active' | 'finished' = 'not_started' winner?: string /** Opening-hand choices, keyed by player id. */ readonly mulligans = new Map() /** Blocks all other actions until the searching player picks a card. */ pendingSearch?: PendingSearch /** "As this enters, choose..." prompts, in entry order. */ readonly pendingChoices: PendingChoice[] = [] get pendingChoice(): PendingChoice | undefined { return this.pendingChoices[0] } private readonly config: GameConfig private readonly rng: () => number private readonly startingHandSize: number private readonly firstPlayer: string private readonly continuousEffects: ContinuousEffect[] = [] private passesInRow = 0 private blockersDeclared = new Set() private nextId = 0 private autoManaDepth = 0 private autoAdvanceDepth = 0 private statDepth = 0 private keywordDepth = 0 private combatDamageDone = false constructor(config: GameConfig) { if (config.players.length < 2) throw new GameError('A game needs at least two players') const ids = new Set(config.players.map(player => player.id)) if (ids.size !== config.players.length) throw new GameError('Player ids must be unique') this.config = config this.startingHandSize = config.startingHandSize ?? 7 this.firstPlayer = config.firstPlayer ?? config.players[0].id if (!ids.has(this.firstPlayer)) throw new GameError(`Unknown first player: ${this.firstPlayer}`) this.rng = config.seed === undefined ? Math.random : mulberry32(config.seed) const startingLife = config.startingLife ?? 40 this.players = config.players.map(player => ({ id: player.id, name: player.name ?? player.id, life: player.life ?? startingLife, lost: false, manaPool: emptyPool(), library: [], hand: [], graveyard: [], exile: [], battlefield: [], command: [], commanderDamage: {}, commanderCasts: {}, landPlayedThisTurn: false, cardsDrawnThisTurn: 0, lifeGainedThisTurn: 0, spellsCastThisTurn: 0, creaturesDiedThisTurn: 0, nonlandPermanentsEnteredThisTurn: 0, attackedThisTurn: false, creaturesAttackedThisTurn: 0, damageTakenThisTurn: 0, energy: 0, poison: 0, })) for (const player of this.players) { this.mulligans.set(player.id, { count: 0, kept: false, bottom: 0 }) } for (const playerConfig of config.players) { for (const definition of playerConfig.deck) { const object = this.createObject(definition, playerConfig.id) this.getPlayer(playerConfig.id).library.push(object.id) } if (config.commander && playerConfig.commander) { const commander = this.createObject(playerConfig.commander, playerConfig.id) commander.isCommander = true commander.zone = 'command' this.getPlayer(playerConfig.id).command.push(commander.id) this.getPlayer(playerConfig.id).commanderId = commander.id } } } get player(): PlayerState { return this.getPlayer(this.activePlayer) } getPlayer(id: string): PlayerState { const player = this.players.find(entry => entry.id === id) if (!player) throw new GameError(`Unknown player: ${id}`) return player } getObject(id: string): GameObject { const object = this.objects.get(id) if (!object) throw new GameError(`Unknown object: ${id}`) return object } /** * Starts the game, shuffles libraries, and draws opening hands. With mulligans * enabled, turn 1 waits until every player keeps; otherwise it begins immediately. */ start(): void { if (this.status !== 'not_started') throw new GameError('Game already started') for (const player of this.players) this.shuffleLibrary(player) for (const player of this.players) { for (let i = 0; i < this.startingHandSize; i++) { if (!player.library.length) break this.drawCard(player.id, true) } } if (!this.config.mulligans) { this.beginGame() return } this.status = 'mulligan' this.turn = 1 this.activePlayer = this.firstPlayer } /** Keeps the opening hand; turn 1 begins once every living player has kept. */ keepHand(playerId: string): void { const mulligan = this.requireMulligan(playerId) if (mulligan.kept) throw new GameError('You already kept your hand') if (mulligan.bottom > 0) throw new GameError('Put your cards on the bottom first') mulligan.kept = true const player = this.getPlayer(playerId) this.logMessage(`${player.name} keeps their hand${mulligan.count ? ` after ${mulligan.count} mulligan${mulligan.count === 1 ? '' : 's'}` : ''}`) if (this.players.every(entry => entry.lost || this.mulligans.get(entry.id)?.kept)) this.beginGame() } /** Shuffles the hand back and draws a new one; each mulligan bottoms one more card. */ mulligan(playerId: string): void { const mulligan = this.requireMulligan(playerId) if (mulligan.kept) throw new GameError('You already kept your hand') if (mulligan.bottom > 0) throw new GameError('Put your cards on the bottom first') const player = this.getPlayer(playerId) for (const id of [...player.hand]) this.moveToZone(id, 'library', { silent: true }) this.shuffleLibrary(player) for (let i = 0; i < this.startingHandSize; i++) { if (!player.library.length) break this.drawCard(player.id, true) } mulligan.count++ mulligan.bottom = Math.min(Math.max(0, mulligan.count - 1), player.hand.length) this.logMessage(`${player.name} mulligans${mulligan.bottom ? ` and puts ${mulligan.bottom} card${mulligan.bottom === 1 ? '' : 's'} on the bottom` : ''}`) } /** Puts one card from a mulliganed opening hand on the bottom of the library. */ putOnBottom(playerId: string, cardId: string): void { const mulligan = this.requireMulligan(playerId) if (mulligan.kept) throw new GameError('You already kept your hand') if (mulligan.bottom <= 0) throw new GameError('You have no cards to put on the bottom') const player = this.getPlayer(playerId) if (!player.hand.includes(cardId)) throw new GameError('Card is not in hand') this.moveToZone(cardId, 'library', { silent: true }) mulligan.bottom-- } private requireMulligan(playerId: string): MulliganState { if (this.status !== 'mulligan') throw new GameError('The game is not in its mulligan step') const player = this.getPlayer(playerId) if (player.lost) throw new GameError('You have left the game') const mulligan = this.mulligans.get(playerId) if (!mulligan) throw new GameError(`Unknown player: ${playerId}`) return mulligan } private beginGame(): void { // Leyline-style "begin the game with it on the battlefield" cards. for (const player of this.players) { if (player.lost) continue for (const id of [...player.hand]) { const object = this.getObject(id) const beginsOnBattlefield = (object.definition.abilities ?? []).some(ability => ability.kind === 'static' && ability.effects.some(effect => effect.op === 'restriction' && effect.rule === 'begin_on_battlefield')) if (beginsOnBattlefield) this.moveToZone(object, 'battlefield', { controller: player.id, silent: true }) } } this.status = 'active' this.turn = 1 this.activePlayer = this.firstPlayer this.beginTurn() } /** * Adds a card directly to a zone. Intended for setup, tests, and future * deck-building flows; by default no enter/leave triggers fire. */ addCard( playerId: string, definition: CardDefinition, zone: Zone, options: { controller?: string; tapped?: boolean; silent?: boolean } = {}, ): GameObject { const object = this.createObject(definition, playerId) this.moveToZone(object, zone, { ...options, silent: options.silent ?? true }) return object } /** Purely cosmetic board layout: normalized center within the controller's mat. */ movePermanent(playerId: string, cardId: string, x: number, y: number): void { const object = this.getObject(cardId) if (object.zone !== 'battlefield') throw new GameError('That card is not on the battlefield') if (object.controller !== playerId) throw new GameError('You do not control that permanent') if (!Number.isFinite(x) || !Number.isFinite(y)) throw new GameError('Invalid position') object.position = { x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)), } } /** Moves an object to a zone, firing leave/enter triggers unless silenced. */ moveToZone( objectOrId: GameObject | string, zone: Zone, options: { controller?: string; tapped?: boolean; silent?: boolean; toTop?: boolean } = {}, ): GameObject { const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId // A commander may go to the command zone instead of the graveyard, exile, // hand, or library. This engine always takes that replacement. let destination: Zone = object.isCommander && zone !== 'battlefield' && zone !== 'stack' && zone !== 'command' ? 'command' : zone if (destination === 'graveyard' && this.exilesInsteadOfGraveyard(object)) destination = 'exile' const from = object.zone this.removeFromZone(object) object.zone = destination if (destination === 'battlefield') { object.controller = options.controller ?? object.owner object.tapped = options.tapped ?? false object.damage = 0 object.deathtouched = false object.attacking = undefined object.blockedBy = [] object.blocking = undefined object.activations = {} object.chosenCreatureType = undefined object.enteredTurn = this.turn this.getPlayer(object.controller).battlefield.push(object.id) if (from !== 'battlefield') { if (this.turn > 0 && !this.isLand(object)) { this.getPlayer(object.controller).nonlandPermanentsEnteredThisTurn++ } if (!options.silent) { this.applyEntersReplacements(object) this.queueEnterChoices(object) this.dispatchEvent({ kind: 'enters', player: object.controller, subject: object }) } } } else { object.position = undefined object.controller = object.owner object.chosenCreatureType = undefined const owner = this.getPlayer(object.owner) if (destination === 'hand') owner.hand.push(object.id) else if (destination === 'graveyard') owner.graveyard.push(object.id) else if (destination === 'exile') owner.exile.push(object.id) else if (destination === 'command') { object.tapped = false owner.command.push(object.id) } else if (destination === 'library') { if (options.toTop) owner.library.unshift(object.id) else owner.library.push(object.id) } } if (from === 'battlefield' && destination !== 'battlefield') { this.handleLeavesBattlefield(object, destination) } if (object.isToken && from === 'battlefield' && destination !== 'battlefield') { this.objects.delete(object.id) } return object } getPower(objectOrId: GameObject | string): number { const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId const base = object.definition.power ?? 0 if (this.statDepth > 0) return base this.statDepth++ try { let power = base let toughness = object.definition.toughness ?? 0 for (const staticSource of this.staticAbilities()) { for (const effect of staticSource.ability.effects) { if (effect.op !== 'set_pt') continue if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue if (effect.power) power = this.value(effect.power, this.staticContext(staticSource.source)) if (effect.toughness) toughness = this.value(effect.toughness, this.staticContext(staticSource.source)) } } for (const continuous of this.continuousEffects) { if (continuous.effect.op !== 'set_pt' || !continuous.affectedIds.includes(object.id)) continue const context = this.continuousContext(continuous) if (continuous.effect.power) power = this.value(continuous.effect.power, context) if (continuous.effect.toughness) toughness = this.value(continuous.effect.toughness, context) } const counterPower = this.counterStat(object.counters, 'power') const counterToughness = this.counterStat(object.counters, 'toughness') power += counterPower toughness += counterToughness for (const staticSource of this.staticAbilities()) { for (const effect of staticSource.ability.effects) { if (effect.op !== 'pump') continue if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue const context = this.staticContext(staticSource.source) power += this.value(effect.power, context) toughness += this.value(effect.toughness, context) } } for (const continuous of this.continuousEffects) { if (continuous.effect.op !== 'pump' || !continuous.affectedIds.includes(object.id)) continue const context = this.continuousContext(continuous) power += this.value(continuous.effect.power, context) toughness += this.value(continuous.effect.toughness, context) } return power } finally { this.statDepth-- } } getToughness(objectOrId: GameObject | string): number { const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId const base = object.definition.toughness ?? 0 if (this.statDepth > 0) return base this.statDepth++ try { let power = base let toughness = object.definition.toughness ?? 0 for (const staticSource of this.staticAbilities()) { for (const effect of staticSource.ability.effects) { if (effect.op !== 'set_pt') continue if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue if (effect.power) power = this.value(effect.power, this.staticContext(staticSource.source)) if (effect.toughness) toughness = this.value(effect.toughness, this.staticContext(staticSource.source)) } } for (const continuous of this.continuousEffects) { if (continuous.effect.op !== 'set_pt' || !continuous.affectedIds.includes(object.id)) continue const context = this.continuousContext(continuous) if (continuous.effect.power) power = this.value(continuous.effect.power, context) if (continuous.effect.toughness) toughness = this.value(continuous.effect.toughness, context) } toughness += this.counterStat(object.counters, 'toughness') for (const staticSource of this.staticAbilities()) { for (const effect of staticSource.ability.effects) { if (effect.op !== 'pump') continue if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue toughness += this.value(effect.toughness, this.staticContext(staticSource.source)) } } for (const continuous of this.continuousEffects) { if (continuous.effect.op !== 'pump' || !continuous.affectedIds.includes(object.id)) continue toughness += this.value(continuous.effect.toughness, this.continuousContext(continuous)) } return toughness } finally { this.statDepth-- } } hasKeyword(objectOrId: GameObject | string, keyword: string): boolean { const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId const wanted = keyword.toLowerCase() if (this.keywordDepth > 0) { for (const ability of object.definition.abilities ?? []) { if (ability.kind === 'keyword' && ability.keyword.toLowerCase() === wanted) return true } return false } this.keywordDepth++ try { for (const ability of object.definition.abilities ?? []) { if (ability.kind === 'keyword' && ability.keyword.toLowerCase() === wanted) return true if (ability.kind === 'keywords' && ability.keywords.some(entry => entry.keyword.toLowerCase() === wanted)) { return true } } for (const staticSource of this.staticAbilities()) { for (const effect of staticSource.ability.effects) { if (effect.op !== 'grant' || effect.keyword.toLowerCase() !== wanted) continue if (this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) return true } } for (const continuous of this.continuousEffects) { if (continuous.effect.op !== 'grant' || continuous.effect.keyword.toLowerCase() !== wanted) continue if (continuous.affectedIds.includes(object.id)) return true } return false } finally { this.keywordDepth-- } } playLand(playerId: string, cardId: string): GameObject { this.requirePriority(playerId) const player = this.getPlayer(playerId) if (this.activePlayer !== playerId) throw new GameError('Only the active player may play a land') if (this.phase !== 'precombat_main' && this.phase !== 'postcombat_main') { throw new GameError('Lands can only be played during a main phase') } if (this.stack.length) throw new GameError('Cannot play a land while the stack is not empty') if (player.landPlayedThisTurn) throw new GameError('Already played a land this turn') if (!player.hand.includes(cardId)) throw new GameError('Card is not in hand') const object = this.getObject(cardId) if (!this.isLand(object)) throw new GameError('That card is not a land') player.landPlayedThisTurn = true this.moveToZone(object, 'battlefield', { controller: playerId, silent: false }) this.passesInRow = 0 this.logMessage(`${player.name} plays ${object.definition.name}`) this.runStateBasedActions() return object } castSpell(playerId: string, cardId: string, options: ActionOptions = {}): StackItem { this.requirePriority(playerId) if (this.status !== 'active') throw new GameError('Game is not active') const player = this.getPlayer(playerId) const fromCommand = player.command.includes(cardId) if (!fromCommand && !player.hand.includes(cardId)) throw new GameError('Card is not in hand') const object = this.getObject(cardId) if (fromCommand && !object.isCommander) throw new GameError('That card cannot be cast from the command zone') if (this.isLand(object)) throw new GameError('Land cards are played, not cast') if (!this.canCastAtThisTime(playerId, object)) { throw new GameError('That spell cannot be cast right now') } const abilities = object.definition.abilities ?? [] const overload = abilities.find((ability): ability is Extract => ability.kind === 'overload') if (options.overload && !overload) throw new GameError('That spell has no overload') const baseEffects = abilities.filter((ability): ability is Extract => ability.kind === 'spell') .flatMap(ability => ability.effects) const effects = options.overload ? this.overloadEffects(baseEffects) : baseEffects const targets = this.selectTargets(effects, object, playerId, options.targets ?? [], options.mode ?? 0) const tax = fromCommand ? (player.commanderCasts[object.id] ?? 0) * 2 : 0 const taxSymbols = '{2}'.repeat(tax / 2) const extra = this.spellCostIncrease(object) const alternative = this.alternativeCostFor(object) if (options.overload && overload) { this.payMana(playerId, `${this.reducedSpellCost(object, overload.cost)}${taxSymbols}${extra ? `{${extra}}` : ''}`, options.x ?? 0) } else if (alternative) { this.payAlternativeCost(alternative, playerId, object) if (extra) this.payMana(playerId, `{${extra}}`, 0) } else { const cost = this.reducedSpellCost(object, object.definition.manaCost ?? '') this.payMana(playerId, `${cost}${taxSymbols}${extra ? `{${extra}}` : ''}`, options.x ?? 0) } this.moveToZone(object, 'stack', { controller: playerId, silent: true }) if (fromCommand) player.commanderCasts[object.id] = (player.commanderCasts[object.id] ?? 0) + 1 const item: StackItem = { id: this.generateId('stack'), kind: 'spell', source: object, controller: playerId, label: object.definition.name, effects, targets, x: options.x ?? 0, mode: options.mode ?? 0, } this.stack.push(item) player.spellsCastThisTurn++ this.passesInRow = 0 this.priority = this.nextAlivePlayer(playerId) this.dispatchEvent({ kind: 'cast', player: playerId, subject: object, spell: object, spellItem: item }) this.logMessage(`${player.name} casts ${object.definition.name}`) return item } private alternativeCostFor(object: GameObject): Extract | undefined { return (object.definition.abilities ?? []).find(ability => ability.kind === 'alternative_cost' && (!ability.condition || this.checkCondition(ability.condition, object))) as | Extract | undefined } private payAlternativeCost( ability: Extract, playerId: string, source: GameObject, ): void { if (!ability.costs.length) return this.payCosts(ability.costs, playerId, source, this.contextFor(source, playerId, [], 0, 0)) } private spellCostIncrease(object: GameObject): number { let extra = 0 for (const { source, ability } of this.staticAbilities()) { for (const effect of ability.effects) { if (effect.op !== 'cost_increase') continue if (effect.spellType === 'noncreature' && this.isCreature(object)) continue if (effect.spellType === 'creature' && !this.isCreature(object)) continue extra += this.value(effect.amount, this.staticContext(source)) } } return extra } // shortcut: only static reducers on the battlefield; a card's own "this spell // costs less" text is not applied yet. Upgrade when self-cost cards matter. private spellCostReduction(object: GameObject): CostReduction { const reduction: CostReduction = { generic: 0, colored: [] } for (const { source, ability } of this.staticAbilities()) { for (const effect of ability.effects) { if (effect.op !== 'cost_reduction' || effect.target.kind !== 'object') continue if (!this.matchesSelector(object, effect.target.selector, source, object.zone)) continue if (effect.amount) reduction.generic += this.value(effect.amount, this.staticContext(source)) if (effect.symbols) { const cost = parseManaCost(effect.symbols) reduction.generic += cost.generic reduction.colored.push(...cost.colored) } } } return reduction } private reducedSpellCost(object: GameObject, symbols: string): string { return reduceManaSymbols(symbols, this.spellCostReduction(object)) } // shortcut: overload only widens top-level targets; modal/conditional nested // effects keep their original targets. Upgrade when an overload card nests them. private overloadEffects(effects: Effect[]): Effect[] { return effects.map(effect => ('target' in effect && effect.target ? { ...effect, target: this.overloadTarget(effect.target) } : effect)) } private overloadTarget(target: Target): Target { if (target.kind === 'object' || target.kind === 'player' || target.kind === 'spell') { return { ...target, mode: 'each' } } return target } activateAbility(playerId: string, sourceId: string, abilityIndex: number, options: ActionOptions = {}): StackItem | undefined { this.requirePriority(playerId) const source = this.getObject(sourceId) if (source.zone !== 'battlefield') throw new GameError('Ability source is not on the battlefield') if (source.controller !== playerId) throw new GameError('You do not control that permanent') if (this.hasRestriction(source, 'cant_activate')) throw new GameError('That permanent cannot activate abilities') const ability = (source.definition.abilities ?? [])[abilityIndex] if (!ability || ability.kind !== 'activated') throw new GameError('That is not an activated ability') if (ability.condition && !this.checkCondition(ability.condition, source)) throw new GameError('Ability condition is not met') if (ability.timing === 'sorcery' && !this.isMainPhaseWithEmptyStack(playerId)) { throw new GameError('Activate only as a sorcery') } if (ability.costs.some(cost => cost.kind === 'tap') && this.isCreature(source) && source.enteredTurn >= this.turn && !this.hasKeyword(source, 'Haste')) { throw new GameError('That creature has summoning sickness') } const activations = source.activations[abilityIndex] ?? 0 if (ability.activationsPerTurn !== undefined && activations >= ability.activationsPerTurn) { throw new GameError('Ability activation limit reached') } const targets = this.selectTargets(ability.effects, source, playerId, options.targets ?? [], options.mode ?? 0) const context = this.contextFor(source, playerId, targets, options.x ?? 0, options.mode ?? 0) this.payCosts(ability.costs, playerId, source, context) source.activations[abilityIndex] = activations + 1 // Mana abilities bypass the stack, which also makes auto-payment possible. if (ability.effects.length && ability.effects.every(effect => effect.op === 'add_mana')) { this.applyEffects(context, ability.effects) this.passesInRow = 0 this.logMessage(`${this.getPlayer(playerId).name} activates ${source.definition.name}`) return undefined } const item: StackItem = { id: this.generateId('stack'), kind: 'ability', source, controller: playerId, label: ability.text, effects: ability.effects, targets, x: options.x ?? 0, mode: options.mode ?? 0, } this.stack.push(item) this.passesInRow = 0 this.priority = this.nextAlivePlayer(playerId) this.logMessage(`${this.getPlayer(playerId).name} activates ${source.definition.name}`) return item } /** Declares attackers, beginning combat first if necessary. */ declareAttackers(playerId: string, attacks: CombatAttack[]): void { this.requirePriority(playerId) if (this.stack.length) throw new GameError('Cannot declare attackers while the stack is not empty') if (this.activePlayer !== playerId) throw new GameError('Only the active player can attack') if (this.phase === 'precombat_main') { this.phase = 'combat' this.step = 'declare_attackers' this.dispatchEvent({ kind: 'begin_combat', player: playerId }) } if (this.phase !== 'combat' || this.step !== 'declare_attackers') { throw new GameError('Not in the declare attackers step') } const seen = new Set() for (const attack of attacks) { if (seen.has(attack.attackerId)) throw new GameError('A creature can only attack once') seen.add(attack.attackerId) const attacker = this.getObject(attack.attackerId) this.requireCanAttack(attacker, playerId) const defender = this.getPlayer(attack.defenderId) if (defender.id === playerId) throw new GameError('A player cannot attack themselves') attacker.attacking = attack.defenderId if (!this.hasKeyword(attacker, 'Vigilance')) attacker.tapped = true this.getPlayer(playerId).attackedThisTurn = true this.getPlayer(playerId).creaturesAttackedThisTurn++ this.dispatchEvent({ kind: 'attacks', player: playerId, subject: attacker }) } this.step = attacks.length ? 'declare_blockers' : 'end_combat' this.blockersDeclared.clear() this.passesInRow = 0 this.priority = this.nextAlivePlayer(playerId) this.logMessage(`${this.getPlayer(playerId).name} attacks with ${attacks.length} creature(s)`) } /** Marks a player as having forfeited. */ concede(playerId: string): void { if (this.status !== 'active' && this.status !== 'mulligan') throw new GameError('Game is not active') this.losePlayer(playerId) if (this.priority === playerId) this.priority = this.nextAlivePlayer(playerId) } /** Declares blockers for the current combat. */ declareBlockers(playerId: string, blocks: CombatBlock[]): void { if (this.phase !== 'combat' || this.step !== 'declare_blockers') throw new GameError('Not in the declare blockers step') if (this.stack.length) throw new GameError('Cannot declare blockers while the stack is not empty') if (this.pendingSearch) throw new GameError('Choose a card from your library first') if (this.pendingChoice) throw new GameError('Resolve the pending choice first') if (this.priority !== playerId) throw new GameError('You do not have priority') const seen = new Set() for (const block of blocks) { if (seen.has(block.blockerId)) throw new GameError('A creature can only block once') seen.add(block.blockerId) const blocker = this.getObject(block.blockerId) const attacker = this.getObject(block.attackerId) if (blocker.controller !== playerId) throw new GameError('You do not control that blocker') if (blocker.zone !== 'battlefield' || attacker.zone !== 'battlefield') throw new GameError('Object is not on the battlefield') if (!this.isCreature(blocker)) throw new GameError('Only creatures can block') if (blocker.tapped) throw new GameError('Tapped creatures cannot block') if (blocker.blocking) throw new GameError('Creature is already blocking') if (attacker.attacking !== playerId) throw new GameError('That creature is not attacking you') if (this.hasRestriction(blocker, 'cant_block')) throw new GameError('That creature cannot block') if (this.hasKeyword(attacker, 'Flying') && !this.hasKeyword(blocker, 'Flying') && !this.hasKeyword(blocker, 'Reach')) { throw new GameError('That creature cannot block a flyer') } blocker.blocking = attacker.id attacker.blockedBy.push(blocker.id) this.dispatchEvent({ kind: 'blocks', player: playerId, subject: blocker }) } this.blockersDeclared.add(playerId) this.logMessage(`${this.getPlayer(playerId).name} declares ${blocks.length} blocker(s)`) if ([...this.defendingPlayers()].every(id => this.blockersDeclared.has(id))) { this.finishBlocking() } else { this.passesInRow = 0 this.priority = this.nextAlivePlayer(playerId) } } private defendingPlayers(): Set { return new Set(this.battlefieldObjects() .filter(object => object.attacking) .map(object => object.attacking as string)) } private finishBlocking(): void { this.step = 'combat_damage' this.combatDamageDone = false this.passesInRow = 0 this.priority = this.activePlayer } /** Resolves the combat damage step. Also runs automatically when both players pass. */ resolveCombatDamage(): void { if (this.phase !== 'combat' || this.step !== 'combat_damage') throw new GameError('Not in the combat damage step') if (this.combatDamageDone) throw new GameError('Combat damage has already been dealt') this.combatDamageDone = true this.dealCombatDamage() this.runStateBasedActions() } /** Passes priority. When all players pass, the top of the stack resolves or the phase advances. */ pass(playerId?: string): void { if (this.status !== 'active') throw new GameError('Game is not active') if (this.pendingSearch) throw new GameError('Choose a card from your library first') if (this.pendingChoice) throw new GameError('Resolve the pending choice first') const actual = playerId ?? this.priority if (this.priority !== actual) throw new GameError('You do not have priority') const alive = this.alivePlayers().length this.passesInRow++ if (!this.stack.length && this.phase === 'combat' && this.step === 'declare_blockers') { const defenders = this.defendingPlayers() if (defenders.has(actual)) this.blockersDeclared.add(actual) if ([...defenders].every(id => this.blockersDeclared.has(id))) { this.finishBlocking() } else { this.priority = this.nextAlivePlayer(actual) } return } if (this.stack.length) { if (this.passesInRow >= alive) { this.passesInRow = 0 this.resolveTop() this.priority = this.getPlayer(this.activePlayer).lost ? this.nextAlivePlayer(this.activePlayer) : this.activePlayer } else { this.priority = this.nextAlivePlayer(actual) } return } if (this.passesInRow >= alive) { this.passesInRow = 0 this.advancePhase() } else { this.priority = this.nextAlivePlayer(actual) } } /** Convenience for tests and scripted games: resolve the stack without advancing phases. */ resolveStack(): void { let guard = 0 while (this.stack.length && this.status === 'active' && !this.pendingSearch && !this.pendingChoice && guard++ < 1000) { this.pass(this.priority) } } /** Ends the active player's turn, skipping any remaining combat. */ endTurn(playerId: string): void { this.requirePriority(playerId) if (playerId !== this.activePlayer) throw new GameError('Only the active player can end the turn') if (this.stack.length) throw new GameError('Cannot end the turn while the stack is not empty') this.clearCombat() this.phase = 'ending' this.step = 'end_step' this.dispatchEvent({ kind: 'end_step', player: playerId }) this.resolveStack() if (this.status !== 'active' || this.pendingSearch || this.pendingChoice) return this.finishTurn() } /** * Whether the player could legally play a card from hand or the command zone * right now. Used for the client's playable state and for auto-passing. */ canPlayCard(playerId: string, cardId: string): boolean { if (this.status !== 'active' || this.priority !== playerId || this.pendingSearch || this.pendingChoice) return false const player = this.getPlayer(playerId) const fromCommand = player.command.includes(cardId) if (!fromCommand && !player.hand.includes(cardId)) return false const object = this.getObject(cardId) if (fromCommand && !object.isCommander) return false if (this.isLand(object)) { return this.activePlayer === playerId && (this.phase === 'precombat_main' || this.phase === 'postcombat_main') && !this.stack.length && !player.landPlayedThisTurn } if (!this.canCastAtThisTime(playerId, object)) return false const tax = fromCommand ? (player.commanderCasts[cardId] ?? 0) * 2 : 0 const extra = this.spellCostIncrease(object) const alternative = this.alternativeCostFor(object) if (alternative) { for (const cost of alternative.costs) { if (cost.kind !== 'mana' || !this.canAffordMana(playerId, cost.symbols, 0)) return false } } else if (!this.canAffordMana( playerId, `${this.reducedSpellCost(object, object.definition.manaCost ?? '')}${'{2}'.repeat(tax / 2)}${extra ? `{${extra}}` : ''}`, 0, )) { return false } if (alternative && extra && !this.canAffordMana(playerId, `{${extra}}`, 0)) return false return this.hasLegalTargets(object, playerId) } /** * Finishes one pick of a paused library search. Searches pause when several * cards match so the player chooses instead of taking the first one. */ chooseSearchCard(playerId: string, cardId: string): void { const pending = this.pendingSearch if (!pending) throw new GameError('No search is waiting for a choice') if (this.pendingChoice) throw new GameError('Resolve the pending choice first') if (pending.playerId !== playerId) throw new GameError('You are not searching your library') const object = this.searchCandidates(playerId).find(candidate => candidate.id === cardId) if (!object) throw new GameError('That card is not a legal choice') this.moveSearchedCard(object, playerId, pending.destination, pending.tapped) pending.remaining-- if (pending.remaining > 0 && pending.split) { pending.destination = pending.split.destination pending.tapped = pending.split.tapped pending.split = undefined } if (pending.remaining <= 0 || !this.searchCandidates(playerId).length) { this.pendingSearch = undefined if (pending.shuffle) this.shuffleLibrary(this.getPlayer(playerId)) this.priority = this.getPlayer(this.activePlayer).lost ? this.nextAlivePlayer(this.activePlayer) : this.activePlayer } this.runStateBasedActions() } /** Cards the pending search may pick, in library order. Empty for other players. */ searchCandidates(playerId: string): GameObject[] { const pending = this.pendingSearch if (!pending || pending.playerId !== playerId) return [] return this.findSearchCandidates(playerId, pending.selector, pending.zones) } /** * Every card in the zones a pending search can look at, in search order. This * is what the chooser sees while deciding; others get an empty list. */ searchPool(playerId: string): GameObject[] { const pending = this.pendingSearch if (!pending || pending.playerId !== playerId) return [] return this.searchableObjects(playerId, pending.zones) } /** * Answers an "as this enters, choose a creature type" prompt. The match API * uses the `choose_type` action. */ chooseCreatureType(playerId: string, type: string): void { const pending = this.pendingChoice if (!pending || pending.what !== 'creature_type') throw new GameError('No choice is waiting') if (pending.playerId !== playerId) throw new GameError('You are not choosing this permanent\'s type') const chosen = CREATURE_TYPES.find(entry => entry.toLowerCase() === type.trim().toLowerCase()) if (!chosen) throw new GameError('Choose a creature type') const object = this.objects.get(pending.sourceId) if (!object || object.zone !== 'battlefield') throw new GameError('That permanent is no longer on the battlefield') object.chosenCreatureType = chosen this.pendingChoices.shift() this.logMessage(`${this.getPlayer(playerId).name} chooses ${chosen} for ${object.definition.name}`) } /** * Answers an "as this enters, you may pay a cost; otherwise it enters tapped" * replacement. The match API uses the `choose_cost` action. */ chooseCostPayment(playerId: string, pay: boolean): void { const pending = this.pendingChoice if (!pending || pending.what !== 'pay_cost' || !pending.cost) throw new GameError('No cost payment is waiting') if (pending.playerId !== playerId) throw new GameError('You are not choosing this payment') const object = this.objects.get(pending.sourceId) if (object && object.zone === 'battlefield') { if (pay) { const context = this.contextFor(object, playerId, [], 0, 0) if (!this.tryPayUnless(pending.cost, playerId, object, context)) throw new GameError('Cannot pay the cost') this.pendingChoices.shift() const detail = pending.amount === undefined ? 'the cost' : `${pending.amount} life` this.logMessage(`${this.getPlayer(playerId).name} pays ${detail} for ${object.definition.name}`) return } this.pendingChoices.shift() object.tapped = true this.logMessage(`${object.definition.name} enters tapped`) return } this.pendingChoices.shift() } /** * Passes priority for players who cannot do anything meaningful. Stops at the * first player who can act, or when the turn ends, so turns never run on. */ autoAdvance(): void { if (this.status !== 'active' || this.pendingSearch || this.pendingChoice || this.autoAdvanceDepth > 0) return this.autoAdvanceDepth++ const turn = this.turn try { let guard = 0 while (this.status === 'active' && !this.pendingSearch && !this.pendingChoice && this.turn === turn && guard++ < 100) { const actor = this.priority if (!actor || this.hasMeaningfulAction(actor)) break this.pass(actor) } } finally { this.autoAdvanceDepth-- } } // --------------------------------------------------------------------------- // Turn structure // --------------------------------------------------------------------------- private beginTurn(): void { const player = this.getPlayer(this.activePlayer) this.phase = 'beginning' this.step = 'untap' this.passesInRow = 0 this.priority = player.id player.landPlayedThisTurn = false player.cardsDrawnThisTurn = 0 player.lifeGainedThisTurn = 0 player.spellsCastThisTurn = 0 player.creaturesDiedThisTurn = 0 player.nonlandPermanentsEnteredThisTurn = 0 player.attackedThisTurn = false player.creaturesAttackedThisTurn = 0 player.damageTakenThisTurn = 0 player.manaPool = emptyPool() this.removeExpiringEffects(player.id) for (const id of [...player.battlefield]) { const object = this.objects.get(id) if (!object || object.zone !== 'battlefield') continue if (!this.hasRestriction(object, 'doesnt_untap')) object.tapped = false } this.step = 'upkeep' this.dispatchEvent({ kind: 'upkeep', player: player.id }) if (this.status !== 'active') return this.step = 'draw' // The first player skips their first draw step, as in Commander. if (this.turn > 1) { this.drawCard(player.id, false) if (this.status !== 'active') return } this.phase = 'precombat_main' this.step = 'main' this.priority = player.id this.passesInRow = 0 } private finishTurn(): void { const player = this.getPlayer(this.activePlayer) while (player.hand.length > 7) { const cardId = player.hand[player.hand.length - 1] this.moveToZone(cardId, 'graveyard', { silent: true }) } for (const object of this.objects.values()) { if (object.zone === 'battlefield') { object.damage = 0 object.deathtouched = false } } this.removeEffectsByDuration('until_end_of_turn') this.removeEndOfNextTurnEffects(player.id) this.clearCombat() for (const entry of this.players) entry.manaPool = emptyPool() if (this.status !== 'active') return this.turn++ this.activePlayer = this.nextAlivePlayer(this.activePlayer) this.beginTurn() } private advancePhase(): void { if (this.status !== 'active') return if (this.stack.length) return this.emptyManaPools() if (this.step === 'main' && this.phase === 'precombat_main') { this.phase = 'combat' this.step = 'begin_combat' this.dispatchEvent({ kind: 'begin_combat', player: this.activePlayer }) this.step = 'declare_attackers' this.priority = this.activePlayer this.passesInRow = 0 return } if (this.step === 'declare_attackers') { this.step = 'end_combat' this.passesInRow = 0 this.priority = this.activePlayer return } if (this.step === 'declare_blockers') { this.step = 'combat_damage' this.combatDamageDone = false this.passesInRow = 0 this.priority = this.activePlayer return } if (this.step === 'combat_damage') { this.combatDamageDone = true this.dealCombatDamage() this.runStateBasedActions() this.passesInRow = 0 this.priority = this.activePlayer return } if (this.step === 'end_combat') { this.clearCombat() this.removeEffectsByDuration('until_end_of_combat') this.phase = 'postcombat_main' this.step = 'main' this.passesInRow = 0 this.priority = this.activePlayer return } if (this.step === 'main' && this.phase === 'postcombat_main') { this.phase = 'ending' this.step = 'end_step' this.dispatchEvent({ kind: 'end_step', player: this.activePlayer }) this.passesInRow = 0 this.priority = this.activePlayer return } if (this.step === 'end_step') { this.finishTurn() } } private clearCombat(): void { this.blockersDeclared.clear() for (const object of this.objects.values()) { if (object.zone !== 'battlefield') continue object.attacking = undefined object.blockedBy = [] object.blocking = undefined } this.combatDamageDone = false } // --------------------------------------------------------------------------- // Stack // --------------------------------------------------------------------------- private resolveTop(): void { const item = this.stack.pop() if (!item) return if (item.kind === 'spell' && item.source.zone !== 'stack') return const context = this.contextFor( item.source, item.controller, item.targets, item.x, item.mode, item.triggerSubject, item.eventPlayer, item.eventAmount, ) if (item.kind === 'spell') { if (this.isPermanent(item.source)) { if (item.source.zone === 'stack') { this.moveToZone(item.source, 'battlefield', { controller: item.controller, silent: false }) } this.applyEffects(context, item.effects) } else { this.applyEffects(context, item.effects) if (item.source.zone === 'stack') this.moveToZone(item.source, 'graveyard', { silent: true }) } } else { this.applyEffects(context, item.effects) } this.logMessage(`Resolved ${item.label}`) this.runStateBasedActions() } private counterStackItem(item: StackItem): void { const index = this.stack.indexOf(item) if (index >= 0) this.stack.splice(index, 1) if (item.kind === 'spell' && item.source.zone === 'stack') { this.moveToZone(item.source, 'graveyard', { silent: true }) } this.logMessage(`Countered ${item.label}`) } // --------------------------------------------------------------------------- // Casting, mana, and costs // --------------------------------------------------------------------------- private canCastAtThisTime(playerId: string, object: GameObject): boolean { const instant = this.isInstant(object) const flash = this.hasKeywordForDefinition(object.definition, 'Flash') if (instant || flash) return true return this.isMainPhaseWithEmptyStack(playerId) } private isMainPhaseWithEmptyStack(playerId: string): boolean { return this.activePlayer === playerId && (this.phase === 'precombat_main' || this.phase === 'postcombat_main') && this.step === 'main' && this.stack.length === 0 } private payMana(playerId: string, symbols: string, x: number): void { if (!symbols) return const player = this.getPlayer(playerId) const cost = parseManaCost(symbols, x) const pool = { ...player.manaPool } const tapped = player.battlefield .map(id => this.objects.get(id)) .filter((object): object is GameObject => Boolean(object?.tapped)) .map(object => object.id) this.autoTapForMana(player, cost) if (!this.canPayMana(player, cost)) { player.manaPool = pool for (const id of player.battlefield) { const object = this.objects.get(id) if (object) object.tapped = tapped.includes(id) } throw new GameError('Not enough mana') } this.deductMana(player, cost) } private canPayMana(player: PlayerState, cost: ManaCost): boolean { const pool = { ...player.manaPool } const payColor = (color: ManaColor): boolean => { if (pool[color] <= 0) return false pool[color]-- return true } for (const color of cost.colored) { if (!payColor(color)) return false } for (const hybrid of cost.hybrid) { const color = hybrid.colors.find(entry => pool[entry] > 0) if (color) pool[color]-- else if (!(hybrid.life > 0 && player.life >= hybrid.life)) return false } const remaining = MANA_COLORS.reduce((total, color) => total + pool[color], 0) return remaining >= cost.generic } private deductMana(player: PlayerState, cost: ManaCost): void { for (const color of cost.colored) player.manaPool[color]-- for (const hybrid of cost.hybrid) { const color = hybrid.colors.find(entry => player.manaPool[entry] > 0) if (color) player.manaPool[color]-- else if (hybrid.life > 0) this.loseLife(player.id, hybrid.life) else throw new GameError('Not enough mana') } let generic = cost.generic for (const color of MANA_COLORS) { const used = Math.min(player.manaPool[color], generic) player.manaPool[color] -= used generic -= used } if (generic > 0) throw new GameError('Not enough mana') } private autoTapForMana(player: PlayerState, cost: ManaCost): void { if (this.autoManaDepth > 0) return let guard = 0 while (!this.canPayMana(player, cost) && guard++ < 25) { const source = this.players .flatMap(entry => entry.battlefield) .map(id => this.objects.get(id)) .map(object => { if (!object || object.zone !== 'battlefield' || object.controller !== player.id || object.tapped) return undefined const found = this.findFreeManaAbility(object) if (!found) return undefined return { object, allowed: this.manaAbilityAllowedColors(object, found.ability) } }) .filter((entry): entry is { object: GameObject; allowed: Set | undefined } => Boolean(entry)) .filter(entry => this.neededColor(player, cost, entry.allowed) !== undefined) .sort((a, b) => (a.allowed?.size ?? Number.MAX_SAFE_INTEGER) - (b.allowed?.size ?? Number.MAX_SAFE_INTEGER))[0]?.object if (!source) break this.autoManaDepth++ try { this.activateManaSource(source, cost) } finally { this.autoManaDepth-- } } } private findFreeManaAbility(source: GameObject): { index: number; ability: Extract } | undefined { const abilities = source.definition.abilities ?? [] for (let index = 0; index < abilities.length; index++) { const ability = abilities[index] if (ability.kind !== 'activated') continue if (!ability.effects.length || !ability.effects.every(effect => effect.op === 'add_mana')) continue if (ability.costs.length !== 1 || ability.costs[0].kind !== 'tap') continue if (source.tapped) continue if (this.isCreature(source) && source.enteredTurn >= this.turn && !this.hasKeyword(source, 'Haste')) continue return { index, ability } } return undefined } private activateManaSource(source: GameObject, cost: ManaCost): void { const found = this.findFreeManaAbility(source) if (!found) return const player = this.getPlayer(source.controller) const color = this.manaAbilityColor(source, found.ability, player, cost) if (!color) return for (const entry of found.ability.costs) { if (entry.kind === 'tap') source.tapped = true } for (const effect of found.ability.effects) { if (effect.op === 'add_mana') this.addMana(source.controller, effect.mana, color) } } private manaAbilityColor( source: GameObject, ability: Extract, player: PlayerState, cost: ManaCost, ): ManaColor | undefined { return this.neededColor(player, cost, this.manaAbilityAllowedColors(source, ability)) } private manaAbilityAllowedColors( source: GameObject, ability: Extract, ): Set | undefined { for (const effect of ability.effects) { if (effect.op !== 'add_mana') continue if (effect.mana.kind === 'symbols' && effect.mana.oneOf) { return new Set(effect.mana.symbols.map(colorOfSymbol)) } return this.anyColorRestrictionColors(effect.mana, source.controller) } return undefined } private neededColor(player: PlayerState, cost: ManaCost, allowed?: Set): ManaColor | undefined { for (const color of cost.colored) { if (player.manaPool[color] > 0) continue return allowed && !allowed.has(color) ? undefined : color } for (const hybrid of cost.hybrid) { if (hybrid.colors.some(color => player.manaPool[color] > 0)) continue return hybrid.colors.find(color => !allowed || allowed.has(color)) } if (allowed) return MANA_COLORS.find(color => allowed.has(color)) return 'W' } private addMana(playerId: string, mana: ManaSpec, preferred?: ManaColor): void { const player = this.getPlayer(playerId) if (mana.kind === 'symbols') { if (mana.oneOf) { const colors = mana.symbols.map(colorOfSymbol) const color = preferred && colors.includes(preferred) ? preferred : colors[0] if (color) player.manaPool[color]++ return } for (const symbol of mana.symbols) player.manaPool[colorOfSymbol(symbol)]++ return } const amount = this.value(mana.amount, { source: this.playerSource(playerId), controller: playerId, targets: [], x: 0, mode: 0, }) const allowed = this.anyColorRestrictionColors(mana, playerId) if (allowed?.size === 0) return let color: ManaColor = preferred ?? 'W' if (allowed && !allowed.has(color)) { color = MANA_COLORS.find(entry => allowed.has(entry)) ?? 'W' } for (let i = 0; i < amount; i++) player.manaPool[color]++ } /** * Colors a land could produce for an "any color that a land ... could * produce" restriction. Colorless and snow are not colors. */ private landManaColors(playerId: string, opponentsOnly: boolean, seen = new Set()): Set { const colors = new Set() const opponents = this.opponentsOf(playerId) for (const object of this.battlefieldObjects()) { if (!this.isLand(object) || seen.has(object.id)) continue if (opponentsOnly ? !opponents.includes(object.controller) : object.controller !== playerId) continue seen.add(object.id) for (const ability of object.definition.abilities ?? []) { if (ability.kind !== 'activated') continue for (const effect of ability.effects) { if (effect.op !== 'add_mana') continue if (effect.mana.kind === 'symbols') { for (const symbol of effect.mana.symbols) { for (const letter of symbol.match(/[WUBRG]/gi) ?? []) colors.add(letter.toUpperCase() as ManaColor) } } else { const nested = this.anyColorRestrictionColors(effect.mana, object.controller, seen) if (nested) { for (const color of nested) colors.add(color) } else { for (const color of MANA_COLORS) if (color !== 'C') colors.add(color) } } } } seen.delete(object.id) } return colors } /** The colors an any-color mana source may produce, when the restriction is known. */ private anyColorRestrictionColors( mana: ManaSpec, playerId: string, seen?: Set, ): Set | undefined { if (mana.kind !== 'any_color') return undefined if (mana.restriction === 'a land an opponent controls could produce') { return this.landManaColors(playerId, true, seen) } if (mana.restriction === 'a land you control could produce') { return this.landManaColors(playerId, false, seen) } return undefined } private payCosts(costs: Cost[], playerId: string, source: GameObject, context: EffectContext): void { for (const cost of costs) { if (cost.kind !== 'mana' && !this.canPayNonManaCost(cost, playerId, source)) { throw new GameError('Cannot pay ability cost') } } for (const cost of costs) { if (cost.kind === 'mana') this.payMana(playerId, cost.symbols, context.x) else this.payNonManaCost(cost, playerId, source, context) } } private canPayNonManaCost(cost: Cost, playerId: string, source: GameObject): boolean { const player = this.getPlayer(playerId) switch (cost.kind) { case 'tap': return !source.tapped case 'untap': return source.tapped case 'tap_other': return this.objectsMatching(cost.selector, source).some(object => !object.tapped) case 'energy': return player.energy >= cost.amount case 'pay_life': return player.life >= this.value(cost.amount, this.staticContext(source)) case 'discard': return player.hand.length >= this.value(cost.amount, this.staticContext(source)) case 'sacrifice': return this.objectsMatching(cost.selector, source).length > 0 case 'sacrifice_self': return source.zone === 'battlefield' case 'exile_self': return source.zone === 'graveyard' case 'exile_from_graveyard': return this.objectsMatching(cost.selector, source).length > 0 case 'return_to_hand': return this.objectsMatching(cost.selector, source).length > 0 case 'put_counter': return this.objectsMatching(cost.selector, source).length > 0 case 'remove_counters': { const amount = this.value(cost.amount, this.staticContext(source)) const objects = cost.selector ? this.objectsMatching(cost.selector, source) : [source] return objects.some(object => (object.counters[cost.counter] ?? 0) >= amount) } case 'mill': return player.library.length >= (cost.amount.kind === 'number' ? cost.amount.value : 0) case 'choice': return cost.options.some(option => option.every(entry => entry.kind === 'mana' || this.canPayNonManaCost(entry, playerId, source))) case 'waterbend': return this.canPayMana(player, parseManaCost('{0}', 0)) case 'reveal': case 'behold': case 'choose': return true default: return false } } private payNonManaCost(cost: Cost, playerId: string, source: GameObject, context: EffectContext): void { const player = this.getPlayer(playerId) switch (cost.kind) { case 'tap': source.tapped = true return case 'untap': source.tapped = false return case 'tap_other': { const target = this.objectsMatching(cost.selector, source).find(object => !object.tapped) if (!target) throw new GameError('No permanent to tap') target.tapped = true return } case 'energy': player.energy -= cost.amount return case 'loyalty': this.addCounters(source, 'loyalty', cost.amount, true) return case 'pay_life': this.loseLife(playerId, this.value(cost.amount, context)) return case 'discard': { const amount = this.value(cost.amount, context) this.discardCards(playerId, amount, cost.random, context) return } case 'sacrifice': { const target = this.objectsMatching(cost.selector, source)[0] if (!target) throw new GameError('No permanent to sacrifice') this.moveToZone(target, 'graveyard', { silent: false }) return } case 'sacrifice_self': this.moveToZone(source, 'graveyard', { silent: false }) return case 'exile_self': this.moveToZone(source, 'exile', { silent: false }) return case 'exile_from_graveyard': { const target = this.objectsMatching(cost.selector, source)[0] if (!target) throw new GameError('No card to exile') this.moveToZone(target, 'exile', { silent: false }) return } case 'return_to_hand': { const target = this.objectsMatching(cost.selector, source)[0] if (!target) throw new GameError('No permanent to return') this.moveToZone(target, 'hand', { silent: false }) return } case 'put_counter': { const target = this.objectsMatching(cost.selector, source)[0] if (!target) throw new GameError('No permanent for counter') this.addCounters(target, cost.counter, 1) return } case 'remove_counters': { const amount = this.value(cost.amount, context) const objects = cost.selector ? this.objectsMatching(cost.selector, source) : [source] const target = objects.find(object => (object.counters[cost.counter] ?? 0) >= amount) if (!target) throw new GameError('No counters to remove') target.counters[cost.counter] = Math.max(0, (target.counters[cost.counter] ?? 0) - amount) return } case 'mill': this.millCards(playerId, this.value(cost.amount, context)) return case 'reveal': case 'behold': case 'choose': return case 'choice': { const option = cost.options.find(entries => entries.every(entry => entry.kind === 'mana' || this.canPayNonManaCost(entry, playerId, source))) if (!option) throw new GameError('No payable cost choice') this.payCosts(option, playerId, source, context) return } case 'waterbend': case 'blight': case 'forage': case 'collect_evidence': throw new GameError(`Unsupported cost: ${cost.kind}`) default: throw new GameError(`Unsupported cost: ${(cost as { kind: string }).kind}`) } } // --------------------------------------------------------------------------- // Targeting // --------------------------------------------------------------------------- private selectTargets( effects: Effect[], source: GameObject, controller: string, provided: TargetChoice[], mode: number, ): TargetChoice[] { const selected: TargetChoice[] = [] const queue = [...provided] const take = (target: Target, playerOnly: 'opponent' | 'any' | undefined): void => { if (target.kind === 'self' || target.kind === 'trigger_subject' || target.kind === 'previous_target') return if (target.kind === 'object' && target.mode === 'each') return if (target.kind === 'player' && target.mode === 'each') return const count = target.kind === 'object' ? target.count ?? 1 : 1 const upTo = target.kind === 'object' && Boolean(target.upTo) for (let i = 0; i < count; i++) { const explicit = queue.shift() if (explicit) { if (!this.targetChoiceMatches(explicit, target, source, playerOnly)) throw new GameError('Invalid target') selected.push(explicit) continue } const legal = this.legalTargets(target, source, controller, playerOnly) if (!legal.length) { if (upTo) break throw new GameError('No legal target') } selected.push(legal[0]) } } const walk = (list: Effect[]): void => { for (const effect of list) { if (effect.op === 'conditional') { walk(effect.effects) continue } if (effect.op === 'modal') { const chosen = effect.modes[mode] ?? effect.modes[0] ?? [] walk(chosen) continue } if ('player' in effect && (effect.player === 'target_player' || effect.player === 'opponent')) { const who = effect.player === 'opponent' ? 'opponent' : 'any' take({ kind: 'player', who: effect.player, mode: 'target' }, who) } if ('target' in effect && effect.target) take(effect.target, undefined) if (effect.op === 'fight') { take(effect.a, undefined) take(effect.b, undefined) } if (effect.op === 'damage_divided') take(effect.target, undefined) } } walk(effects) return selected } private legalTargets( target: Target, source: GameObject, controller: string, playerOnly: 'opponent' | 'any' | undefined, ): TargetChoice[] { switch (target.kind) { case 'object': { return this.objectsMatching(target.selector, source) .map(object => ({ kind: 'object' as const, id: object.id })) } case 'player': { const players = playerOnly === 'opponent' ? this.opponentsOf(controller) : this.alivePlayers().map(player => player.id) return players.map(id => ({ kind: 'player' as const, id })) } case 'player_or_planeswalker': { const choices: TargetChoice[] = this.opponentsOf(controller).map(id => ({ kind: 'player' as const, id })) for (const object of this.battlefieldObjects()) { if (this.hasType(object, 'planeswalker')) choices.push({ kind: 'object', id: object.id }) } return choices } case 'any': { const choices: TargetChoice[] = this.opponentsOf(controller).map(id => ({ kind: 'player' as const, id })) for (const object of this.battlefieldObjects()) choices.push({ kind: 'object', id: object.id }) return choices } case 'spell': return [...this.stack].reverse() .filter(item => item.kind === 'spell' && this.matchesSelector(item.source, target.selector, source, 'stack')) .map(item => ({ kind: 'spell' as const, id: item.id })) case 'ability': return [...this.stack].reverse() .filter(item => item.kind === 'ability') .map(item => ({ kind: 'spell' as const, id: item.id })) case 'divided': return this.opponentsOf(controller).map(id => ({ kind: 'player' as const, id })) default: return [] } } private targetChoiceMatches( choice: TargetChoice, target: Target, source: GameObject, playerOnly: 'opponent' | 'any' | undefined, ): boolean { const isOpponent = (id: string): boolean => this.opponentsOf(source.controller).includes(id) if (choice.kind === 'player') { if (target.kind === 'any' || target.kind === 'player' || target.kind === 'player_or_planeswalker') { return playerOnly !== 'opponent' || isOpponent(choice.id) } return false } if (choice.kind === 'object') { const object = this.objects.get(choice.id) if (!object) return false if (target.kind === 'any' || target.kind === 'player_or_planeswalker') { return target.kind === 'any' ? object.zone === 'battlefield' : this.hasType(object, 'planeswalker') } if (target.kind !== 'object') return false return this.matchesSelector(object, target.selector, source) } if (choice.kind === 'spell') { const item = this.findStackItem(choice.id) if (!item) return false if (target.kind === 'spell') { return item.kind === 'spell' && this.matchesSelector(item.source, target.selector, source, 'stack') } return target.kind === 'ability' && item.kind === 'ability' } return false } private resolveTargets(context: EffectContext, target: Target): ResolvedTarget[] { let result: ResolvedTarget[] = [] switch (target.kind) { case 'self': result = [{ kind: 'object', object: context.source }] break case 'trigger_subject': if (context.triggerSubject) result = [{ kind: 'object', object: context.triggerSubject }] break case 'previous_target': if (context.lastTarget) result = [context.lastTarget] break case 'object': if (target.mode === 'each') { result = this.objectsMatching(target.selector, context.source) .map(object => ({ kind: 'object' as const, object })) } else { const count = target.count ?? 1 for (let i = 0; i < count; i++) { const choice = context.targets.shift() if (!choice) break if (choice.kind === 'object') { const object = this.objects.get(choice.id) if (object) result.push({ kind: 'object', object }) } } } break case 'player': if (target.mode === 'each') { result = this.playersForEffect(target.who, context).map(id => ({ kind: 'player' as const, id })) } else { const choice = context.targets.shift() if (choice?.kind === 'player') result = [{ kind: 'player', id: choice.id }] else { const id = this.playersForEffect(target.who, context)[0] if (id) result = [{ kind: 'player', id }] } } break case 'player_or_planeswalker': case 'any': { const choice = context.targets.shift() if (choice?.kind === 'player') result = [{ kind: 'player', id: choice.id }] else if (choice?.kind === 'object') { const object = this.objects.get(choice.id) if (object) result = [{ kind: 'object', object }] } break } case 'spell': case 'ability': { const choice = context.targets.shift() if (choice?.kind === 'spell') { const item = this.findStackItem(choice.id) if (item) result = [{ kind: 'stack', item }] } break } case 'divided': { const choice = context.targets.shift() if (choice?.kind === 'player') result = [{ kind: 'player', id: choice.id }] else if (choice?.kind === 'object') { const object = this.objects.get(choice.id) if (object) result = [{ kind: 'object', object }] } break } } if (result.length) context.lastTarget = result[0] return result } private playersForEffect(ref: PlayerRef, context: EffectContext): string[] { const controller = context.source.controller switch (ref) { case 'you': return [controller] case 'opponent': { const choice = context.targets.shift() if (choice?.kind === 'player') return [choice.id] return [this.opponentsOf(controller)[0]].filter(Boolean) } case 'each_opponent': return this.opponentsOf(controller) case 'each_player': return this.alivePlayers().map(player => player.id) case 'target_player': { const choice = context.targets.shift() return [choice?.kind === 'player' ? choice.id : undefined].filter((id): id is string => Boolean(id)) } case 'that_player': return [context.eventPlayer ?? this.opponentsOf(controller)[0]].filter(Boolean) case 'its_controller': return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.controller] : [] case 'its_owner': return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.owner] : [] } } private playersForValue(ref: PlayerRef, context: EffectContext): string[] { const controller = context.source.controller switch (ref) { case 'you': return [controller] case 'opponent': return [this.opponentsOf(controller)[0]].filter(Boolean) case 'each_opponent': return this.opponentsOf(controller) case 'each_player': return this.alivePlayers().map(player => player.id) case 'target_player': return [context.lastTarget?.kind === 'player' ? context.lastTarget.id : this.opponentsOf(controller)[0]].filter(Boolean) case 'that_player': return [context.eventPlayer ?? this.opponentsOf(controller)[0]].filter(Boolean) case 'its_controller': return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.controller] : [] case 'its_owner': return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.owner] : [] } } // --------------------------------------------------------------------------- // Effects // --------------------------------------------------------------------------- private applyEffects(context: EffectContext, effects: Effect[]): void { for (const effect of effects) { if (this.status === 'finished') return switch (effect.op) { case 'damage': { const targets = this.resolveTargets(context, effect.target) const amount = Math.max(0, this.value(effect.amount, context)) let source = context.source if (effect.source) { const sourceTarget = this.resolveTargets(context, effect.source)[0] if (sourceTarget?.kind === 'object') source = sourceTarget.object } for (const target of targets) this.damageTarget(target, amount, source, false) break } case 'draw': { const amount = this.value(effect.amount, context) for (const playerId of this.playersForEffect(effect.player, context)) this.drawCards(playerId, amount) break } case 'discard': { const amount = this.value(effect.amount, context) for (const playerId of this.playersForEffect(effect.player, context)) { this.discardCards(playerId, amount, effect.random, context) } break } case 'mill': { const amount = this.value(effect.amount, context) for (const playerId of this.playersForEffect(effect.player, context)) this.millCards(playerId, amount) break } case 'life': { const amount = this.value(effect.amount, context) for (const playerId of this.playersForEffect(effect.player, context)) { if (effect.mode === 'gain') this.gainLife(playerId, amount) else this.loseLife(playerId, amount) } break } case 'pump': { const targets = this.resolveTargets(context, effect.target) const ids = targets.filter((target): target is Extract => target.kind === 'object') .map(target => target.object.id) this.addContinuousEffect(context.source, context.controller, effect, ids, effect.duration) break } case 'set_pt': { const targets = this.resolveTargets(context, effect.target) const ids = targets.filter((target): target is Extract => target.kind === 'object') .map(target => target.object.id) this.addContinuousEffect(context.source, context.controller, effect, ids, effect.duration) break } case 'grant': { const targets = this.resolveTargets(context, effect.target) const ids = targets.filter((target): target is Extract => target.kind === 'object') .map(target => target.object.id) this.addContinuousEffect(context.source, context.controller, effect, ids, effect.duration) break } case 'put_counters': { const amount = this.value(effect.amount, context) for (const target of this.resolveTargets(context, effect.target)) { if (target.kind === 'object') this.addCounters(target.object, effect.counter, amount) } break } case 'remove_counters': { const amount = this.value(effect.amount, context) for (const target of this.resolveTargets(context, effect.target)) { if (target.kind !== 'object') continue target.object.counters[effect.counter] = Math.max(0, (target.object.counters[effect.counter] ?? 0) - amount) } break } case 'proliferate': { for (const object of this.battlefieldObjects()) { for (const counter of Object.keys(object.counters)) { if (object.counters[counter] > 0) object.counters[counter]++ } } break } case 'create_token': { const amount = Math.max(0, this.value(effect.amount, context)) const players = this.playersForEffect(effect.player, context) for (const playerId of players) { for (let i = 0; i < amount; i++) { if (effect.copyOf) { const source = this.resolveTargets(context, effect.copyOf).find(target => target.kind === 'object') if (source?.kind === 'object') this.createTokenCopy(playerId, source.object, effect.notLegendary) } else { this.createToken(playerId, effect.token, context) } } } break } case 'destroy': { for (const target of this.resolveTargets(context, effect.target)) { if (target.kind === 'object') this.destroyPermanent(target.object) } break } case 'exile': { for (const target of this.resolveTargets(context, effect.target)) { if (target.kind === 'object') this.moveToZone(target.object, 'exile', { silent: false }) } break } case 'exile_graveyards': { for (const player of this.players) { for (const id of [...player.graveyard]) this.moveToZone(id, 'exile', { silent: false }) } break } case 'sacrifice': { const players = this.playersForEffect(effect.player, context) if (effect.unless && this.tryPayUnless(effect.unless, players[0], context.source, context)) break const targets = this.resolveTargets(context, effect.target) for (const target of targets) { if (target.kind === 'object' && players.includes(target.object.controller)) { this.moveToZone(target.object, 'graveyard', { silent: false }) } } break } case 'counter': { if (effect.unless && this.tryPayUnless(effect.unless, context.controller, context.source, context)) break for (const target of this.resolveTargets(context, effect.target)) { if (target.kind === 'stack') this.counterStackItem(target.item) } break } case 'return_to_hand': { for (const target of this.resolveTargets(context, effect.target)) { if (target.kind === 'object') this.moveToZone(target.object, 'hand', { silent: false }) } break } case 'return_to_battlefield': { const targets = this.resolveTargets(context, effect.target) for (const target of targets) { if (target.kind !== 'object') continue this.moveToZone(target.object, 'battlefield', { controller: context.controller, tapped: effect.tapped, silent: false, }) if (effect.counters) { this.addCounters(target.object, effect.counters.counter, this.value(effect.counters.amount, context)) } } break } case 'put_on_top': { for (const target of this.resolveTargets(context, effect.target)) { if (target.kind === 'object') this.moveToZone(target.object, 'library', { toTop: true, silent: false }) } break } case 'tap': { for (const target of this.resolveTargets(context, effect.target)) { if (target.kind === 'object') target.object.tapped = true } break } case 'untap': { for (const target of this.resolveTargets(context, effect.target)) { if (target.kind === 'object') target.object.tapped = false } break } case 'scry': case 'surveil': break case 'search': { const amount = Math.max(0, this.value(effect.amount, context)) for (const playerId of this.playersForEffect(effect.player, context)) { this.searchLibrary(playerId, effect.selector, amount, effect.destination, effect.tapped, effect.shuffle, effect.zones, effect.split) } break } case 'shuffle': { for (const playerId of this.playersForEffect(effect.player, context)) this.shuffleLibrary(this.getPlayer(playerId)) break } case 'add_mana': { for (const playerId of this.playersForEffect(effect.player, context)) this.addMana(playerId, effect.mana) break } case 'fight': { const a = this.resolveTargets(context, effect.a)[0] const b = this.resolveTargets(context, effect.b)[0] if (a?.kind === 'object' && b?.kind === 'object') { const aPower = this.getPower(a.object) const bPower = this.getPower(b.object) this.damageTarget({ kind: 'object', object: a.object }, bPower, b.object, false) this.damageTarget({ kind: 'object', object: b.object }, aPower, a.object, false) } break } case 'regenerate': { for (const target of this.resolveTargets(context, effect.target)) { if (target.kind === 'object') target.object.regenerationShields++ } break } case 'energy': { const amount = this.value(effect.amount, context) for (const playerId of this.playersForEffect(effect.player, context)) this.getPlayer(playerId).energy += amount break } case 'attach': { const target = this.resolveTargets(context, effect.target)[0] if (target?.kind === 'object') this.attach(context.source, target.object) break } case 'restriction': { const targets = this.resolveTargets(context, effect.target) const ids = targets.filter((target): target is Extract => target.kind === 'object') .map(target => target.object.id) this.addContinuousEffect(context.source, context.controller, effect, ids, effect.duration) break } case 'keyword_action': break case 'prevent_damage': case 'gain_control': case 'emblem': case 'transform': case 'schedule': case 'level_up': case 'put_from_among': case 'look_top': break case 'pay': try { this.payCosts(effect.costs, context.controller, context.source, context) } catch { // "You may pay" — doing nothing is the legal choice when it is not payable. } break case 'conditional': if (this.checkCondition(effect.condition, context.source)) this.applyEffects(context, effect.effects) break case 'modal': { const chosen = effect.modes[context.mode] ?? effect.modes[0] if (chosen) this.applyEffects(context, chosen) break } case 'dig': this.dig(context, effect) break case 'damage_divided': { const targets = this.resolveTargets(context, effect.target) const amount = this.value(effect.amount, context) if (targets.length) { const each = Math.floor(amount / targets.length) for (const target of targets) this.damageTarget(target, each, context.source, false) } break } case 'hideaway': this.hideaway(context, effect) break case 'play_exiled': { const playerId = this.playersForEffect(effect.player, context)[0] const cardId = context.source.linkedExile?.find(id => this.getObject(id).zone === 'exile') if (!playerId || !cardId) break const object = this.getObject(cardId) if (this.playExiledCard(playerId, object, effect.free)) { context.source.linkedExile = context.source.linkedExile?.filter(id => id !== cardId) } break } } } } private hideaway(context: EffectContext, effect: Extract): void { // shortcut: auto-pick the top card; face-down exile and the look/choice are not modelled. const player = this.getPlayer(context.controller) const amount = this.value(effect.amount, context) const top = player.library.slice(0, amount).map(id => this.getObject(id)) const hidden = top.shift() if (!hidden) return this.moveToZone(hidden, 'exile', { silent: true }) context.source.linkedExile = [...(context.source.linkedExile ?? []), hidden.id] for (let index = top.length - 1; index > 0; index--) { const swap = Math.floor(this.rng() * (index + 1)) const temp = top[index] top[index] = top[swap] top[swap] = temp } for (const object of top) this.moveToZone(object, 'library', { silent: true }) this.logMessage(`${player.name} hides away a card`) } private playExiledCard(playerId: string, object: GameObject, free: boolean | undefined): boolean { if (!free) return false if (this.isLand(object)) { const player = this.getPlayer(playerId) if (player.landPlayedThisTurn || !this.isMainPhaseWithEmptyStack(playerId)) return false player.landPlayedThisTurn = true this.moveToZone(object, 'battlefield', { controller: playerId, silent: false }) this.logMessage(`${this.getPlayer(playerId).name} plays ${object.definition.name} from exile`) return true } if (!this.canCastAtThisTime(playerId, object)) return false const effects = (object.definition.abilities ?? []) .filter((ability): ability is Extract => ability.kind === 'spell') .flatMap(ability => ability.effects) let targets: TargetChoice[] try { targets = this.selectTargets(effects, object, playerId, [], 0) } catch { return false } this.moveToZone(object, 'stack', { controller: playerId, silent: true }) const item: StackItem = { id: this.generateId('stack'), kind: 'spell', source: object, controller: playerId, label: object.definition.name, effects, targets, x: 0, mode: 0, } this.stack.push(item) this.getPlayer(playerId).spellsCastThisTurn++ this.passesInRow = 0 this.priority = this.nextAlivePlayer(playerId) this.dispatchEvent({ kind: 'cast', player: playerId, subject: object, spell: object, spellItem: item }) this.logMessage(`${this.getPlayer(playerId).name} casts ${object.definition.name} from exile`) return true } private dig( context: EffectContext, effect: Extract, ): void { const player = this.getPlayer(context.controller) const amount = this.value(effect.amount, context) const top = player.library.slice(0, amount).map(id => this.getObject(id)) const pickCount = this.value(effect.pick, context) const picked = top.filter(object => !effect.pickSelector || this.matchesSelector(object, effect.pickSelector, context.source, 'library')) .slice(0, pickCount) for (const object of picked) { if (effect.to === 'battlefield') { this.moveToZone(object, 'battlefield', { controller: context.controller, tapped: effect.tapped, silent: false }) } else { this.moveToZone(object, 'hand', { silent: false }) } } for (const object of top) { if (picked.includes(object)) continue if (effect.rest === 'graveyard') this.moveToZone(object, 'graveyard', { silent: false }) else if (effect.rest === 'bottom') this.moveToZone(object, 'library', { silent: true }) else this.moveToZone(object, 'library', { toTop: true, silent: true }) } } private tryPayUnless(cost: Cost, playerId: string | undefined, source: GameObject, context: EffectContext): boolean { if (!playerId) return false try { if (cost.kind === 'mana') { this.payMana(playerId, cost.symbols, context.x) } else { if (!this.canPayNonManaCost(cost, playerId, source)) return false this.payNonManaCost(cost, playerId, source, context) } return true } catch { return false } } private addContinuousEffect( source: GameObject, controller: string, effect: Extract, affectedIds: string[], duration: Duration, ): void { this.continuousEffects.push({ id: this.generateId('effect'), sourceId: source.id, controller, effect, affectedIds, duration, createdTurn: this.turn, }) } private continuousContext(effect: ContinuousEffect): EffectContext { const source = this.objects.get(effect.sourceId) ?? this.playerSource(effect.controller) return this.contextFor(source, effect.controller, [], 0, 0) } private staticContext(source: GameObject): EffectContext { return this.contextFor(source, source.controller, [], 0, 0) } private contextFor( source: GameObject, controller: string, targets: TargetChoice[], x: number, mode: number, triggerSubject?: GameObject, eventPlayer?: string, eventAmount?: number, ): EffectContext { return { source, controller, targets: [...targets], x, mode, triggerSubject, eventPlayer, eventAmount } } private value(value: Value, context: EffectContext): number { switch (value.kind) { case 'number': return value.value case 'x': return context.x case 'count': return this.objectsMatching(value.selector, context.source).length case 'source_power': return this.getPower(context.source) case 'source_toughness': return this.getToughness(context.source) case 'cards_in_hand': { const playerId = this.playersForValue(value.player, context)[0] return playerId ? this.getPlayer(playerId).hand.length : 0 } case 'max_cards_in_hand': return Math.max(...this.alivePlayers().map(player => player.hand.length), 0) case 'max_opponent_count': return Math.max(...this.opponentsOf(context.source.controller).map(playerId => this.objectsMatching(value.selector, context.source) .filter(object => object.controller === playerId).length), 0) case 'total_mana_value': return this.objectsMatching(value.selector, context.source) .reduce((total, object) => total + manaValueOf(object.definition), 0) case 'total_power': return this.objectsMatching(value.selector, context.source) .reduce((total, object) => total + this.getPower(object), 0) case 'any_number': return 0 case 'event_amount': return context.eventAmount ?? 0 } } private damageTarget( target: ResolvedTarget, amount: number, source: GameObject, combat: boolean, ): void { if (amount <= 0) return if (target.kind === 'player') { if (combat && source.isCommander) { const defender = this.getPlayer(target.id) defender.commanderDamage[source.id] = (defender.commanderDamage[source.id] ?? 0) + amount } this.getPlayer(target.id).damageTakenThisTurn += amount this.loseLife(target.id, amount) this.dispatchEvent({ kind: 'deals_damage', player: source.controller, subject: source, recipient: 'player', amount, combat }) } else if (target.kind === 'object') { const object = target.object if (object.zone !== 'battlefield') return object.damage += amount if (this.hasKeyword(source, 'Deathtouch')) object.deathtouched = true this.dispatchEvent({ kind: 'deals_damage', player: source.controller, subject: source, recipient: this.isCreature(object) ? 'creature' : 'permanent', amount, combat, }) } if (this.hasKeyword(source, 'Lifelink')) this.gainLife(source.controller, amount) } private destroyPermanent(object: GameObject): void { if (object.zone !== 'battlefield') return if (this.hasKeyword(object, 'Indestructible')) return if (object.regenerationShields > 0) { object.regenerationShields-- object.tapped = true object.damage = 0 object.deathtouched = false object.attacking = undefined object.blockedBy = [] object.blocking = undefined return } this.moveToZone(object, 'graveyard', { silent: false }) } private createToken(playerId: string, spec: TokenSpec, context: EffectContext): GameObject { const definition = tokenCard({ ...spec, power: spec.power ? this.value(spec.power, context) : undefined, toughness: spec.toughness ? this.value(spec.toughness, context) : undefined, }) const player = this.getPlayer(playerId) const object: GameObject = { id: this.generateId('token'), definition, owner: playerId, controller: playerId, zone: 'battlefield', tapped: false, damage: 0, deathtouched: false, counters: {}, isToken: true, token: spec, enteredTurn: this.turn, blockedBy: [], attachments: [], regenerationShields: 0, activations: {}, } this.objects.set(object.id, object) this.moveToZone(object, 'battlefield', { controller: playerId, tapped: spec.tapped ?? false, silent: false }) return object } private createTokenCopy(playerId: string, source: GameObject, notLegendary = false): GameObject { const definition = notLegendary ? { ...source.definition, typeLine: source.definition.typeLine.replace(/\bLegendary\s+/i, '') } : source.definition const object: GameObject = { id: this.generateId('token'), definition, owner: playerId, controller: playerId, zone: 'battlefield', tapped: false, damage: 0, deathtouched: false, counters: {}, isToken: true, token: source.token, enteredTurn: this.turn, blockedBy: [], attachments: [], regenerationShields: 0, activations: {}, } this.objects.set(object.id, object) this.moveToZone(object, 'battlefield', { controller: playerId, tapped: false, silent: false }) return object } private attach(source: GameObject, target: GameObject): void { if (source.attachedTo) { const previous = this.objects.get(source.attachedTo) if (previous) previous.attachments = previous.attachments.filter(id => id !== source.id) } source.attachedTo = target.id if (!target.attachments.includes(source.id)) target.attachments.push(source.id) } private addCounters(object: GameObject, counter: string, amount: number, silent = false): void { if (amount === 0) return object.counters[counter] = Math.max(0, (object.counters[counter] ?? 0) + amount) if (!silent) this.dispatchEvent({ kind: 'counter_placed', player: object.controller, subject: object, amount, counter }) } // --------------------------------------------------------------------------- // Triggers, statics, and conditions // --------------------------------------------------------------------------- private dispatchEvent(event: EventContext): void { if (this.status !== 'active') return const sources = this.battlefieldObjects() if (event.subject && event.subject.zone !== 'battlefield' && !sources.includes(event.subject)) { sources.push(event.subject) } sources.sort((a, b) => { const aFirst = a.controller === this.activePlayer ? 0 : 1 const bFirst = b.controller === this.activePlayer ? 0 : 1 return aFirst - bFirst }) let added = 0 for (const source of sources) { for (const ability of source.definition.abilities ?? []) { if (ability.kind !== 'triggered') continue if (ability.condition && !this.checkCondition(ability.condition, source)) continue if (!this.matchesTrigger(event, ability.event, source)) continue let targets: TargetChoice[] try { targets = this.selectTargets(ability.effects, source, source.controller, [], 0) } catch { continue } this.stack.push({ id: this.generateId('stack'), kind: 'ability', source, controller: source.controller, label: ability.text, effects: ability.effects, targets, x: 0, mode: 0, triggerSubject: event.subject, eventPlayer: event.player, eventAmount: event.amount, }) added++ } } if (added) { this.passesInRow = 0 this.priority = this.activePlayer } } private matchesTrigger(event: EventContext, trigger: TriggerEvent, source: GameObject): boolean { switch (trigger.kind) { case 'enters': case 'dies': case 'attacks': case 'blocks': case 'leaves_battlefield': return event.kind === trigger.kind && this.subjectMatches(trigger.subject, source, event) case 'enters_or_attacks': return (event.kind === 'enters' || event.kind === 'attacks') && this.subjectMatches(trigger.subject, source, event) case 'enters_or_dies': return (event.kind === 'enters' || event.kind === 'dies') && this.subjectMatches(trigger.subject, source, event) case 'attacks_or_blocks': return (event.kind === 'attacks' || event.kind === 'blocks') && this.subjectMatches(trigger.subject, source, event) case 'counter_placed': return event.kind === 'counter_placed' && this.subjectMatches(trigger.subject, source, event) && (!trigger.counter || trigger.counter === event.counter) case 'upkeep': case 'end_step': case 'begin_combat': return event.kind === trigger.kind && this.whoMatches(trigger.who, source, event.player) case 'main_phase': return event.kind === 'main_phase' && this.whoMatches(trigger.who, source, event.player) case 'cast': if (event.kind !== 'cast' || !event.spell) return false if (!this.whoMatches(trigger.who, source, event.player)) return false if (!this.matchesSelector(event.spell, trigger.spell, source, 'stack')) return false if (trigger.targetsSelf && !(event.spellItem?.targets.some(choice => choice.kind === 'object' && choice.id === source.id))) { return false } return true case 'draw': if (event.kind !== 'draw' || !this.whoMatches(trigger.who, source, event.player)) return false return !trigger.ordinal || trigger.ordinal === event.ordinal case 'life': if (event.kind !== 'life' || !this.whoMatches(trigger.who, source, event.player)) return false return trigger.mode === event.mode case 'deals_damage': if (event.kind !== 'deals_damage' || !this.subjectMatches(trigger.subject, source, event)) return false if (trigger.combat && !event.combat) return false return trigger.recipient === 'any' || trigger.recipient === event.recipient case 'becomes_target': case 'becomes_level': return false } } private subjectMatches(target: Target, source: GameObject, event: EventContext): boolean { if (!event.subject) return false if (target.kind === 'self' || target.kind === 'trigger_subject') return event.subject.id === source.id if (target.kind !== 'object') return false if (target.selector.other && event.subject.id === source.id && !target.includeSelf) return false return this.matchesSelector(event.subject, target.selector, source, event.subject.zone) } private whoMatches(who: 'you' | 'opponent' | 'each_player', source: GameObject, eventPlayer: string | undefined): boolean { if (who === 'each_player') return true if (!eventPlayer) return false return who === 'you' ? source.controller === eventPlayer : source.controller !== eventPlayer } private staticAbilities(): { source: GameObject; ability: Extract }[] { const result: { source: GameObject; ability: Extract }[] = [] for (const source of this.battlefieldObjects()) { for (const ability of source.definition.abilities ?? []) { if (ability.kind !== 'static') continue if (ability.condition && !this.checkCondition(ability.condition, source)) continue result.push({ source, ability }) } } return result } private staticTargets(source: GameObject, target: Target): GameObject[] { if (target.kind === 'self') return [source] if (target.kind !== 'object') return [] return this.objectsMatching(target.selector, source) } private exilesInsteadOfGraveyard(object: GameObject): boolean { for (const { source, ability } of this.staticAbilities()) { for (const effect of ability.effects) { if (effect.op !== 'exile_instead_of_graveyard') continue if (effect.owner === 'opponent' && object.owner === source.controller) continue if (effect.owner === 'you' && object.owner !== source.controller) continue return true } } return false } private applyEntersReplacements(object: GameObject): void { for (const staticSource of this.staticAbilities()) { for (const effect of staticSource.ability.effects) { if (effect.op === 'enters_tapped') { if (effect.unless && this.checkCondition(effect.unless, staticSource.source)) continue if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue if (effect.unlessCost && !object.tapped) { const context = this.staticContext(staticSource.source) this.pendingChoices.push({ playerId: object.controller, sourceId: object.id, what: 'pay_cost', cost: effect.unlessCost, amount: effect.unlessCost.kind === 'pay_life' ? this.value(effect.unlessCost.amount, context) : undefined, }) continue } object.tapped = true } else if (effect.op === 'enters_with_counters') { if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue const amount = this.value(effect.amount, this.staticContext(staticSource.source)) this.addCounters(object, effect.counter, amount, true) } } } } /** Queues the "as this enters, choose a creature type" prompt for a new permanent. */ private queueEnterChoices(object: GameObject): void { for (const ability of object.definition.abilities ?? []) { if (ability.kind !== 'static') continue if (!ability.effects.some(effect => effect.op === 'choose' && effect.what === 'creature_type')) continue this.pendingChoices.push({ playerId: object.controller, sourceId: object.id, what: 'creature_type' }) return } } private hasRestriction(object: GameObject, rule: string): boolean { for (const staticSource of this.staticAbilities()) { for (const effect of staticSource.ability.effects) { if (effect.op !== 'restriction' || (effect.rule !== rule && !effect.rule.startsWith(`${rule}_`))) continue if (this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) return true } } for (const continuous of this.continuousEffects) { if (continuous.effect.op !== 'restriction' || continuous.effect.rule !== rule) continue if (continuous.affectedIds.includes(object.id)) return true } return false } private checkCondition(condition: Condition, source: GameObject): boolean { const controller = source.controller switch (condition.kind) { case 'you_control': return this.objectsMatching(condition.selector, source).filter(object => object.controller === controller).length >= (condition.atLeast ?? 1) case 'opponent_controls': return this.opponentsOf(controller).some(playerId => this.objectsMatching(condition.selector, source) .some(object => object.controller === playerId)) case 'your_turn': return this.activePlayer === controller case 'not_your_turn': return this.activePlayer !== controller case 'source_tapped': return source.tapped case 'source_untapped': return !source.tapped case 'source_attacking': return Boolean(source.attacking) case 'life_at_least': return this.playersForValue(condition.player, this.staticContext(source)) .some(playerId => this.getPlayer(playerId).life >= condition.amount) case 'life_at_most': return this.playersForValue(condition.player, this.staticContext(source)) .some(playerId => this.getPlayer(playerId).life <= condition.amount) case 'cards_in_graveyard': return this.playersForValue(condition.player, this.staticContext(source)) .some(playerId => this.getPlayer(playerId).graveyard.length >= condition.atLeast) case 'hand_empty': return this.playersForValue(condition.player, this.staticContext(source)) .some(playerId => this.getPlayer(playerId).hand.length === 0) case 'creature_died_this_turn': return this.getPlayer(controller).creaturesDiedThisTurn > 0 case 'you_gained_life_this_turn': return this.getPlayer(controller).lifeGainedThisTurn >= (condition.atLeast ?? 1) case 'you_drew_cards_this_turn': return this.getPlayer(controller).cardsDrawnThisTurn >= (condition.atLeast ?? 1) case 'attacked_this_turn': return this.getPlayer(controller).attackedThisTurn case 'you_attacked_this_turn': return this.getPlayer(controller).attackedThisTurn case 'attacked_with_creatures': return this.getPlayer(controller).creaturesAttackedThisTurn >= condition.atLeast case 'opponent_damaged_this_turn': return this.opponentsOf(controller) .some(playerId => this.getPlayer(playerId).damageTakenThisTurn >= condition.atLeast) case 'library_at_most': return this.alivePlayers().some(player => player.library.length <= condition.atMost) case 'no_objects': return this.objectsMatching(condition.selector, source).length === 0 case 'cards_in_hand_at_most': { const players = this.playersForValue(condition.who, this.staticContext(source)) const check = (playerId: string): boolean => this.getPlayer(playerId).hand.length <= condition.atMost return condition.who === 'each_player' || condition.who === 'each_opponent' ? players.every(check) : players.some(check) } case 'on_battlefield': return source.zone === 'battlefield' case 'in_graveyard': return source.zone === 'graveyard' case 'not_token': return !source.isToken case 'full_party': return false case 'you_control_commander': return this.battlefieldObjects().some(object => object.controller === controller && object.isCommander) case 'distinct_names': return new Set(this.objectsMatching(condition.selector, source) .filter(object => object.controller === controller) .map(object => object.definition.name.toLowerCase())).size >= condition.atLeast case 'total_power': return this.battlefieldObjects() .filter(object => object.controller === controller && this.isCreature(object)) .reduce((total, object) => total + this.getPower(object), 0) >= condition.atLeast default: return false } } // --------------------------------------------------------------------------- // Combat damage // --------------------------------------------------------------------------- private dealCombatDamage(): void { const attackers = this.battlefieldObjects().filter(object => object.attacking) const anyFirstStrike = attackers.some(object => this.hasKeyword(object, 'First strike') || this.hasKeyword(object, 'Double strike')) || attackers.some(object => object.blockedBy .map(id => this.objects.get(id)) .some(blocker => blocker && (this.hasKeyword(blocker, 'First strike') || this.hasKeyword(blocker, 'Double strike')))) if (anyFirstStrike) this.dealCombatDamageRound(true) this.dealCombatDamageRound(false) this.step = 'end_combat' this.passesInRow = 0 this.priority = this.activePlayer } private dealCombatDamageRound(firstStrike: boolean): void { for (const attacker of this.battlefieldObjects()) { if (attacker.zone !== 'battlefield' || !attacker.attacking) continue const doubleStrike = this.hasKeyword(attacker, 'Double strike') const first = this.hasKeyword(attacker, 'First strike') if (firstStrike ? (!first && !doubleStrike) : (first && !doubleStrike)) continue let power = this.getPower(attacker) const blockers = attacker.blockedBy .map(id => this.objects.get(id)) .filter((object): object is GameObject => Boolean(object && object.zone === 'battlefield' && object.blocking === attacker.id)) const deathtouch = this.hasKeyword(attacker, 'Deathtouch') const trample = this.hasKeyword(attacker, 'Trample') if (!blockers.length) { this.damageDefender(attacker, power) } else { let remaining = power for (let index = 0; index < blockers.length && remaining > 0; index++) { const blocker = blockers[index] const lethal = deathtouch ? 1 : Math.max(0, this.getToughness(blocker) - blocker.damage) const assign = index === blockers.length - 1 && !trample ? remaining : Math.min(remaining, Math.max(lethal, 1)) if (assign <= 0) continue this.damageTarget({ kind: 'object', object: blocker }, assign, attacker, true) remaining -= assign } if (trample && remaining > 0) this.damageDefender(attacker, remaining) for (const blocker of blockers) { if (blocker.zone !== 'battlefield' || blocker.blocking !== attacker.id) continue const blockerDouble = this.hasKeyword(blocker, 'Double strike') const blockerFirst = this.hasKeyword(blocker, 'First strike') if (firstStrike ? (!blockerFirst && !blockerDouble) : (blockerFirst && !blockerDouble)) continue this.damageTarget({ kind: 'object', object: attacker }, this.getPower(blocker), blocker, true) } } } this.runStateBasedActions() } private damageDefender(attacker: GameObject, amount: number): void { const defenderId = attacker.attacking if (!defenderId) return const player = this.players.find(entry => entry.id === defenderId) if (player) { this.damageTarget({ kind: 'player', id: player.id }, amount, attacker, true) return } const permanent = this.objects.get(defenderId) if (permanent?.zone === 'battlefield') { this.damageTarget({ kind: 'object', object: permanent }, amount, attacker, true) } } private requireCanAttack(attacker: GameObject, playerId: string): void { if (attacker.zone !== 'battlefield') throw new GameError('Attacker is not on the battlefield') if (attacker.controller !== playerId) throw new GameError('You do not control that creature') if (!this.isCreature(attacker)) throw new GameError('Only creatures can attack') if (attacker.tapped) throw new GameError('Tapped creatures cannot attack') if (attacker.enteredTurn >= this.turn && !this.hasKeyword(attacker, 'Haste')) { throw new GameError('That creature has summoning sickness') } if (this.hasRestriction(attacker, 'cant_attack')) throw new GameError('That creature cannot attack') } private hasMeaningfulAction(playerId: string): boolean { if (this.status !== 'active' || this.priority !== playerId || this.pendingChoice) return false const player = this.getPlayer(playerId) if (player.lost) return false if (this.phase === 'combat' && this.step === 'declare_attackers' && !this.stack.length && this.activePlayer === playerId && this.canAttackWithAny(playerId)) { return true } if (this.phase === 'combat' && this.step === 'declare_blockers' && !this.stack.length && this.canBlockWithAny(playerId)) { return true } if ([...player.hand, ...player.command].some(id => this.canPlayCard(playerId, id))) return true for (const id of player.battlefield) { const object = this.objects.get(id) if (!object) continue const abilities = object.definition.abilities ?? [] for (let index = 0; index < abilities.length; index++) { const ability = abilities[index] if (ability.kind !== 'activated') continue // Mana abilities alone do not advance the game; counting them would // stop auto-pass on every untapped land. if (ability.effects.length && ability.effects.every(effect => effect.op === 'add_mana')) continue if (this.isActivatedAbilityPlayable(playerId, object, index, ability)) return true } } return false } private isActivatedAbilityPlayable( playerId: string, source: GameObject, index: number, ability: Extract, ): boolean { if (source.zone !== 'battlefield' || source.controller !== playerId) return false if (this.hasRestriction(source, 'cant_activate')) return false if (ability.condition && !this.checkCondition(ability.condition, source)) return false if (ability.timing === 'sorcery' && !this.isMainPhaseWithEmptyStack(playerId)) return false if (ability.costs.some(cost => cost.kind === 'tap') && this.isCreature(source) && source.enteredTurn >= this.turn && !this.hasKeyword(source, 'Haste')) { return false } if (ability.activationsPerTurn !== undefined && (source.activations[index] ?? 0) >= ability.activationsPerTurn) { return false } for (const cost of ability.costs) { if (cost.kind === 'mana') { if (!this.canAffordMana(playerId, cost.symbols, 0)) return false } else if (!this.canPayNonManaCost(cost, playerId, source)) { return false } } return this.hasLegalTargets(source, playerId, ability.effects) } private hasLegalTargets(source: GameObject, playerId: string, effects?: Effect[]): boolean { const list = effects ?? (source.definition.abilities ?? []) .filter((ability): ability is Extract => ability.kind === 'spell') .flatMap(ability => ability.effects) try { this.selectTargets(list, source, playerId, [], 0) return true } catch (error) { if (error instanceof GameError) return false throw error } } /** * Affordability check that mirrors auto-tapping without changing the game. * shortcut: only land-based any_color restrictions are modelled; mana * restricted by a commander identity or a spell type is still flexible. */ private canAffordMana(playerId: string, symbols: string, x: number): boolean { if (!symbols) return true const player = this.getPlayer(playerId) const cost = parseManaCost(symbols, x) const pool = { ...player.manaPool } let flexible = 0 const restricted: { colors: Set; amount: number }[] = [] for (const object of this.battlefieldObjects()) { if (object.controller !== playerId) continue const found = this.findFreeManaAbility(object) if (!found) continue for (const effect of found.ability.effects) { if (effect.op !== 'add_mana') continue if (effect.mana.kind === 'symbols') { for (const symbol of effect.mana.symbols) pool[colorOfSymbol(symbol)]++ } else { const amount = this.value(effect.mana.amount, { source: object, controller: playerId, targets: [], x: 0, mode: 0, }) const allowed = this.anyColorRestrictionColors(effect.mana, playerId) if (!allowed) flexible += amount else if (allowed.size) restricted.push({ colors: allowed, amount }) } } } let life = player.life restricted.sort((a, b) => a.colors.size - b.colors.size) const take = (color: ManaColor): boolean => { if (pool[color] > 0) { pool[color]-- return true } const source = restricted.find(entry => entry.amount > 0 && entry.colors.has(color)) if (source) { source.amount-- return true } if (flexible > 0) { flexible-- return true } return false } for (const color of cost.colored) { if (!take(color)) return false } for (const hybrid of cost.hybrid) { if (hybrid.colors.some(take)) continue if (!(hybrid.life > 0 && life >= hybrid.life)) return false life -= hybrid.life } const remaining = MANA_COLORS.reduce((total, color) => total + pool[color], 0) + flexible + restricted.reduce((total, entry) => total + entry.amount, 0) return remaining >= cost.generic } private canAttackWithAny(playerId: string): boolean { return this.battlefieldObjects().some(object => { try { this.requireCanAttack(object, playerId) return true } catch (error) { if (error instanceof GameError) return false throw error } }) } private canBlockWithAny(playerId: string): boolean { const attackers = this.battlefieldObjects().filter(object => object.attacking === playerId) if (!attackers.length) return false return this.battlefieldObjects().some(blocker => { if (blocker.controller !== playerId) return false if (!this.isCreature(blocker) || blocker.tapped || blocker.blocking) return false if (this.hasRestriction(blocker, 'cant_block')) return false return attackers.some(attacker => !this.hasKeyword(attacker, 'Flying') || this.hasKeyword(blocker, 'Flying') || this.hasKeyword(blocker, 'Reach')) }) } // --------------------------------------------------------------------------- // Zones, state-based actions, and utilities // --------------------------------------------------------------------------- private handleLeavesBattlefield(object: GameObject, destination: Zone): void { if (object.attachedTo) { const attached = this.objects.get(object.attachedTo) if (attached) attached.attachments = attached.attachments.filter(id => id !== object.id) object.attachedTo = undefined } for (const attachmentId of [...object.attachments]) { const attachment = this.objects.get(attachmentId) if (attachment) attachment.attachedTo = undefined } object.attachments = [] object.attacking = undefined object.blockedBy = [] object.blocking = undefined object.linkedExile = undefined for (let index = this.continuousEffects.length - 1; index >= 0; index--) { const effect = this.continuousEffects[index] if (effect.sourceId !== object.id) continue if (effect.duration === 'permanent' || effect.duration === 'while_source_on_battlefield') { this.continuousEffects.splice(index, 1) } } if (destination === 'graveyard' && this.isCreature(object)) { this.getPlayer(object.controller).creaturesDiedThisTurn++ this.dispatchEvent({ kind: 'dies', player: object.controller, subject: object }) } this.dispatchEvent({ kind: 'leaves_battlefield', player: object.controller, subject: object }) } private runStateBasedActions(): void { if (this.status !== 'active') return let changed = true let guard = 0 while (changed && guard++ < 50 && this.status === 'active') { changed = false for (const player of this.players) { if (!player.lost && (player.life <= 0 || player.poison >= 10 || Object.values(player.commanderDamage).some(damage => damage >= 21))) { this.losePlayer(player.id) changed = true } } if (this.status !== 'active') return for (const id of [...this.battlefieldObjects().map(object => object.id)]) { const object = this.objects.get(id) if (!object || object.zone !== 'battlefield' || !this.isCreature(object)) continue const lethal = this.getToughness(object) <= 0 || object.damage >= this.getToughness(object) || (object.deathtouched && object.damage > 0) if (!lethal) continue if (this.hasKeyword(object, 'Indestructible')) continue if (object.regenerationShields > 0) { object.regenerationShields-- object.tapped = true object.damage = 0 object.deathtouched = false object.attacking = undefined object.blockedBy = [] object.blocking = undefined } else { this.moveToZone(object, 'graveyard', { silent: false }) } changed = true } for (const player of this.alivePlayers()) { const legends = new Map() for (const object of this.battlefieldObjects()) { if (object.controller !== player.id || !/\blegendary\b/i.test(object.definition.typeLine)) continue const name = object.definition.name.toLowerCase() legends.set(name, [...(legends.get(name) ?? []), object]) } for (const copies of legends.values()) { // shortcut: keeps the first copy found, not the player's choice; ask when the API can pause for it for (const extra of copies.slice(1)) { this.moveToZone(extra, 'graveyard', { silent: false }) changed = true } } } } } private losePlayer(playerId: string): void { const player = this.getPlayer(playerId) if (player.lost) return player.lost = true this.logMessage(`${player.name} loses the game`) const alive = this.alivePlayers() if (alive.length <= 1) { this.status = 'finished' this.winner = alive[0]?.id if (this.winner) this.logMessage(`${this.getPlayer(this.winner).name} wins`) } } private gainLife(playerId: string, amount: number): void { if (amount <= 0) return const player = this.getPlayer(playerId) if (player.lost) return player.life += amount player.lifeGainedThisTurn += amount this.dispatchEvent({ kind: 'life', player: playerId, amount, mode: 'gain' }) } private loseLife(playerId: string, amount: number): void { if (amount <= 0) return const player = this.getPlayer(playerId) if (player.lost) return player.life -= amount this.dispatchEvent({ kind: 'life', player: playerId, amount, mode: 'lose' }) this.runStateBasedActions() } private drawCard(playerId: string, silent: boolean): void { const player = this.getPlayer(playerId) if (player.lost) return if (!player.library.length) { this.losePlayer(playerId) return } const id = player.library.shift() if (!id) return player.hand.push(id) const object = this.getObject(id) object.zone = 'hand' object.controller = playerId player.cardsDrawnThisTurn++ if (!silent) { this.dispatchEvent({ kind: 'draw', player: playerId, amount: 1, ordinal: player.cardsDrawnThisTurn }) } } private drawCards(playerId: string, amount: number): void { for (let i = 0; i < amount; i++) this.drawCard(playerId, false) } private discardCards(playerId: string, amount: number, random: boolean | undefined, context: EffectContext): void { const player = this.getPlayer(playerId) for (let i = 0; i < amount && player.hand.length; i++) { const index = random ? Math.floor(this.rng() * player.hand.length) : 0 const id = player.hand[index] this.moveToZone(id, 'graveyard', { silent: false }) } void context } private millCards(playerId: string, amount: number): void { const player = this.getPlayer(playerId) for (let i = 0; i < amount && player.library.length; i++) { const id = player.library[0] this.moveToZone(id, 'graveyard', { silent: true }) } } private searchLibrary( playerId: string, selector: ObjectSelector, amount: number, destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom', tapped: boolean, shuffle: boolean, zones?: ('library' | 'graveyard')[], split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean }, ): void { // shortcut: a search only pauses itself; later effects in the same ability // still run before the pick, and a second search in that ability is skipped. // Most search lines are a single effect. if (this.pendingSearch) return const player = this.getPlayer(playerId) let remaining = amount let first = true while (remaining > 0) { const pickDestination = first ? destination : (split?.destination ?? destination) const pickTapped = first ? tapped : (split?.tapped ?? tapped) const candidates = this.findSearchCandidates(playerId, selector, zones) if (!candidates.length) break if (candidates.length > 1) { this.pendingSearch = { playerId, selector, remaining, destination: pickDestination, tapped: pickTapped, shuffle, zones, ...(first && split && remaining > 1 ? { split } : {}), } return } this.moveSearchedCard(candidates[0], playerId, pickDestination, pickTapped) remaining-- first = false } if (shuffle) this.shuffleLibrary(player) } private findSearchCandidates( playerId: string, selector: ObjectSelector, zones?: ('library' | 'graveyard')[], ): GameObject[] { const source = this.playerSource(playerId) return this.searchableObjects(playerId, zones) .filter(object => this.matchesSelector(object, selector, source, object.zone)) } private searchableObjects(playerId: string, zones?: ('library' | 'graveyard')[]): GameObject[] { const player = this.getPlayer(playerId) const allowed = zones ?? ['library'] const libraryLimit = this.searchLibraryLimit(playerId) const ids = allowed.includes('library') ? player.library.slice(0, libraryLimit ?? player.library.length) : [] if (allowed.includes('graveyard')) ids.push(...player.graveyard) return ids.map(id => this.getObject(id)).filter(object => object.owner === playerId) } private moveSearchedCard( object: GameObject, playerId: string, destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom', tapped: boolean, ): void { if (destination === 'battlefield') { this.moveToZone(object, 'battlefield', { controller: playerId, tapped, silent: false }) } else if (destination === 'hand') { this.moveToZone(object, 'hand', { silent: false }) } else if (destination === 'graveyard') { this.moveToZone(object, 'graveyard', { silent: false }) } else if (destination === 'top') { this.moveToZone(object, 'library', { toTop: true, silent: false }) } else { this.moveToZone(object, 'library', { silent: false }) } } // shortcut: the limit is recomputed after each pick, so a multi-card search // can see one new card per pick. Upgrade when a card searches for several // cards while Aven Mindcensor is out. private searchLibraryLimit(playerId: string): number | undefined { let limit: number | undefined for (const { source, ability } of this.staticAbilities()) { for (const effect of ability.effects) { if (effect.op !== 'search_restriction') continue const applies = effect.who === 'you' ? playerId === source.controller : playerId !== source.controller if (!applies) continue const amount = this.value(effect.amount, this.staticContext(source)) limit = limit === undefined ? amount : Math.min(limit, amount) } } return limit } private shuffleLibrary(player: PlayerState): void { for (let index = player.library.length - 1; index > 0; index--) { const swap = Math.floor(this.rng() * (index + 1)) const temp = player.library[index] player.library[index] = player.library[swap] player.library[swap] = temp } } private removeFromZone(object: GameObject): void { const owner = this.getPlayer(object.owner) if (object.zone === 'battlefield') { const controller = this.getPlayer(object.controller) controller.battlefield = controller.battlefield.filter(id => id !== object.id) } else if (object.zone === 'hand') owner.hand = owner.hand.filter(id => id !== object.id) else if (object.zone === 'graveyard') owner.graveyard = owner.graveyard.filter(id => id !== object.id) else if (object.zone === 'exile') owner.exile = owner.exile.filter(id => id !== object.id) else if (object.zone === 'command') owner.command = owner.command.filter(id => id !== object.id) else if (object.zone === 'library') owner.library = owner.library.filter(id => id !== object.id) } private objectsMatching(selector: ObjectSelector, source: GameObject, zoneOverride?: Zone): GameObject[] { const zone = zoneOverride ?? selector.zone ?? 'battlefield' return [...this.objects.values()].filter(object => this.matchesSelector(object, selector, source, zone)) } private matchesSelector(object: GameObject, selector: ObjectSelector, source: GameObject, zoneOverride?: Zone): boolean { const zone = zoneOverride ?? selector.zone ?? 'battlefield' if (object.zone !== zone) return false if (selector.other && object.id === source.id) return false const typeLine = object.definition.typeLine.toLowerCase() const words = new Set(typeLine.split(/[\s—–\-/,()]+/).filter(Boolean)) const matchesWords = (values: string[]): boolean => { const matches = values.map(value => words.has(value.toLowerCase())) return selector.match === 'any' ? matches.some(Boolean) : matches.every(Boolean) } // "Permanent" is a zone property, not a word on the type line. const types = selector.types?.filter(type => type.toLowerCase() !== 'permanent') if (types?.length && !matchesWords(types)) return false if (selector.excludeTypes?.some(type => words.has(type.toLowerCase()))) return false if (selector.supertypes?.length && !matchesWords(selector.supertypes)) return false if (selector.subtypes?.length && !matchesWords(selector.subtypes)) return false if (selector.controller === 'you' && object.controller !== source.controller) return false if (selector.controller === 'opponent' && object.controller === source.controller) return false if (selector.owner === 'you' && object.owner !== source.controller) return false if (selector.owner === 'opponent' && object.owner === source.controller) return false const colors = object.definition.colors ?? [] if (selector.colors?.length) { const matches = selector.colors.map(color => colors.includes(color)) if (selector.match === 'any' ? !matches.some(Boolean) : !matches.every(Boolean)) return false } if (selector.tapped !== undefined && object.tapped !== selector.tapped) return false if (selector.attacking !== undefined && Boolean(object.attacking) !== selector.attacking) return false if (selector.token !== undefined && object.isToken !== selector.token) return false if (selector.name && object.definition.name.toLowerCase() !== selector.name.toLowerCase()) return false if (selector.counters) { const count = object.counters[selector.counters.counter] ?? 0 if (count < selector.counters.atLeast) return false } if (selector.power) { const power = this.getPower(object) if (selector.power.atLeast !== undefined && power < selector.power.atLeast) return false if (selector.power.atMost !== undefined && power > selector.power.atMost) return false } if (selector.toughness) { const toughness = this.getToughness(object) if (selector.toughness.atLeast !== undefined && toughness < selector.toughness.atLeast) return false if (selector.toughness.atMost !== undefined && toughness > selector.toughness.atMost) return false } if (selector.manaValue) { const value = manaValueOf(object.definition) if (selector.manaValue.atLeast !== undefined && value < selector.manaValue.atLeast) return false if (selector.manaValue.atMost !== undefined && value > selector.manaValue.atMost) return false } if (selector.keywords?.some(keyword => !this.hasKeyword(object, keyword))) return false if (selector.excludeKeywords?.some(keyword => this.hasKeyword(object, keyword))) return false if (selector.attached) { const attached = [...this.objects.values()].some(attachment => attachment.attachedTo === object.id && (selector.attached === 'equipped' ? this.hasType(attachment, 'equipment') : this.hasType(attachment, 'aura'))) if (!attached) return false } return true } // --------------------------------------------------------------------------- // Rules helpers // --------------------------------------------------------------------------- private isCreature(object: GameObject): boolean { return this.hasType(object, 'creature') } private isLand(object: GameObject): boolean { return this.hasType(object, 'land') } private isInstant(object: GameObject): boolean { return this.hasType(object, 'instant') } private isInstantOrSorcery(object: GameObject): boolean { return this.hasType(object, 'instant') || this.hasType(object, 'sorcery') } private isPermanent(object: GameObject): boolean { if (this.isInstantOrSorcery(object)) return false return ['creature', 'artifact', 'enchantment', 'planeswalker', 'battle', 'land'] .some(type => this.hasType(object, type)) } private hasType(object: GameObject, type: string): boolean { const words = object.definition.typeLine.toLowerCase().split(/[\s—–\-/,()]+/) return words.includes(type.toLowerCase()) } private hasKeywordForDefinition(definition: CardDefinition, keyword: string): boolean { const wanted = keyword.toLowerCase() for (const ability of definition.abilities ?? []) { if (ability.kind === 'keyword' && ability.keyword.toLowerCase() === wanted) return true if (ability.kind === 'keywords' && ability.keywords.some(entry => entry.keyword.toLowerCase() === wanted)) return true } return false } private battlefieldObjects(): GameObject[] { return [...this.objects.values()].filter(object => object.zone === 'battlefield') } private alivePlayers(): PlayerState[] { return this.players.filter(player => !player.lost) } private opponentsOf(playerId: string): string[] { return this.alivePlayers().filter(player => player.id !== playerId).map(player => player.id) } private nextAlivePlayer(playerId: string): string { const start = this.players.findIndex(player => player.id === playerId) for (let offset = 1; offset <= this.players.length; offset++) { const player = this.players[(start + offset) % this.players.length] if (!player.lost) return player.id } return playerId } private requirePriority(playerId: string): void { if (this.status !== 'active') throw new GameError('Game is not active') if (this.pendingSearch) throw new GameError('Choose a card from your library first') if (this.pendingChoice) throw new GameError('Resolve the pending choice first') if (this.priority !== playerId) throw new GameError('You do not have priority') } private emptyManaPools(): void { for (const player of this.players) player.manaPool = emptyPool() } private removeExpiringEffects(playerId: string): void { for (let index = this.continuousEffects.length - 1; index >= 0; index--) { const effect = this.continuousEffects[index] if ((effect.duration === 'until_your_next_turn' || effect.duration === 'until_controllers_next_untap_step') && effect.controller === playerId) { this.continuousEffects.splice(index, 1) } } } /** "Until the end of your next turn" skips the turn the effect was created in. */ private removeEndOfNextTurnEffects(playerId: string): void { for (let index = this.continuousEffects.length - 1; index >= 0; index--) { const effect = this.continuousEffects[index] if (effect.duration === 'until_end_of_your_next_turn' && effect.controller === playerId && effect.createdTurn !== this.turn) { this.continuousEffects.splice(index, 1) } } } private removeEffectsByDuration(duration: Duration): void { for (let index = this.continuousEffects.length - 1; index >= 0; index--) { if (this.continuousEffects[index].duration === duration) this.continuousEffects.splice(index, 1) } } private counterStat(counters: Record, stat: 'power' | 'toughness'): number { let total = 0 for (const [counter, count] of Object.entries(counters)) { const match = counter.match(/^([+-])(\d+)\/([+-])(\d+)$/) if (!match) continue const value = stat === 'power' ? `${match[1]}${match[2]}` : `${match[3]}${match[4]}` total += Number(value) } return total } private findStackItem(id: string): StackItem | undefined { return this.stack.find(item => item.id === id) ?? this.stack.find(item => item.source.id === id) } private playerSource(playerId: string): GameObject { return { id: `player:${playerId}`, definition: { oracleId: `player:${playerId}`, name: this.getPlayer(playerId).name, typeLine: '' }, owner: playerId, controller: playerId, zone: 'battlefield', tapped: false, damage: 0, deathtouched: false, counters: {}, isToken: false, enteredTurn: 0, blockedBy: [], attachments: [], regenerationShields: 0, activations: {}, } } private createObject(definition: CardDefinition, owner: string): GameObject { const object: GameObject = { id: this.generateId('card'), definition, owner, controller: owner, zone: 'library', tapped: false, damage: 0, deathtouched: false, counters: {}, isToken: false, enteredTurn: 0, blockedBy: [], attachments: [], regenerationShields: 0, activations: {}, } this.objects.set(object.id, object) return object } private generateId(prefix: string): string { this.nextId++ return `${prefix}_${this.nextId}` } private logMessage(message: string): void { this.log.push(message) } } function mulberry32(seed: number): () => number { let state = seed >>> 0 return () => { state = (state + 0x6d2b79f5) >>> 0 let value = state value = Math.imul(value ^ (value >>> 15), value | 1) value ^= value + Math.imul(value ^ (value >>> 7), value | 61) return ((value ^ (value >>> 14)) >>> 0) / 4294967296 } }