Fa triggers malament
This commit is contained in:
@@ -7,6 +7,7 @@ import {
|
||||
parseSelector,
|
||||
parseTarget,
|
||||
parseValue,
|
||||
ROLE_NAMES,
|
||||
} from './parse.js'
|
||||
import type {
|
||||
Ability,
|
||||
@@ -397,6 +398,11 @@ function parseTokenBody(text: string, tapped: boolean): TokenSpec | undefined {
|
||||
}
|
||||
if (/\bcolorless\b/.test(rest)) colors.push('C')
|
||||
|
||||
const role = Object.entries(ROLE_NAMES).find(([name]) => rest.endsWith(`${name} role`))
|
||||
if (role) {
|
||||
return { name: role[1], types: ['enchantment'], subtypes: ['aura', 'role'], colors, tapped: tapped || undefined }
|
||||
}
|
||||
|
||||
let power: Value | undefined
|
||||
let toughness: Value | undefined
|
||||
const pt = rest.match(/^(\d+|x)\/(\d+|x)\b/)
|
||||
@@ -777,6 +783,16 @@ function parseEffect(text: string): Effect | Effect[] | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^create (?:(\w+) )?(?:a |an )?(.+?) tokens? attached to (.+)$/)
|
||||
if (match) {
|
||||
const amount = match[1] && !['a', 'an'].includes(match[1])
|
||||
? parseValue(match[1])
|
||||
: ({ kind: 'number', value: 1 } as Value)
|
||||
const token = parseToken(match[2])
|
||||
const attachTo = parseTarget(match[3])
|
||||
if (amount && token && attachTo) return { op: 'create_token', player: 'you', amount, token, attachTo }
|
||||
}
|
||||
|
||||
match = sentence.match(/^create (?:((?:that many)|\w+) )?(.+?) tokens?(?: (with .+))?$/)
|
||||
if (match) {
|
||||
const amount = match[1] ? parseValue(match[1]) : ({ kind: 'number', value: 1 } as Value)
|
||||
@@ -1944,6 +1960,26 @@ function parseStaticEffects(text: string): StaticEffect[] | undefined {
|
||||
if (what) return [{ op: 'choose', what }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if an effect would create one or more (tokens?|creature tokens?) under your control, it creates (twice|three times) that many of those tokens instead$/)
|
||||
if (match) {
|
||||
return [{
|
||||
op: 'token_multiplier',
|
||||
multiplier: match[2] === 'twice' ? 2 : 3,
|
||||
who: 'you',
|
||||
...(match[1] === 'creature tokens' ? { creatureOnly: true } : {}),
|
||||
}]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if one or more (tokens?|creature tokens?) would be created( under your control)?, (twice|three times) that many of those tokens are created instead$/)
|
||||
if (match) {
|
||||
return [{
|
||||
op: 'token_multiplier',
|
||||
multiplier: match[3] === 'twice' ? 2 : 3,
|
||||
who: match[2] ? 'you' : 'each_player',
|
||||
...(match[1] === 'creature tokens' ? { creatureOnly: true } : {}),
|
||||
}]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if this would be put into (?:a|your) graveyard from anywhere, exile it instead$/)
|
||||
if (match) {
|
||||
return [{ op: 'replacement', what: 'dies', instead: 'exile', target: { kind: 'self' } }]
|
||||
|
||||
@@ -116,6 +116,9 @@ function formatSelector(selector: ObjectSelector): string {
|
||||
if (selector.colors?.length) {
|
||||
text += `.withColor(${selector.colors.map(color => quote(COLOR_NAMES[color] ?? color)).join(', ')})`
|
||||
}
|
||||
if (selector.excludeColors?.length) {
|
||||
text += `.withoutColor(${selector.excludeColors.map(color => quote(COLOR_NAMES[color] ?? color)).join(', ')})`
|
||||
}
|
||||
if (selector.supertypes?.length) {
|
||||
text += `.withSupertype(${selector.supertypes.map(quote).join(', ')})`
|
||||
}
|
||||
@@ -315,7 +318,7 @@ export function formatEffect(effect: Effect): string {
|
||||
case 'create_token':
|
||||
return effect.copyOf
|
||||
? `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, copyOf(${formatTarget(effect.copyOf)}${effect.notLegendary ? ', { notLegendary: true }' : ''}))`
|
||||
: `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, ${formatToken(effect.token)})`
|
||||
: `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, ${formatToken(effect.token)}${effect.attachTo ? `, { attachTo: ${formatTarget(effect.attachTo)} }` : ''})`
|
||||
case 'destroy':
|
||||
return `destroy(${formatTarget(effect.target)})`
|
||||
case 'exile':
|
||||
@@ -560,6 +563,8 @@ function formatCondition(condition: Condition): string {
|
||||
return `attackedWithCreatures(${condition.atLeast})`
|
||||
case 'library_at_most':
|
||||
return `libraryAtMost(${condition.atMost})`
|
||||
case 'event_subject_toughness_at_most':
|
||||
return `eventSubjectToughnessAtMost(${condition.amount})`
|
||||
}
|
||||
}
|
||||
|
||||
@@ -651,6 +656,11 @@ function formatStaticEffect(effect: StaticEffect): string {
|
||||
return `searchRestriction(${quote(effect.who)}, ${formatValue(effect.amount)})`
|
||||
case 'exile_instead_of_graveyard':
|
||||
return `exileInsteadOfGraveyard(${effect.owner ? quote(effect.owner) : ''})`
|
||||
case 'token_multiplier':
|
||||
return `tokenMultiplier(${effect.multiplier}${optionArg([
|
||||
['who', effect.who === 'each_player' ? quote('each_player') : undefined],
|
||||
['creatureOnly', effect.creatureOnly ? 'true' : undefined],
|
||||
])})`
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -144,6 +144,16 @@ const NON_CREATURE_SUBTYPES: Record<string, string> = {
|
||||
desert: 'land',
|
||||
}
|
||||
|
||||
export const ROLE_NAMES: Record<string, string> = {
|
||||
cursed: 'Cursed',
|
||||
monster: 'Monster',
|
||||
royal: 'Royal',
|
||||
sorcerer: 'Sorcerer',
|
||||
virtuous: 'Virtuous',
|
||||
wicked: 'Wicked',
|
||||
'young hero': 'Young Hero',
|
||||
}
|
||||
|
||||
function typeForSubtype(subtype: string): string {
|
||||
return NON_CREATURE_SUBTYPES[subtype] ?? 'creature'
|
||||
}
|
||||
@@ -462,6 +472,7 @@ export function parseSelector(text: string): ObjectSelector | undefined {
|
||||
const supertypes: string[] = []
|
||||
const subtypes: string[] = []
|
||||
const colors: string[] = []
|
||||
const excludeColors: string[] = []
|
||||
let match: ObjectSelector['match']
|
||||
|
||||
for (const rawWord of words) {
|
||||
@@ -506,6 +517,10 @@ export function parseSelector(text: string): ObjectSelector | undefined {
|
||||
excludeTypes.push(negative[1])
|
||||
continue
|
||||
}
|
||||
if (negative && COLOR_WORDS[negative[1]]) {
|
||||
excludeColors.push(COLOR_WORDS[negative[1]])
|
||||
continue
|
||||
}
|
||||
|
||||
if (STATE_WORDS.has(word)) {
|
||||
if (word === 'token') selector.token = true
|
||||
@@ -528,7 +543,7 @@ export function parseSelector(text: string): ObjectSelector | undefined {
|
||||
if (!types.length) {
|
||||
if (subtypes.length) {
|
||||
types.push(typeForSubtype(subtypes[0]))
|
||||
} else if (!(excludeTypes.length || colors.length || supertypes.length || selector.name)) {
|
||||
} else if (!(excludeTypes.length || excludeColors.length || colors.length || supertypes.length || selector.name)) {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
@@ -536,6 +551,7 @@ export function parseSelector(text: string): ObjectSelector | undefined {
|
||||
selector.types = types
|
||||
if (match) selector.match = match
|
||||
if (excludeTypes.length) selector.excludeTypes = excludeTypes
|
||||
if (excludeColors.length) selector.excludeColors = excludeColors
|
||||
if (supertypes.length) selector.supertypes = supertypes
|
||||
if (subtypes.length) selector.subtypes = subtypes
|
||||
if (colors.length) selector.colors = colors
|
||||
|
||||
@@ -522,7 +522,7 @@ const STATIC_OPS = new Set([
|
||||
'pump', 'grant', 'grant_ability', 'restriction', 'enters_tapped',
|
||||
'enters_with_counters', 'set_pt', 'control', 'choose', 'replacement',
|
||||
'cost_reduction', 'cost_increase', 'search_restriction',
|
||||
'exile_instead_of_graveyard',
|
||||
'exile_instead_of_graveyard', 'token_multiplier',
|
||||
])
|
||||
|
||||
const COST_KINDS = new Set([
|
||||
@@ -766,6 +766,18 @@ class Selector {
|
||||
})
|
||||
}
|
||||
|
||||
withoutColor(...colors: unknown[]): Selector {
|
||||
return this.with({
|
||||
excludeColors: [
|
||||
...(this.fields.excludeColors ?? []),
|
||||
...colors.map(color => {
|
||||
const text = asString(color, 'color').toLowerCase()
|
||||
return COLOR_CODES[text] ?? text.toUpperCase()
|
||||
}),
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
matchingAny(): Selector {
|
||||
return this.with({ match: 'any' })
|
||||
}
|
||||
@@ -1249,7 +1261,10 @@ function proliferate(): Effect {
|
||||
return { op: 'proliferate' }
|
||||
}
|
||||
|
||||
function createToken(player: unknown, amount: unknown, tokenValue: unknown): Effect {
|
||||
function createToken(player: unknown, amount: unknown, tokenValue: unknown, options?: unknown): Effect {
|
||||
const attachTo = options && typeof options === 'object' && 'attachTo' in options
|
||||
? asTarget((options as { attachTo: unknown }).attachTo)
|
||||
: undefined
|
||||
if (tokenValue instanceof CopyOf) {
|
||||
return {
|
||||
op: 'create_token',
|
||||
@@ -1258,9 +1273,16 @@ function createToken(player: unknown, amount: unknown, tokenValue: unknown): Eff
|
||||
token: { types: [], subtypes: [], colors: [] },
|
||||
copyOf: tokenValue.target,
|
||||
...(tokenValue.notLegendary ? { notLegendary: true } : {}),
|
||||
...(attachTo ? { attachTo } : {}),
|
||||
}
|
||||
}
|
||||
return { op: 'create_token', player: asPlayer(player), amount: asValue(amount), token: asToken(tokenValue) }
|
||||
return {
|
||||
op: 'create_token',
|
||||
player: asPlayer(player),
|
||||
amount: asValue(amount),
|
||||
token: asToken(tokenValue),
|
||||
...(attachTo ? { attachTo } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function destroy(targetValue: unknown): Effect {
|
||||
@@ -1603,6 +1625,19 @@ function replace(what: unknown, options?: unknown): StaticEffect {
|
||||
}
|
||||
}
|
||||
|
||||
function tokenMultiplier(multiplier: unknown, options?: unknown): StaticEffect {
|
||||
const data = asOptions(options)
|
||||
if (data.who !== undefined && data.who !== 'you' && data.who !== 'each_player') {
|
||||
throw new Error("tokenMultiplier() who must be 'you' or 'each_player'")
|
||||
}
|
||||
return {
|
||||
op: 'token_multiplier',
|
||||
multiplier: asNumber(multiplier, 'token multiplier'),
|
||||
who: data.who === 'each_player' ? 'each_player' : 'you',
|
||||
...(data.creatureOnly === true ? { creatureOnly: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function costReduction(targetValue: unknown, amount: unknown, options?: unknown): StaticEffect {
|
||||
const data = asOptions(options)
|
||||
return {
|
||||
@@ -2351,6 +2386,7 @@ function createApi(): Record<string, unknown> {
|
||||
costIncrease,
|
||||
searchRestriction,
|
||||
exileInsteadOfGraveyard,
|
||||
tokenMultiplier,
|
||||
|
||||
// abilities
|
||||
keyword,
|
||||
|
||||
@@ -73,6 +73,7 @@ Selectors (chainable):
|
||||
permanents, cards, creatures
|
||||
.withType('land'), .withSubtype('dragon'), .withSupertype('legendary')
|
||||
.withColor('white'|'blue'|'black'|'red'|'green'|'colorless')
|
||||
.withoutColor('white'|'blue'|'black'|'red'|'green'|'colorless')
|
||||
.withoutType('creature'), .withKeyword('flying'), .withoutKeyword('flying')
|
||||
.other(), .tapped(), .untapped(), .attacking(), .token(), .nontoken()
|
||||
.equipped(), .enchanted(), .youControl(), .opponentControls(), .controlledBy('you'|'opponent'|'any')
|
||||
|
||||
@@ -25,6 +25,7 @@ export interface ObjectSelector {
|
||||
controller?: 'you' | 'opponent' | 'any'
|
||||
owner?: 'you' | 'opponent'
|
||||
colors?: string[]
|
||||
excludeColors?: string[]
|
||||
other?: boolean
|
||||
attached?: 'equipped' | 'enchanted'
|
||||
zone?: Zone
|
||||
@@ -191,6 +192,7 @@ export type Condition =
|
||||
| { kind: 'opponent_damaged_this_turn'; atLeast: number }
|
||||
| { kind: 'attacked_with_creatures'; atLeast: number }
|
||||
| { kind: 'library_at_most'; atMost: number }
|
||||
| { kind: 'event_subject_toughness_at_most'; amount: number }
|
||||
|
||||
export type TriggerEvent =
|
||||
| { kind: 'enters'; subject: Target }
|
||||
@@ -225,7 +227,7 @@ export type Effect =
|
||||
| { op: 'put_counters'; target: Target; counter: string; amount: Value }
|
||||
| { op: 'remove_counters'; target: Target; counter: string; amount: Value }
|
||||
| { op: 'proliferate' }
|
||||
| { op: 'create_token'; player: PlayerRef; amount: Value; token: TokenSpec; copyOf?: Target; notLegendary?: boolean }
|
||||
| { op: 'create_token'; player: PlayerRef; amount: Value; token: TokenSpec; copyOf?: Target; notLegendary?: boolean; attachTo?: Target }
|
||||
| { op: 'destroy'; target: Target }
|
||||
| { op: 'exile'; target: Target }
|
||||
| { op: 'sacrifice'; player: PlayerRef; target: Target; unless?: Cost }
|
||||
@@ -278,6 +280,7 @@ export type StaticEffect =
|
||||
| { op: 'cost_increase'; amount: Value; spellType?: 'noncreature' | 'creature' }
|
||||
| { op: 'search_restriction'; who: 'opponent' | 'you'; amount: Value }
|
||||
| { op: 'exile_instead_of_graveyard'; owner?: 'opponent' | 'you' }
|
||||
| { op: 'token_multiplier'; multiplier: number; who: 'you' | 'each_player'; creatureOnly?: boolean }
|
||||
|
||||
export type Ability =
|
||||
| KeywordAbility
|
||||
|
||||
@@ -33,6 +33,7 @@ import type {
|
||||
TargetChoice,
|
||||
} from './types.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { predefinedToken } from './tokens.js'
|
||||
|
||||
export class GameError extends Error {}
|
||||
|
||||
@@ -65,6 +66,8 @@ interface EffectContext {
|
||||
eventAmount?: number
|
||||
x: number
|
||||
mode: number
|
||||
/** Color picked for a mana ability, so choice effects produce it. */
|
||||
manaColor?: ManaColor
|
||||
}
|
||||
|
||||
interface ContinuousEffect {
|
||||
@@ -167,19 +170,66 @@ function colorOfSymbol(symbol: string): ManaColor {
|
||||
return 'C'
|
||||
}
|
||||
|
||||
function tokenCard(token: { types: string[]; subtypes: string[]; name?: string; colors: string[]; power?: number; toughness?: number; keywords?: string[] }): CardDefinition {
|
||||
function tokenCard(token: {
|
||||
name?: string
|
||||
types: string[]
|
||||
subtypes: string[]
|
||||
colors: string[]
|
||||
power?: number
|
||||
toughness?: number
|
||||
keywords?: string[]
|
||||
}): { definition: CardDefinition; backFace?: CardDefinition } {
|
||||
const predefined = predefinedToken(token)
|
||||
const types = predefined?.types ?? token.types
|
||||
const subtypes = predefined?.subtypes ?? token.subtypes
|
||||
const colors = [...new Set([...(predefined?.colors ?? []), ...token.colors])]
|
||||
const keywords = [...(predefined?.keywords ?? []), ...(token.keywords ?? [])]
|
||||
const definition = tokenFace({
|
||||
name: predefined?.name ?? token.name ?? (subtypes.map(capitalize).join(' ') || 'Token'),
|
||||
types,
|
||||
subtypes,
|
||||
colors,
|
||||
power: token.power ?? predefined?.power,
|
||||
toughness: token.toughness ?? predefined?.toughness,
|
||||
keywords,
|
||||
abilities: predefined?.abilities,
|
||||
})
|
||||
const backFace = predefined?.backFace
|
||||
? tokenFace({ ...predefined.backFace, keywords: predefined.backFace.keywords ?? [] })
|
||||
: undefined
|
||||
return { definition, backFace }
|
||||
}
|
||||
|
||||
function capitalize(word: string): string {
|
||||
return word[0]?.toUpperCase() + word.slice(1)
|
||||
}
|
||||
|
||||
function tokenFace(fields: {
|
||||
name: string
|
||||
types: string[]
|
||||
subtypes: string[]
|
||||
colors: string[]
|
||||
power?: number
|
||||
toughness?: number
|
||||
keywords?: string[]
|
||||
abilities?: Ability[]
|
||||
}): 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(),
|
||||
oracleId: `token:${fields.name}`,
|
||||
name: fields.name,
|
||||
typeLine: [fields.types.join(' '), fields.subtypes.length ? `— ${fields.subtypes.join(' ')}` : ''].join(' ').trim(),
|
||||
manaValue: 0,
|
||||
colors: token.colors,
|
||||
power: token.power,
|
||||
toughness: token.toughness,
|
||||
abilities: (token.keywords ?? []).map(keyword => ({ kind: 'keyword', keyword })),
|
||||
colors: fields.colors,
|
||||
power: fields.power,
|
||||
toughness: fields.toughness,
|
||||
abilities: [
|
||||
...(fields.abilities ?? []),
|
||||
...(fields.keywords ?? []).map(keyword => ({ kind: 'keyword' as const, keyword })),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A deliberately small but real Magic rules engine: zones, priority, the stack,
|
||||
* turn phases, combat, state-based actions, mana, triggered/activated/static
|
||||
@@ -431,6 +481,7 @@ export class Game {
|
||||
const from = object.zone
|
||||
this.removeFromZone(object)
|
||||
object.zone = destination
|
||||
if (destination !== 'exile') object.faceDown = undefined
|
||||
|
||||
if (destination === 'battlefield') {
|
||||
object.controller = options.controller ?? object.owner
|
||||
@@ -617,8 +668,10 @@ export class Game {
|
||||
}
|
||||
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 (!player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) {
|
||||
throw new GameError('Card is not in hand')
|
||||
}
|
||||
if (!this.isLand(object)) throw new GameError('That card is not a land')
|
||||
|
||||
player.landPlayedThisTurn = true
|
||||
@@ -634,8 +687,10 @@ export class Game {
|
||||
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 && !player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) {
|
||||
throw new GameError('Card is not in hand')
|
||||
}
|
||||
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)) {
|
||||
@@ -773,9 +828,13 @@ export class Game {
|
||||
if (ability.activationsPerTurn !== undefined && activations >= ability.activationsPerTurn) {
|
||||
throw new GameError('Ability activation limit reached')
|
||||
}
|
||||
if (options.manaColor && !this.manaColorChoices(source, abilityIndex)?.includes(options.manaColor)) {
|
||||
throw new GameError('That ability cannot produce that mana')
|
||||
}
|
||||
|
||||
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)
|
||||
context.manaColor = options.manaColor
|
||||
this.payCosts(ability.costs, playerId, source, context)
|
||||
source.activations[abilityIndex] = activations + 1
|
||||
|
||||
@@ -980,8 +1039,8 @@ export class Game {
|
||||
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 && !player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) return false
|
||||
if (fromCommand && !object.isCommander) return false
|
||||
|
||||
if (this.isLand(object)) {
|
||||
@@ -1010,6 +1069,13 @@ export class Game {
|
||||
return this.hasLegalTargets(object, playerId)
|
||||
}
|
||||
|
||||
/** Junk and other impulse effects grant a one-turn play permission from exile. */
|
||||
private playableFromExile(playerId: string, object: GameObject): boolean {
|
||||
return object.zone === 'exile'
|
||||
&& object.owner === playerId
|
||||
&& object.playableFromExileTurn === this.turn
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes one pick of a paused library search. Searches pause when several
|
||||
* cards match so the player chooses instead of taking the first one.
|
||||
@@ -1056,6 +1122,37 @@ export class Game {
|
||||
return this.searchableObjects(playerId, pending.zones)
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers the hideaway look: exiles the chosen card linked to the source and
|
||||
* puts the rest on the bottom of the library in a random order.
|
||||
*/
|
||||
chooseHideawayCard(playerId: string, cardId: string): void {
|
||||
const pending = this.pendingChoice
|
||||
if (!pending || pending.what !== 'hideaway') throw new GameError('No hideaway choice is waiting')
|
||||
if (pending.playerId !== playerId) throw new GameError('You are not choosing this hideaway card')
|
||||
const looked = (pending.cardIds ?? []).map(id => this.getObject(id))
|
||||
const hidden = looked.find(object => object.id === cardId && object.zone === 'library')
|
||||
if (!hidden) throw new GameError('That card is not a legal choice')
|
||||
|
||||
this.pendingChoices.shift()
|
||||
this.moveToZone(hidden, 'exile', { silent: true })
|
||||
const source = this.objects.get(pending.sourceId)
|
||||
if (hidden.zone === 'exile') {
|
||||
hidden.faceDown = true
|
||||
if (source) source.linkedExile = [...(source.linkedExile ?? []), hidden.id]
|
||||
}
|
||||
|
||||
const rest = looked.filter(object => object.id !== hidden.id)
|
||||
for (let index = rest.length - 1; index > 0; index--) {
|
||||
const swap = Math.floor(this.rng() * (index + 1))
|
||||
const temp = rest[index]
|
||||
rest[index] = rest[swap]
|
||||
rest[swap] = temp
|
||||
}
|
||||
for (const object of rest) this.moveToZone(object, 'library', { silent: true })
|
||||
this.logMessage(`${this.getPlayer(playerId).name} hides away a card`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers an "as this enters, choose a creature type" prompt. The match API
|
||||
* uses the `choose_type` action.
|
||||
@@ -1153,11 +1250,8 @@ export class Game {
|
||||
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.drawCard(player.id, false)
|
||||
if (this.status !== 'active') return
|
||||
|
||||
this.phase = 'precombat_main'
|
||||
this.step = 'main'
|
||||
@@ -1441,6 +1535,28 @@ export class Game {
|
||||
return this.neededColor(player, cost, this.manaAbilityAllowedColors(source, ability))
|
||||
}
|
||||
|
||||
/**
|
||||
* Colors a mana ability lets its controller choose between. Undefined when
|
||||
* the ability has no choice, such as fixed or single-color mana.
|
||||
*/
|
||||
manaColorChoices(source: GameObject, abilityIndex: number): ManaColor[] | undefined {
|
||||
const ability = (source.definition.abilities ?? [])[abilityIndex]
|
||||
if (!ability || ability.kind !== 'activated') return undefined
|
||||
let colors: ManaColor[] | undefined
|
||||
for (const effect of ability.effects) {
|
||||
if (effect.op !== 'add_mana') continue
|
||||
if (effect.mana.kind === 'symbols' && effect.mana.oneOf) {
|
||||
colors = [...new Set(effect.mana.symbols.map(colorOfSymbol))]
|
||||
} else if (effect.mana.kind === 'any_color') {
|
||||
const allowed = this.anyColorRestrictionColors(effect.mana, source.controller)
|
||||
colors = allowed
|
||||
? MANA_COLORS.filter(color => color !== 'C' && allowed.has(color))
|
||||
: ['W', 'U', 'B', 'R', 'G']
|
||||
}
|
||||
}
|
||||
return colors && colors.length > 1 ? colors : undefined
|
||||
}
|
||||
|
||||
private manaAbilityAllowedColors(
|
||||
source: GameObject,
|
||||
ability: Extract<Ability, { kind: 'activated' }>,
|
||||
@@ -1543,6 +1659,11 @@ export class Game {
|
||||
if (mana.restriction === 'a land you control could produce') {
|
||||
return this.landManaColors(playerId, false, seen)
|
||||
}
|
||||
if (mana.restriction === "commander's color identity") {
|
||||
const commander = this.objects.get(this.getPlayer(playerId).commanderId ?? '')
|
||||
const identity = commander?.definition.colorIdentity ?? []
|
||||
return new Set(identity.filter((color): color is ManaColor => /^[WUBRG]$/.test(color)))
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
@@ -1747,6 +1868,10 @@ export class Game {
|
||||
take({ kind: 'player', who: effect.player, mode: 'target' }, who)
|
||||
}
|
||||
if ('target' in effect && effect.target) take(effect.target, undefined)
|
||||
if (effect.op === 'create_token') {
|
||||
if (effect.copyOf) take(effect.copyOf, undefined)
|
||||
if (effect.attachTo) take(effect.attachTo, undefined)
|
||||
}
|
||||
if (effect.op === 'fight') {
|
||||
take(effect.a, undefined)
|
||||
take(effect.b, undefined)
|
||||
@@ -1758,6 +1883,70 @@ export class Game {
|
||||
return selected
|
||||
}
|
||||
|
||||
/** Legal choices for a card's targets, so the UI can offer only real targets. */
|
||||
legalTargetsForCard(playerId: string, cardId: string): TargetChoice[] {
|
||||
const source = this.objects.get(cardId)
|
||||
if (!source) return []
|
||||
const effects = (source.definition.abilities ?? [])
|
||||
.filter((ability): ability is Extract<Ability, { kind: 'spell' }> => ability.kind === 'spell')
|
||||
.flatMap(ability => ability.effects)
|
||||
return this.collectTargets(effects, source, playerId, 0)
|
||||
}
|
||||
|
||||
/** Legal choices for an activated ability's targets. */
|
||||
legalTargetsForAbility(playerId: string, sourceId: string, abilityIndex: number): TargetChoice[] {
|
||||
const source = this.objects.get(sourceId)
|
||||
const ability = source?.definition.abilities?.[abilityIndex]
|
||||
if (!source || !ability || ability.kind !== 'activated') return []
|
||||
return this.collectTargets(ability.effects, source, playerId, 0)
|
||||
}
|
||||
|
||||
private collectTargets(
|
||||
effects: Effect[],
|
||||
source: GameObject,
|
||||
controller: string,
|
||||
mode: number,
|
||||
): TargetChoice[] {
|
||||
const choices = new Map<string, TargetChoice>()
|
||||
const add = (target: Target, playerOnly?: 'opponent' | 'any'): void => {
|
||||
if (target.kind === 'self' || target.kind === 'trigger_subject' || target.kind === 'previous_target') return
|
||||
if ((target.kind === 'object' || target.kind === 'player') && target.mode === 'each') return
|
||||
for (const choice of this.legalTargets(target, source, controller, playerOnly)) {
|
||||
choices.set(`${choice.kind}:${choice.id}`, choice)
|
||||
}
|
||||
}
|
||||
const walk = (list: Effect[]): void => {
|
||||
for (const effect of list) {
|
||||
if (effect.op === 'conditional') {
|
||||
walk(effect.effects)
|
||||
continue
|
||||
}
|
||||
if (effect.op === 'modal') {
|
||||
walk(effect.modes[mode] ?? effect.modes[0] ?? [])
|
||||
continue
|
||||
}
|
||||
if ('player' in effect && (effect.player === 'target_player' || effect.player === 'opponent')) {
|
||||
add(
|
||||
{ kind: 'player', who: effect.player, mode: 'target' },
|
||||
effect.player === 'opponent' ? 'opponent' : 'any',
|
||||
)
|
||||
}
|
||||
if ('target' in effect && effect.target) add(effect.target)
|
||||
if (effect.op === 'create_token') {
|
||||
if (effect.copyOf) add(effect.copyOf)
|
||||
if (effect.attachTo) add(effect.attachTo)
|
||||
}
|
||||
if (effect.op === 'fight') {
|
||||
add(effect.a)
|
||||
add(effect.b)
|
||||
}
|
||||
if (effect.op === 'damage_divided') add(effect.target)
|
||||
}
|
||||
}
|
||||
walk(effects)
|
||||
return [...choices.values()]
|
||||
}
|
||||
|
||||
private legalTargets(
|
||||
target: Target,
|
||||
source: GameObject,
|
||||
@@ -2046,16 +2235,29 @@ export class Game {
|
||||
case 'create_token': {
|
||||
const amount = Math.max(0, this.value(effect.amount, context))
|
||||
const players = this.playersForEffect(effect.player, context)
|
||||
const created: GameObject[] = []
|
||||
for (const playerId of players) {
|
||||
for (let i = 0; i < amount; i++) {
|
||||
const source = effect.copyOf
|
||||
? this.resolveTargets(context, effect.copyOf).find(target => target.kind === 'object')
|
||||
: undefined
|
||||
const creatureToken = source?.kind === 'object'
|
||||
? this.isCreature(source.object)
|
||||
: effect.token.types.includes('creature')
|
||||
const count = amount * this.tokenMultiplier(playerId, creatureToken)
|
||||
for (let i = 0; i < count; 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)
|
||||
if (source?.kind === 'object') created.push(this.createTokenCopy(playerId, source.object, effect.notLegendary))
|
||||
} else {
|
||||
this.createToken(playerId, effect.token, context)
|
||||
created.push(this.createToken(playerId, effect.token, context))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (effect.attachTo) {
|
||||
const target = this.resolveTargets(context, effect.attachTo)[0]
|
||||
if (target?.kind === 'object') {
|
||||
for (const token of created) this.attach(token, target.object)
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'destroy': {
|
||||
@@ -2148,7 +2350,7 @@ export class Game {
|
||||
break
|
||||
}
|
||||
case 'add_mana': {
|
||||
for (const playerId of this.playersForEffect(effect.player, context)) this.addMana(playerId, effect.mana)
|
||||
for (const playerId of this.playersForEffect(effect.player, context)) this.addMana(playerId, effect.mana, context.manaColor)
|
||||
break
|
||||
}
|
||||
case 'fight': {
|
||||
@@ -2186,16 +2388,28 @@ export class Game {
|
||||
break
|
||||
}
|
||||
case 'keyword_action':
|
||||
if (effect.action === 'explore') this.explore(context, effect)
|
||||
else if (effect.action === 'incubate') this.incubate(context, effect.amount)
|
||||
else if (effect.action === 'impulse') this.impulse(context)
|
||||
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 'transform': {
|
||||
const target = this.resolveTargets(context, effect.target)[0]
|
||||
if (target?.kind === 'object' && target.object.backFace) {
|
||||
const front = target.object.definition
|
||||
target.object.definition = target.object.backFace
|
||||
target.object.backFace = front
|
||||
this.logMessage(`${target.object.definition.name} transforms`)
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'pay':
|
||||
try {
|
||||
this.payCosts(effect.costs, context.controller, context.source, context)
|
||||
@@ -2241,24 +2455,28 @@ export class Game {
|
||||
}
|
||||
|
||||
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.
|
||||
// The exiled card stays face down and is linked to the source until played.
|
||||
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
|
||||
const looked = player.library.slice(0, amount).map(id => this.getObject(id))
|
||||
if (!looked.length) return
|
||||
if (looked.length === 1) {
|
||||
this.moveToZone(looked[0], 'exile', { silent: true })
|
||||
if (looked[0].zone === 'exile') {
|
||||
looked[0].faceDown = true
|
||||
context.source.linkedExile = [...(context.source.linkedExile ?? []), looked[0].id]
|
||||
}
|
||||
this.logMessage(`${player.name} hides away a card`)
|
||||
return
|
||||
}
|
||||
for (const object of top) this.moveToZone(object, 'library', { silent: true })
|
||||
this.logMessage(`${player.name} hides away a card`)
|
||||
|
||||
this.pendingChoices.push({
|
||||
playerId: context.controller,
|
||||
sourceId: context.source.id,
|
||||
what: 'hideaway',
|
||||
cardIds: looked.map(object => object.id),
|
||||
})
|
||||
this.logMessage(`${player.name} looks at the top ${looked.length} cards of their library`)
|
||||
}
|
||||
|
||||
private playExiledCard(playerId: string, object: GameObject, free: boolean | undefined): boolean {
|
||||
@@ -2304,6 +2522,48 @@ export class Game {
|
||||
return true
|
||||
}
|
||||
|
||||
private explore(context: EffectContext, effect: Extract<Effect, { op: 'keyword_action' }>): void {
|
||||
const target = effect.target ? this.resolveTargets(context, effect.target)[0] : undefined
|
||||
if (target?.kind !== 'object') return
|
||||
const player = this.getPlayer(context.controller)
|
||||
const cardId = player.library[0]
|
||||
if (!cardId) return
|
||||
const card = this.getObject(cardId)
|
||||
if (this.isLand(card)) {
|
||||
this.moveToZone(card, 'hand', { silent: false })
|
||||
this.logMessage(`${player.name} explores and puts ${card.definition.name} into their hand`)
|
||||
return
|
||||
}
|
||||
this.addCounters(target.object, '+1/+1', 1)
|
||||
// shortcut: the explored card always goes to the graveyard instead of
|
||||
// asking whether to put it on top. Upgrade when the choice matters.
|
||||
this.moveToZone(card, 'graveyard', { silent: false })
|
||||
this.logMessage(`${player.name} explores with ${target.object.definition.name}`)
|
||||
}
|
||||
|
||||
private incubate(context: EffectContext, amount: Value | undefined): void {
|
||||
const counters = amount ? Math.max(0, this.value(amount, context)) : 0
|
||||
const count = this.tokenMultiplier(context.controller, false)
|
||||
for (let i = 0; i < count; i++) {
|
||||
const token = this.createToken(context.controller, {
|
||||
types: ['artifact'],
|
||||
subtypes: ['incubator'],
|
||||
colors: [],
|
||||
}, context)
|
||||
this.addCounters(token, '+1/+1', counters)
|
||||
}
|
||||
}
|
||||
|
||||
private impulse(context: EffectContext): void {
|
||||
const player = this.getPlayer(context.controller)
|
||||
const cardId = player.library[0]
|
||||
if (!cardId) return
|
||||
const card = this.getObject(cardId)
|
||||
this.moveToZone(card, 'exile', { silent: false })
|
||||
card.playableFromExileTurn = this.turn
|
||||
this.logMessage(`${player.name} exiles ${card.definition.name} and may play it this turn`)
|
||||
}
|
||||
|
||||
private dig(
|
||||
context: EffectContext,
|
||||
effect: Extract<Effect, { op: 'dig' }>,
|
||||
@@ -2467,7 +2727,7 @@ export class Game {
|
||||
}
|
||||
|
||||
private createToken(playerId: string, spec: TokenSpec, context: EffectContext): GameObject {
|
||||
const definition = tokenCard({
|
||||
const card = tokenCard({
|
||||
...spec,
|
||||
power: spec.power ? this.value(spec.power, context) : undefined,
|
||||
toughness: spec.toughness ? this.value(spec.toughness, context) : undefined,
|
||||
@@ -2475,7 +2735,8 @@ export class Game {
|
||||
const player = this.getPlayer(playerId)
|
||||
const object: GameObject = {
|
||||
id: this.generateId('token'),
|
||||
definition,
|
||||
definition: card.definition,
|
||||
backFace: card.backFace,
|
||||
owner: playerId,
|
||||
controller: playerId,
|
||||
zone: 'battlefield',
|
||||
@@ -2503,6 +2764,7 @@ export class Game {
|
||||
const object: GameObject = {
|
||||
id: this.generateId('token'),
|
||||
definition,
|
||||
backFace: source.backFace,
|
||||
owner: playerId,
|
||||
controller: playerId,
|
||||
zone: 'battlefield',
|
||||
@@ -2558,7 +2820,11 @@ export class Game {
|
||||
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 (ability.condition) {
|
||||
if (ability.condition.kind === 'event_subject_toughness_at_most') {
|
||||
if (!event.subject || this.getToughness(event.subject) > ability.condition.amount) continue
|
||||
} else if (!this.checkCondition(ability.condition, source)) continue
|
||||
}
|
||||
if (!this.matchesTrigger(event, ability.event, source)) continue
|
||||
let targets: TargetChoice[]
|
||||
try {
|
||||
@@ -2672,6 +2938,20 @@ export class Game {
|
||||
return this.objectsMatching(target.selector, source)
|
||||
}
|
||||
|
||||
/** Product of every token-doubling replacement that applies to this creation. */
|
||||
private tokenMultiplier(playerId: string, creatureToken: boolean): number {
|
||||
let multiplier = 1
|
||||
for (const { source, ability } of this.staticAbilities()) {
|
||||
for (const effect of ability.effects) {
|
||||
if (effect.op !== 'token_multiplier') continue
|
||||
if (effect.who === 'you' && source.controller !== playerId) continue
|
||||
if (effect.creatureOnly && !creatureToken) continue
|
||||
multiplier *= effect.multiplier
|
||||
}
|
||||
}
|
||||
return multiplier
|
||||
}
|
||||
|
||||
private exilesInsteadOfGraveyard(object: GameObject): boolean {
|
||||
for (const { source, ability } of this.staticAbilities()) {
|
||||
for (const effect of ability.effects) {
|
||||
@@ -2810,6 +3090,8 @@ export class Game {
|
||||
return this.battlefieldObjects()
|
||||
.filter(object => object.controller === controller && this.isCreature(object))
|
||||
.reduce((total, object) => total + this.getPower(object), 0) >= condition.atLeast
|
||||
case 'event_subject_toughness_at_most':
|
||||
return false
|
||||
default:
|
||||
return false
|
||||
}
|
||||
@@ -2914,7 +3196,7 @@ export class Game {
|
||||
return true
|
||||
}
|
||||
|
||||
if ([...player.hand, ...player.command].some(id => this.canPlayCard(playerId, id))) return true
|
||||
if ([...player.hand, ...player.command, ...player.exile].some(id => this.canPlayCard(playerId, id))) return true
|
||||
|
||||
for (const id of player.battlefield) {
|
||||
const object = this.objects.get(id)
|
||||
@@ -3241,6 +3523,12 @@ export class Game {
|
||||
// Most search lines are a single effect.
|
||||
if (this.pendingSearch) return
|
||||
const player = this.getPlayer(playerId)
|
||||
// Searching then shuffling is the same as shuffling first when the picked
|
||||
// cards go on top, and it keeps the shuffle from burying them again.
|
||||
if (shuffle && (destination === 'top' || split?.destination === 'top')) {
|
||||
this.shuffleLibrary(player)
|
||||
shuffle = false
|
||||
}
|
||||
let remaining = amount
|
||||
let first = true
|
||||
while (remaining > 0) {
|
||||
@@ -3379,6 +3667,7 @@ export class Game {
|
||||
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
|
||||
@@ -3517,7 +3806,7 @@ export class Game {
|
||||
const match = counter.match(/^([+-])(\d+)\/([+-])(\d+)$/)
|
||||
if (!match) continue
|
||||
const value = stat === 'power' ? `${match[1]}${match[2]}` : `${match[3]}${match[4]}`
|
||||
total += Number(value)
|
||||
total += Number(value) * count
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { getCardDefinition } from './catalog.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { validateCommanderDeck } from './commander.js'
|
||||
import { Game, GameError } from './game.js'
|
||||
import type { CardDefinition, GameObject, ManaPool, TargetChoice } from './types.js'
|
||||
import type { CardDefinition, GameObject, ManaColor, ManaPool, TargetChoice } from './types.js'
|
||||
|
||||
export class MatchError extends Error {
|
||||
constructor(message: string, readonly status = 400) {
|
||||
@@ -28,6 +28,8 @@ export interface ActionPayload {
|
||||
mode?: number
|
||||
overload?: boolean
|
||||
choice?: string
|
||||
/** Mana color picked when activating a mana ability that can make several. */
|
||||
color?: string
|
||||
pay?: boolean
|
||||
position?: { x?: unknown; y?: unknown }
|
||||
attackers?: { attackerId: string; defenderId: string }[]
|
||||
@@ -60,7 +62,13 @@ export interface CardView {
|
||||
blocking?: string
|
||||
/** Creature type chosen as this permanent entered, if any. */
|
||||
chosenType?: string
|
||||
abilities: { index: number; kind: string; text?: string }[]
|
||||
/** Number of face-down cards exiled under this permanent (hideaway). */
|
||||
hiddenCards?: number
|
||||
/** This exiled card is face down; its identity is not included. */
|
||||
faceDown?: boolean
|
||||
/** Legal choices for this card's targets, for the cast panel. */
|
||||
targets?: TargetChoice[]
|
||||
abilities: { index: number; kind: string; text?: string; targets?: TargetChoice[]; manaColors?: string[] }[]
|
||||
/** Viewer-specific: can this card be played from hand right now? */
|
||||
playable?: boolean
|
||||
}
|
||||
@@ -136,6 +144,8 @@ export interface MatchView {
|
||||
amount?: number
|
||||
/** Choices to offer, populated only for the chooser. */
|
||||
options: string[]
|
||||
/** Cards to choose from for hideaway, populated only for the chooser. */
|
||||
cards?: CardView[]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -426,6 +436,7 @@ export function performAction(matchId: string, token: string | undefined, action
|
||||
x: Number.isFinite(action.x) ? Number(action.x) : 0,
|
||||
mode: Number.isFinite(action.mode) ? Number(action.mode) : 0,
|
||||
overload: action.overload === true,
|
||||
manaColor: manaColorOf(action.color),
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -457,6 +468,9 @@ export function performAction(matchId: string, token: string | undefined, action
|
||||
case 'choose_search':
|
||||
game.chooseSearchCard(seat.playerId, requireId(action.cardId))
|
||||
break
|
||||
case 'choose_hideaway':
|
||||
game.chooseHideawayCard(seat.playerId, requireId(action.cardId))
|
||||
break
|
||||
case 'choose_type':
|
||||
if (typeof action.choice !== 'string') throw new MatchError('Missing type choice')
|
||||
game.chooseCreatureType(seat.playerId, action.choice)
|
||||
@@ -503,9 +517,46 @@ function requireId(id: unknown): string {
|
||||
return id
|
||||
}
|
||||
|
||||
function manaColorOf(value: unknown): ManaColor | undefined {
|
||||
if (value === undefined) return undefined
|
||||
if (typeof value !== 'string' || !/^[WUBRGCS]$/i.test(value)) throw new MatchError('Invalid mana color')
|
||||
return value.toUpperCase() as ManaColor
|
||||
}
|
||||
|
||||
function cardView(game: Game, object: GameObject, abilities = true): CardView {
|
||||
// Face-down exiled cards (hideaway) keep their identity server-side only.
|
||||
if (object.faceDown) {
|
||||
return {
|
||||
id: object.id,
|
||||
oracleId: '',
|
||||
name: 'Face-down card',
|
||||
typeLine: '',
|
||||
colors: [],
|
||||
colorIdentity: [],
|
||||
tapped: false,
|
||||
damage: 0,
|
||||
counters: {},
|
||||
isToken: false,
|
||||
isCommander: false,
|
||||
zone: object.zone,
|
||||
controller: object.controller,
|
||||
owner: object.owner,
|
||||
blockedBy: [],
|
||||
faceDown: true,
|
||||
abilities: [],
|
||||
}
|
||||
}
|
||||
const definition = object.definition
|
||||
const creature = /creature/i.test(definition.typeLine)
|
||||
const hiddenCards = object.zone === 'battlefield'
|
||||
? (object.linkedExile ?? []).filter(id => {
|
||||
const linked = game.objects.get(id)
|
||||
return linked?.zone === 'exile' && linked.faceDown
|
||||
}).length
|
||||
: 0
|
||||
const targets = object.zone === 'hand' || object.zone === 'command' || object.zone === 'exile'
|
||||
? game.legalTargetsForCard(object.owner, object.id)
|
||||
: []
|
||||
return {
|
||||
id: object.id,
|
||||
oracleId: definition.oracleId,
|
||||
@@ -531,11 +582,17 @@ function cardView(game: Game, object: GameObject, abilities = true): CardView {
|
||||
blockedBy: [...object.blockedBy],
|
||||
blocking: object.blocking,
|
||||
chosenType: object.chosenCreatureType,
|
||||
hiddenCards: hiddenCards || undefined,
|
||||
targets: targets.length ? targets : undefined,
|
||||
abilities: abilities
|
||||
? (definition.abilities ?? []).map((ability, index) => ({
|
||||
index,
|
||||
kind: ability.kind,
|
||||
text: 'text' in ability ? ability.text : undefined,
|
||||
manaColors: game.manaColorChoices(object, index),
|
||||
targets: ability.kind === 'activated' && object.zone === 'battlefield'
|
||||
? game.legalTargetsForAbility(object.controller, object.id, index)
|
||||
: undefined,
|
||||
}))
|
||||
: [],
|
||||
}
|
||||
@@ -560,6 +617,16 @@ function serialize(match: Match, viewerId: string): MatchView {
|
||||
const game = match.game
|
||||
if (!game) return view
|
||||
|
||||
const hiddenUnderSource = new Set<string>()
|
||||
for (const player of game.players) {
|
||||
for (const id of player.battlefield) {
|
||||
for (const linked of game.getObject(id).linkedExile ?? []) {
|
||||
const object = game.objects.get(linked)
|
||||
if (object?.zone === 'exile' && object.faceDown) hiddenUnderSource.add(linked)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view.players = match.seats.map(seat => {
|
||||
const player = game.getPlayer(seat.playerId)
|
||||
return {
|
||||
@@ -572,7 +639,15 @@ function serialize(match: Match, viewerId: string): MatchView {
|
||||
libraryCount: player.library.length,
|
||||
battlefield: player.battlefield.map(id => cardView(game, game.getObject(id))),
|
||||
graveyard: player.graveyard.map(id => cardView(game, game.getObject(id), false)),
|
||||
exile: player.exile.map(id => cardView(game, game.getObject(id), false)),
|
||||
exile: player.exile
|
||||
.filter(id => !hiddenUnderSource.has(id))
|
||||
.map(id => {
|
||||
const playable = player.id === viewerId && game.canPlayCard(viewerId, id)
|
||||
return {
|
||||
...cardView(game, game.getObject(id), playable),
|
||||
...(playable ? { playable } : {}),
|
||||
}
|
||||
}),
|
||||
command: player.command.map(id => cardView(game, game.getObject(id), false)),
|
||||
commanderId: player.commanderId,
|
||||
commanderDamage: Object.entries(player.commanderDamage)
|
||||
@@ -621,6 +696,9 @@ function serialize(match: Match, viewerId: string): MatchView {
|
||||
sourceName: game.objects.get(choice.sourceId)?.definition.name ?? 'Permanent',
|
||||
amount: choice.amount,
|
||||
options: choice.playerId === viewerId && choice.what === 'creature_type' ? [...CREATURE_TYPES] : [],
|
||||
cards: choice.playerId === viewerId && choice.what === 'hideaway'
|
||||
? (choice.cardIds ?? []).map(id => cardView(game, game.getObject(id), false))
|
||||
: undefined,
|
||||
}
|
||||
: undefined,
|
||||
pendingSearch: search
|
||||
|
||||
414
backend/src/game/tokens.ts
Normal file
414
backend/src/game/tokens.ts
Normal file
@@ -0,0 +1,414 @@
|
||||
import type { Ability, Cost, Effect, StaticEffect } from '../effects/types.js'
|
||||
|
||||
/**
|
||||
* The predefined tokens from rule 111.10. Effects that name one of these
|
||||
* tokens ("create a Treasure token") use these characteristics instead of
|
||||
* whatever the oracle parser managed to infer from the words.
|
||||
*/
|
||||
export interface PredefinedTokenFace {
|
||||
name: string
|
||||
types: string[]
|
||||
subtypes: string[]
|
||||
colors: string[]
|
||||
power?: number
|
||||
toughness?: number
|
||||
keywords?: string[]
|
||||
abilities?: Ability[]
|
||||
}
|
||||
|
||||
export interface PredefinedToken extends PredefinedTokenFace {
|
||||
/** Back face of a double-faced token, currently only Incubator. */
|
||||
backFace?: PredefinedTokenFace
|
||||
}
|
||||
|
||||
function activated(costs: Cost[], effects: Effect[], text: string, timing?: 'sorcery'): Ability {
|
||||
return { kind: 'activated', costs, effects, timing, optional: false, text }
|
||||
}
|
||||
|
||||
function anyColor(): Effect {
|
||||
return {
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: { kind: 'any_color', amount: { kind: 'number', value: 1 }, oneColor: false },
|
||||
}
|
||||
}
|
||||
|
||||
function drawOne(): Effect {
|
||||
return { op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } }
|
||||
}
|
||||
|
||||
function pumpEnchanted(power: number, toughness: number): StaticEffect {
|
||||
return {
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
|
||||
power: { kind: 'number', value: power },
|
||||
toughness: { kind: 'number', value: toughness },
|
||||
}
|
||||
}
|
||||
|
||||
function grantEnchanted(keyword: string, value?: string): StaticEffect {
|
||||
return {
|
||||
op: 'grant',
|
||||
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
|
||||
keyword,
|
||||
...(value ? { value } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
const tap: Cost = { kind: 'tap' }
|
||||
const sacrificeSelf: Cost = { kind: 'sacrifice_self' }
|
||||
const mana = (symbols: string): Cost => ({ kind: 'mana', symbols })
|
||||
const enchantCreature: Ability = { kind: 'keyword', keyword: 'Enchant', value: 'creature' }
|
||||
|
||||
function attackTrigger(effects: Effect[], text: string, condition?: Extract<Ability, { kind: 'triggered' }>['condition']): Ability {
|
||||
return {
|
||||
kind: 'triggered',
|
||||
event: {
|
||||
kind: 'attacks',
|
||||
subject: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
|
||||
},
|
||||
...(condition ? { condition } : {}),
|
||||
effects,
|
||||
optional: false,
|
||||
text,
|
||||
}
|
||||
}
|
||||
|
||||
export const PREDEFINED_TOKENS: Record<string, PredefinedToken> = {
|
||||
treasure: {
|
||||
name: 'Treasure',
|
||||
types: ['artifact'],
|
||||
subtypes: ['treasure'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[tap, sacrificeSelf],
|
||||
[anyColor()],
|
||||
'{T}, Sacrifice this artifact: Add one mana of any color.',
|
||||
)],
|
||||
},
|
||||
food: {
|
||||
name: 'Food',
|
||||
types: ['artifact'],
|
||||
subtypes: ['food'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{2}'), tap, sacrificeSelf],
|
||||
[{ op: 'life', player: 'you', amount: { kind: 'number', value: 3 }, mode: 'gain' }],
|
||||
'{2}, {T}, Sacrifice this artifact: You gain 3 life.',
|
||||
)],
|
||||
},
|
||||
gold: {
|
||||
name: 'Gold',
|
||||
types: ['artifact'],
|
||||
subtypes: ['gold'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[sacrificeSelf],
|
||||
[anyColor()],
|
||||
'Sacrifice this artifact: Add one mana of any color.',
|
||||
)],
|
||||
},
|
||||
walker: {
|
||||
name: 'Walker',
|
||||
types: ['creature'],
|
||||
subtypes: ['zombie'],
|
||||
colors: ['B'],
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
},
|
||||
shard: {
|
||||
name: 'Shard',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['shard'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{2}'), sacrificeSelf],
|
||||
[
|
||||
{ op: 'scry', player: 'you', amount: { kind: 'number', value: 1 } },
|
||||
drawOne(),
|
||||
],
|
||||
'{2}, Sacrifice this enchantment: Scry 1, then draw a card.',
|
||||
)],
|
||||
},
|
||||
clue: {
|
||||
name: 'Clue',
|
||||
types: ['artifact'],
|
||||
subtypes: ['clue'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{2}'), sacrificeSelf],
|
||||
[drawOne()],
|
||||
'{2}, Sacrifice this artifact: Draw a card.',
|
||||
)],
|
||||
},
|
||||
blood: {
|
||||
name: 'Blood',
|
||||
types: ['artifact'],
|
||||
subtypes: ['blood'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{1}'), tap, { kind: 'discard', amount: { kind: 'number', value: 1 }, player: 'you' }, sacrificeSelf],
|
||||
[drawOne()],
|
||||
'{1}, {T}, Discard a card, Sacrifice this artifact: Draw a card.',
|
||||
)],
|
||||
},
|
||||
powerstone: {
|
||||
name: 'Powerstone',
|
||||
types: ['artifact'],
|
||||
subtypes: ['powerstone'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[tap],
|
||||
[{
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
// shortcut: the pool does not track restricted mana yet, so this is
|
||||
// usable for any spell. Upgrade when spell-type mana restrictions matter.
|
||||
mana: { kind: 'symbols', symbols: ['{C}'], restriction: 'artifact spells' },
|
||||
}],
|
||||
'{T}: Add {C}. This mana can\'t be spent to cast a nonartifact spell.',
|
||||
)],
|
||||
},
|
||||
incubator: {
|
||||
name: 'Incubator',
|
||||
types: ['artifact'],
|
||||
subtypes: ['incubator'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{2}')],
|
||||
[{ op: 'transform', target: { kind: 'self' } }],
|
||||
'{2}: Transform this artifact.',
|
||||
)],
|
||||
backFace: {
|
||||
name: 'Phyrexian',
|
||||
types: ['artifact', 'creature'],
|
||||
subtypes: ['phyrexian'],
|
||||
colors: [],
|
||||
power: 0,
|
||||
toughness: 0,
|
||||
},
|
||||
},
|
||||
map: {
|
||||
name: 'Map',
|
||||
types: ['artifact'],
|
||||
subtypes: ['map'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{1}'), tap, sacrificeSelf],
|
||||
[{
|
||||
op: 'keyword_action',
|
||||
action: 'explore',
|
||||
target: { kind: 'object', selector: { types: ['creature'], controller: 'you' }, mode: 'target' },
|
||||
}],
|
||||
'{1}, {T}, Sacrifice this artifact: Target creature you control explores. Activate only as a sorcery.',
|
||||
'sorcery',
|
||||
)],
|
||||
},
|
||||
junk: {
|
||||
name: 'Junk',
|
||||
types: ['artifact'],
|
||||
subtypes: ['junk'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[tap, sacrificeSelf],
|
||||
[{ op: 'keyword_action', action: 'impulse' }],
|
||||
'{T}, Sacrifice this artifact: Exile the top card of your library. You may play that card this turn. Activate only as a sorcery.',
|
||||
'sorcery',
|
||||
)],
|
||||
},
|
||||
lander: {
|
||||
name: 'Lander',
|
||||
types: ['artifact'],
|
||||
subtypes: ['lander'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{2}'), tap, sacrificeSelf],
|
||||
[{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { supertypes: ['basic'], types: ['land'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
}],
|
||||
'{2}, {T}, Sacrifice this artifact: Search your library for a basic land card, put it onto the battlefield tapped, then shuffle.',
|
||||
)],
|
||||
},
|
||||
mutagen: {
|
||||
name: 'Mutagen',
|
||||
types: ['artifact'],
|
||||
subtypes: ['mutagen'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{1}'), tap, sacrificeSelf],
|
||||
[{
|
||||
op: 'put_counters',
|
||||
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
|
||||
counter: '+1/+1',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}],
|
||||
'{1}, {T}, Sacrifice this artifact: Put a +1/+1 counter on target creature. Activate only as a sorcery.',
|
||||
'sorcery',
|
||||
)],
|
||||
},
|
||||
vibranium: {
|
||||
name: 'Vibranium',
|
||||
types: ['artifact'],
|
||||
subtypes: ['vibranium'],
|
||||
colors: [],
|
||||
keywords: ['Indestructible'],
|
||||
abilities: [activated(
|
||||
[tap],
|
||||
[{
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: { kind: 'symbols', symbols: ['{C}'], restriction: 'artifact spells' },
|
||||
}],
|
||||
'Indestructible\n{T}: Add {C}. This mana can\'t be spent to cast a nonartifact spell.',
|
||||
)],
|
||||
},
|
||||
heartwood: {
|
||||
name: 'Heartwood',
|
||||
types: ['artifact'],
|
||||
subtypes: ['heartwood'],
|
||||
colors: ['R', 'G'],
|
||||
abilities: [activated(
|
||||
[tap],
|
||||
[{
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: { kind: 'symbols', symbols: ['{R}', '{G}'], oneOf: true },
|
||||
}],
|
||||
'{T}: Add {R} or {G}.',
|
||||
)],
|
||||
},
|
||||
cursed: {
|
||||
name: 'Cursed Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'set_pt',
|
||||
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
|
||||
power: { kind: 'number', value: 1 },
|
||||
toughness: { kind: 'number', value: 1 },
|
||||
base: true,
|
||||
}],
|
||||
text: 'Enchanted creature has base power and toughness 1/1.',
|
||||
},
|
||||
],
|
||||
},
|
||||
monster: {
|
||||
name: 'Monster Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{ kind: 'static', effects: [pumpEnchanted(1, 1), grantEnchanted('Trample')], text: 'Enchanted creature gets +1/+1 and has trample.' },
|
||||
],
|
||||
},
|
||||
royal: {
|
||||
name: 'Royal Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{ kind: 'static', effects: [pumpEnchanted(1, 1), grantEnchanted('Ward', '{1}')], text: 'Enchanted creature gets +1/+1 and has ward {1}.' },
|
||||
],
|
||||
},
|
||||
sorcerer: {
|
||||
name: 'Sorcerer Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{ kind: 'static', effects: [pumpEnchanted(1, 1)], text: 'Enchanted creature gets +1/+1.' },
|
||||
attackTrigger(
|
||||
[{ op: 'scry', player: 'you', amount: { kind: 'number', value: 1 } }],
|
||||
'Whenever enchanted creature attacks, scry 1.',
|
||||
),
|
||||
],
|
||||
},
|
||||
virtuous: {
|
||||
name: 'Virtuous Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
|
||||
power: { kind: 'count', selector: { types: ['enchantment'], controller: 'you' } },
|
||||
toughness: { kind: 'count', selector: { types: ['enchantment'], controller: 'you' } },
|
||||
}],
|
||||
text: 'Enchanted creature gets +1/+1 for each enchantment you control.',
|
||||
},
|
||||
],
|
||||
},
|
||||
wicked: {
|
||||
name: 'Wicked Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{ kind: 'static', effects: [pumpEnchanted(1, 1)], text: 'Enchanted creature gets +1/+1.' },
|
||||
{
|
||||
kind: 'triggered',
|
||||
// Curse of the Werefox and friends put this in the graveyard; the
|
||||
// engine only distinguishes "died" for creatures, so any leave triggers it.
|
||||
event: { kind: 'leaves_battlefield', subject: { kind: 'self' } },
|
||||
effects: [{ op: 'life', player: 'each_opponent', amount: { kind: 'number', value: 1 }, mode: 'lose' }],
|
||||
optional: false,
|
||||
text: 'When this token is put into a graveyard from the battlefield, each opponent loses 1 life.',
|
||||
},
|
||||
],
|
||||
},
|
||||
'young hero': {
|
||||
name: 'Young Hero Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
attackTrigger(
|
||||
[{
|
||||
op: 'put_counters',
|
||||
target: { kind: 'trigger_subject' },
|
||||
counter: '+1/+1',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}],
|
||||
'Whenever enchanted creature attacks, if its toughness is 3 or less, put a +1/+1 counter on it.',
|
||||
{ kind: 'event_subject_toughness_at_most', amount: 3 },
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
/** Finds a predefined token by subtype or name, including "Cursed Role". */
|
||||
export function predefinedToken(spec: { name?: string; subtypes: string[] }): PredefinedToken | undefined {
|
||||
const words = spec.subtypes.map(word => word.toLowerCase())
|
||||
const roleIndex = words.indexOf('role')
|
||||
const candidates = roleIndex >= 0 ? [words.slice(0, roleIndex).join(' ')] : []
|
||||
candidates.push(...words)
|
||||
for (const candidate of candidates) {
|
||||
const token = PREDEFINED_TOKENS[candidate]
|
||||
if (token) return token
|
||||
}
|
||||
if (spec.name) {
|
||||
const name = spec.name.toLowerCase()
|
||||
return PREDEFINED_TOKENS[name] ?? PREDEFINED_TOKENS[name.replace(/\s+role$/, '')]
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
@@ -94,6 +94,10 @@ export interface GameObject {
|
||||
counters: Record<string, number>
|
||||
isToken: boolean
|
||||
token?: TokenSpec
|
||||
/** Back face of a double-faced token (Incubator); transform swaps it in. */
|
||||
backFace?: CardDefinition
|
||||
/** Set by impulse effects; the card may be played from exile this turn. */
|
||||
playableFromExileTurn?: number
|
||||
isCommander?: boolean
|
||||
enteredTurn: number
|
||||
/** Normalized center on the controller's mat; absent means auto-arranged. */
|
||||
@@ -105,6 +109,8 @@ export interface GameObject {
|
||||
attachedTo?: string
|
||||
/** Cards exiled with this object, such as a card hidden by hideaway. */
|
||||
linkedExile?: string[]
|
||||
/** Exiled face down (hideaway); its identity is hidden from every view. */
|
||||
faceDown?: boolean
|
||||
/** Creature type chosen as this permanent entered (Cavern of Souls). */
|
||||
chosenCreatureType?: string
|
||||
regenerationShields: number
|
||||
@@ -136,6 +142,8 @@ export interface ActionOptions {
|
||||
x?: number
|
||||
mode?: number
|
||||
overload?: boolean
|
||||
/** Color chosen for a mana ability that can produce more than one. */
|
||||
manaColor?: ManaColor
|
||||
}
|
||||
|
||||
/** A search that is waiting for its player to pick one of several matching cards. */
|
||||
@@ -151,15 +159,17 @@ export interface PendingSearch {
|
||||
split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean }
|
||||
}
|
||||
|
||||
/** An "as this enters..." pause. Blocks all actions until its controller picks. */
|
||||
/** A pause such as "as this enters..." or a hideaway look. Blocks all actions until its controller picks. */
|
||||
export interface PendingChoice {
|
||||
playerId: string
|
||||
sourceId: string
|
||||
what: 'creature_type' | 'pay_cost'
|
||||
what: 'creature_type' | 'pay_cost' | 'hideaway'
|
||||
/** Cost to pay to avoid entering tapped. */
|
||||
cost?: Cost
|
||||
/** Life total to display for a `pay_life` cost. */
|
||||
amount?: number
|
||||
/** Cards to choose from for `hideaway`. */
|
||||
cardIds?: string[]
|
||||
}
|
||||
|
||||
export interface CombatAttack {
|
||||
|
||||
Reference in New Issue
Block a user