kjdskjdsk

This commit is contained in:
2026-10-27 19:14:33 +01:00
parent c962800876
commit bb85881cac
19 changed files with 2355 additions and 185 deletions

View File

@@ -23,6 +23,7 @@ import type {
GameConfig,
ManaColor,
ManaPool,
PendingChoice,
PendingSearch,
Phase,
PlayerState,
@@ -30,6 +31,7 @@ import type {
Step,
TargetChoice,
} from './types.js'
import { CREATURE_TYPES } from './creature-types.js'
export class GameError extends Error {}
@@ -120,6 +122,37 @@ function parseManaCost(symbols: string, x = 0): ManaCost {
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 ?? '')
@@ -166,6 +199,12 @@ export class Game {
winner?: string
/** 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
@@ -214,6 +253,8 @@ export class Game {
creaturesDiedThisTurn: 0,
nonlandPermanentsEnteredThisTurn: 0,
attackedThisTurn: false,
creaturesAttackedThisTurn: 0,
damageTakenThisTurn: 0,
energy: 0,
poison: 0,
}))
@@ -260,6 +301,17 @@ export class Game {
}
}
// Leyline-style "begin the game with it on the battlefield" cards.
for (const player of this.players) {
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
@@ -302,9 +354,10 @@ export class Game {
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.
const destination: Zone = object.isCommander && zone !== 'battlefield' && zone !== 'stack' && zone !== 'command'
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
@@ -318,6 +371,7 @@ export class Game {
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') {
@@ -326,12 +380,14 @@ export class Game {
}
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)
@@ -517,11 +573,25 @@ export class Game {
}
const abilities = object.definition.abilities ?? []
const effects = abilities.filter((ability): ability is Extract<Ability, { kind: 'spell' }> => ability.kind === 'spell')
const overload = abilities.find((ability): ability is Extract<Ability, { kind: 'overload' }> => 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' }> => 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
this.payMana(playerId, `${object.definition.manaCost ?? ''}${'{2}'.repeat(tax / 2)}`, options.x ?? 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
@@ -545,11 +615,80 @@ export class Game {
return item
}
private alternativeCostFor(object: GameObject): Extract<Ability, { kind: 'alternative_cost' }> | undefined {
return (object.definition.abilities ?? []).find(ability =>
ability.kind === 'alternative_cost'
&& (!ability.condition || this.checkCondition(ability.condition, object))) as
| Extract<Ability, { kind: 'alternative_cost' }>
| undefined
}
private payAlternativeCost(
ability: Extract<Ability, { kind: 'alternative_cost' }>,
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')
@@ -621,6 +760,7 @@ export class Game {
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 })
}
@@ -643,6 +783,7 @@ export class Game {
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('Choose a creature type first')
if (this.priority !== playerId) throw new GameError('You do not have priority')
const seen = new Set<string>()
@@ -702,6 +843,7 @@ export class Game {
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('Choose a creature type first')
const actual = playerId ?? this.priority
if (this.priority !== actual) throw new GameError('You do not have priority')
const alive = this.alivePlayers().length
@@ -740,7 +882,8 @@ export class Game {
/** 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 && guard++ < 1000) {
while (this.stack.length && this.status === 'active' && !this.pendingSearch && !this.pendingChoice
&& guard++ < 1000) {
this.pass(this.priority)
}
}
@@ -755,7 +898,7 @@ export class Game {
this.step = 'end_step'
this.dispatchEvent({ kind: 'end_step', player: playerId })
this.resolveStack()
if (this.status !== 'active' || this.pendingSearch) return
if (this.status !== 'active' || this.pendingSearch || this.pendingChoice) return
this.finishTurn()
}
@@ -764,7 +907,7 @@ export class Game {
* 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) return false
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
@@ -780,9 +923,20 @@ export class Game {
if (!this.canCastAtThisTime(playerId, object)) return false
const tax = fromCommand ? (player.commanderCasts[cardId] ?? 0) * 2 : 0
if (!this.canAffordMana(playerId, `${object.definition.manaCost ?? ''}${'{2}'.repeat(tax / 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)
}
@@ -793,12 +947,18 @@ export class Game {
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('Choose a creature type 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))
@@ -816,17 +976,45 @@ export class Game {
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) 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}`)
}
/**
* 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.autoAdvanceDepth > 0) return
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.turn === turn && guard++ < 100) {
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)
@@ -853,6 +1041,8 @@ export class Game {
player.creaturesDiedThisTurn = 0
player.nonlandPermanentsEnteredThisTurn = 0
player.attackedThisTurn = false
player.creaturesAttackedThisTurn = 0
player.damageTakenThisTurn = 0
player.manaPool = emptyPool()
this.removeExpiringEffects(player.id)
@@ -1688,6 +1878,12 @@ export class Game {
}
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
@@ -1751,7 +1947,7 @@ export class Game {
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)
this.searchLibrary(playerId, effect.selector, amount, effect.destination, effect.tapped, effect.shuffle, effect.zones, effect.split)
}
break
}
@@ -1835,10 +2031,87 @@ export class Game {
}
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<Effect, { op: 'hideaway' }>): 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' }> => 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<Effect, { op: 'dig' }>,
@@ -1965,6 +2238,7 @@ export class Game {
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') {
@@ -2206,6 +2480,18 @@ export class Game {
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) {
@@ -2223,6 +2509,16 @@ export class Game {
}
}
/** 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) {
@@ -2278,11 +2574,22 @@ export class Game {
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':
return this.playersForValue(condition.who, this.staticContext(source))
.some(playerId => this.getPlayer(playerId).hand.length <= condition.atMost)
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':
@@ -2291,6 +2598,16 @@ export class Game {
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
}
@@ -2382,7 +2699,7 @@ export class Game {
}
private hasMeaningfulAction(playerId: string): boolean {
if (this.status !== 'active' || this.priority !== playerId) return false
if (this.status !== 'active' || this.priority !== playerId || this.pendingChoice) return false
const player = this.getPlayer(playerId)
if (player.lost) return false
@@ -2420,6 +2737,7 @@ export class Game {
ability: Extract<Ability, { kind: 'activated' }>,
): 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)
@@ -2553,6 +2871,7 @@ export class Game {
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]
@@ -2687,6 +3006,7 @@ export class Game {
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.
@@ -2694,15 +3014,28 @@ export class Game {
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, tapped, shuffle, zones }
this.pendingSearch = {
playerId,
selector,
remaining,
destination: pickDestination,
tapped: pickTapped,
shuffle,
zones,
...(first && split && remaining > 1 ? { split } : {}),
}
return
}
this.moveSearchedCard(candidates[0], playerId, destination, tapped)
this.moveSearchedCard(candidates[0], playerId, pickDestination, pickTapped)
remaining--
first = false
}
if (shuffle) this.shuffleLibrary(player)
}
@@ -2712,14 +3045,20 @@ export class Game {
selector: ObjectSelector,
zones?: ('library' | 'graveyard')[],
): GameObject[] {
const player = this.getPlayer(playerId)
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 ids = allowed.includes('library') ? [...player.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
&& this.matchesSelector(object, selector, source, object.zone))
return ids.map(id => this.getObject(id)).filter(object => object.owner === playerId)
}
private moveSearchedCard(
@@ -2741,6 +3080,23 @@ export class Game {
}
}
// 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))
@@ -2774,13 +3130,16 @@ export class Game {
const typeLine = object.definition.typeLine.toLowerCase()
const words = new Set(typeLine.split(/[\s—–\-/,()]+/).filter(Boolean))
if (selector.types?.length) {
const matches = selector.types.map(type => words.has(type.toLowerCase()))
if (selector.match === 'any' ? !matches.some(Boolean) : !matches.every(Boolean)) return false
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?.some(type => !words.has(type.toLowerCase()))) return false
if (selector.subtypes?.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
@@ -2788,7 +3147,10 @@ export class Game {
if (selector.owner === 'opponent' && object.owner === source.controller) return false
const colors = object.definition.colors ?? []
if (selector.colors?.some(color => !colors.includes(color))) return false
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
@@ -2886,6 +3248,7 @@ export class Game {
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('Choose a creature type first')
if (this.priority !== playerId) throw new GameError('You do not have priority')
}