Files
commander/backend/src/game/game-stats.ts
2026-11-04 17:10:22 +01:00

307 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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'
import { predefinedToken } from './tokens.js'
import { GameError, ResolvedTarget, EventContext, EffectContext, ContinuousEffect, DamageShield, ManaCost, CostReduction, MANA_COLORS, COLOR_NAMES, emptyPool, parseManaCost, reduceManaSymbols, manaValueOf, colorOfSymbol, tokenCard, capitalize, tokenFace, mulberry32 } from './game-helpers.js'
import { GameBase } from './game-base.js'
export abstract class GameStats extends GameBase {
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--
}
}
protected 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
}
protected isCreature(object: GameObject): boolean {
return this.hasType(object, 'creature')
}
protected isLand(object: GameObject): boolean {
return this.hasType(object, 'land')
}
protected isInstant(object: GameObject): boolean {
return this.hasType(object, 'instant')
}
protected isInstantOrSorcery(object: GameObject): boolean {
return this.hasType(object, 'instant') || this.hasType(object, 'sorcery')
}
protected isPermanent(object: GameObject): boolean {
if (this.isInstantOrSorcery(object)) return false
return ['creature', 'artifact', 'enchantment', 'planeswalker', 'battle', 'land']
.some(type => this.hasType(object, type))
}
protected hasType(object: GameObject, type: string): boolean {
const words = object.definition.typeLine.toLowerCase().split(/[\s—–\-/,()]+/)
return words.includes(type.toLowerCase())
}
protected battlefieldObjects(): GameObject[] {
return [...this.objects.values()].filter(object => object.zone === 'battlefield')
}
protected alivePlayers(): PlayerState[] {
return this.players.filter(player => !player.lost)
}
protected opponentsOf(playerId: string): string[] {
return this.alivePlayers().filter(player => player.id !== playerId).map(player => player.id)
}
protected 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
}
protected counterStat(counters: Record<string, number>, 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) * count
}
return total
}
protected 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))
}
protected 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.excludeColors?.some(color => color === 'C' ? colors.length === 0 : colors.includes(color))) 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
// ---------------------------------------------------------------------------
}