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

@@ -69,9 +69,11 @@ const deckSchema = new Schema({
commander: { type: deckCardSchema, required: true },
cards: { type: [deckCardSchema], default: [] },
cardBack: { type: String, default: null },
shareToken: String,
updatedAt: { type: Number, required: true },
})
deckSchema.index({ owner: 1, deckId: 1 }, { unique: true })
deckSchema.index({ shareToken: 1 }, { unique: true, sparse: true })
const User = mongoose.models.User ?? mongoose.model('User', userSchema)
const Session = mongoose.models.Session ?? mongoose.model('Session', sessionSchema)
@@ -83,6 +85,7 @@ interface DeckRow {
commander: DeckCardInput
cards: DeckCardInput[]
cardBack?: string | null
shareToken?: string
updatedAt: number
}
@@ -305,6 +308,34 @@ export function registerAccountRoutes(app: FastifyInstance): void {
return { ok: true }
})
// Reuses the deck's token so re-sharing a deck never breaks an existing link.
app.post<{ Params: { id: string } }>('/me/decks/:id/share', async (request, reply) => {
const user = await authenticate(request)
const deckId = request.params.id
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(deckId)) {
return reply.code(400).send({ error: 'Invalid deck id' })
}
const created = await Deck.findOneAndUpdate(
{ owner: user.id, deckId, shareToken: null },
{ $set: { shareToken: randomBytes(16).toString('base64url') } },
{ returnDocument: 'after' },
).lean<DeckRow>()
if (created?.shareToken) return { token: created.shareToken }
const existing = await Deck.findOne({ owner: user.id, deckId }).lean<DeckRow>()
if (!existing?.shareToken) return reply.code(404).send({ error: 'Deck not found' })
return { token: existing.shareToken }
})
app.get<{ Params: { token: string } }>('/decks/share/:token', async (request, reply) => {
if (!/^[A-Za-z0-9_-]{22}$/.test(request.params.token)) {
return reply.code(404).send({ error: 'Shared deck not found' })
}
const deck = await Deck.findOne({ shareToken: request.params.token }).lean<DeckRow>()
if (!deck) return reply.code(404).send({ error: 'Shared deck not found' })
return { deck: toDeck(deck, await implementationIndex()) }
})
app.get('/me/preferences', async request => {
const user = await authenticate(request)
return preferences(user.id)

View File

@@ -448,6 +448,27 @@ function parseDigDestination(text: string): 'hand' | 'graveyard' | 'battlefield'
return 'bottom'
}
function parseSearchDestination(
text: string,
): { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean } | undefined {
switch (text) {
case 'into your hand':
return { destination: 'hand', tapped: false }
case 'onto the battlefield':
return { destination: 'battlefield', tapped: false }
case 'onto the battlefield tapped':
return { destination: 'battlefield', tapped: true }
case 'into your graveyard':
return { destination: 'graveyard', tapped: false }
case 'on top of your library':
return { destination: 'top', tapped: false }
case 'on the bottom of your library':
return { destination: 'bottom', tapped: false }
default:
return undefined
}
}
function parseSearch(text: string): Effect | undefined {
const match = text.match(/^search your (library|library and\/or graveyard) for (.+)$/)
if (!match) return undefined
@@ -476,34 +497,53 @@ function parseSearch(text: string): Effect | undefined {
const revealPrefix = /^reveal (?:it|them|that card|those cards),? (?:and )?/
let destinationText = rest.replace(revealPrefix, '')
let shuffle = false
if (/^then shuffle and put (?:it|them|that card|those cards) on top(?: of your library)?$/.test(destinationText)) {
if (/^then shuffle and put (?:it|them|that card|those cards|the card|the chosen card) on top(?: of your library)?$/.test(destinationText)) {
return { op: 'search', player: 'you', selector, amount, destination: 'top', tapped: false, shuffle: true, ...(zones ? { zones } : {}) }
}
if (/^shuffle and put (?:it|them|that card|those cards) on top(?: of your library)?$/.test(destinationText)) {
if (/^shuffle and put (?:it|them|that card|those cards|the card|the chosen card) on top(?: of your library)?$/.test(destinationText)) {
return { op: 'search', player: 'you', selector, amount, destination: 'top', tapped: false, shuffle: true, ...(zones ? { zones } : {}) }
}
if (/^put (?:it|them|that card|those cards) on top of your library, then shuffle$/.test(destinationText)) {
if (/^put (?:it|them|that card|those cards|the card|the chosen card) on top of your library, then shuffle$/.test(destinationText)) {
return { op: 'search', player: 'you', selector, amount, destination: 'top', tapped: false, shuffle: true, ...(zones ? { zones } : {}) }
}
const split = destinationText.match(/^put one (.+?) and the other (.+?)(, then shuffle)?$/)
if (split && amount.kind === 'number' && amount.value >= 2) {
const first = parseSearchDestination(split[1].trim())
const second = parseSearchDestination(split[2].trim())
if (first && second) {
return {
op: 'search',
player: 'you',
selector,
amount,
destination: first.destination,
tapped: first.tapped,
shuffle: Boolean(split[3]),
split: second,
...(zones ? { zones } : {}),
}
}
}
const put = destinationText.match(
/^put (?:it|them|that card|those cards|the chosen card) (into your hand|onto the battlefield(?: tapped)?|into your graveyard|on top of your library|on the bottom of your library)(?: under your control)?(?:, then shuffle)?$/,
)
if (!put) continue
const destination =
put[1] === 'into your hand'
? 'hand'
: put[1].startsWith('onto the battlefield')
? 'battlefield'
: put[1] === 'into your graveyard'
? 'graveyard'
: put[1] === 'on top of your library'
? 'top'
: 'bottom'
const parsedDestination = parseSearchDestination(put[1])
if (!parsedDestination) continue
shuffle = /then shuffle$/.test(destinationText)
const tapped = /\btapped\b/.test(put[1])
return { op: 'search', player: 'you', selector, amount, destination, tapped, shuffle, ...(zones ? { zones } : {}) }
return {
op: 'search',
player: 'you',
selector,
amount,
destination: parsedDestination.destination,
tapped: parsedDestination.tapped,
shuffle,
...(zones ? { zones } : {}),
}
}
return undefined
@@ -750,6 +790,8 @@ function parseEffect(text: string): Effect | Effect[] | undefined {
if (target) return { op: 'destroy', target }
}
if (sentence === 'exile all graveyards') return { op: 'exile_graveyards' }
match = sentence.match(/^exile (.+)$/)
if (match) {
const target = parseGroupTarget(match[1])
@@ -1084,6 +1126,9 @@ function parseEffect(text: string): Effect | Effect[] | undefined {
if (sentence === 'shuffle your library') return { op: 'shuffle', player: 'you' }
match = sentence.match(/^(?:you may )?play the exiled card without paying its mana cost$/)
if (match) return { op: 'play_exiled', player: 'you', free: true }
return undefined
}
@@ -1359,6 +1404,14 @@ function parseEffects(text: string): { effects: Effect[]; optional: boolean } |
return undefined
}
// The search already shuffles; the sentence only spells out when.
if (/^if you search your library this way, shuffle\.?$/i.test(sentence)) {
const last = effects[effects.length - 1]
if (last?.op !== 'search') return undefined
last.shuffle = true
continue
}
const conditional = sentence.match(/^if (.+?), (.+)$/i)
if (conditional) {
const raw = conditional[1].trim().toLowerCase()
@@ -1630,8 +1683,28 @@ function parseStaticTarget(text: string): Target | undefined {
return undefined
}
/** "Each spell you cast that's X" and "X spells and Y spells" reduce on a union. */
function parseCostReductionTarget(text: string): Target | undefined {
const eachSpell = text.match(/^each spell you cast that(?:'s| is) (.+)$/)
const normalized = eachSpell
? `${eachSpell[1].replace(/^an? /, '')} spells you cast`
: text
const target = parseStaticTarget(normalized)
if (!target || target.kind !== 'object') return target
if (!/\band\b|,/.test(normalized)) return target
target.selector.match = 'any'
// parseSelector infers one type from the first subtype; a mixed list has none.
if ((target.selector.subtypes?.length ?? 0) > 1) target.selector.types = []
return target
}
function parseStaticEffects(text: string): StaticEffect[] | undefined {
const sentence = text.trim().replace(/\.$/, '')
const sentence = text
.trim()
.replace(/\.$/, '')
// Clarifies how a colored cost reduction works; our symbols do exactly this.
.replace(/\. this effect reduces only the amount of colored mana you pay$/, '')
let match = sentence.match(/^(?:its|this's) (base )?power and toughness are each equal to (.+)$/)
if (match) {
@@ -1875,6 +1948,33 @@ function parseStaticEffects(text: string): StaticEffect[] | undefined {
return [{ op: 'replacement', what: 'leaves_battlefield', instead: 'exile', target: { kind: 'self' } }]
}
if (sentence === 'if a card or token would be put into a graveyard from anywhere, exile it instead') {
return [{ op: 'exile_instead_of_graveyard' }]
}
match = sentence.match(/^if a card would be put into (an opponent's|your) graveyard from anywhere, exile it instead$/)
if (match) {
return [{ op: 'exile_instead_of_graveyard', owner: match[1] === 'your' ? 'you' : 'opponent' }]
}
match = sentence.match(/^if (an opponent|you) would search (?:a|their) library, that player searches the top (\w+) cards? of that library instead$/)
if (match) {
const amount = parseValue(match[2])
if (amount) return [{ op: 'search_restriction', who: match[1] === 'you' ? 'you' : 'opponent', amount }]
}
match = sentence.match(/^activated abilities of (.+?) cannot be activated$/)
if (match) {
const target = parseStaticTarget(match[1])
if (target) return [{ op: 'restriction', target, rule: 'cant_activate' }]
}
match = sentence.match(/^(noncreature|creature) spells cost (\{[^}]+\}) more to cast$/)
if (match) {
const amount = parseValue(match[2].slice(1, -1))
if (amount) return [{ op: 'cost_increase', amount, spellType: match[1] === 'creature' ? 'creature' : 'noncreature' }]
}
let costText = sentence
let costCondition: Condition | undefined
let costAmount: Value | undefined
@@ -1896,17 +1996,25 @@ function parseStaticEffects(text: string): StaticEffect[] | undefined {
}
match = costText.match(/^(.+?) costs? ((?:\{[^}]+\})+) less to cast(?: for each (.+))?$/)
if (match) {
const target = parseStaticTarget(match[1])
const target = parseCostReductionTarget(match[1])
let amount: Value | undefined = costAmount
let symbols: string | undefined
if (!amount && match[3]) {
const selector = parseSelector(match[3])
if (selector) amount = { kind: 'count', selector }
} else if (!amount) {
const inner = match[2].match(/\{([^}]+)\}/)?.[1]
if (inner) amount = parseValue(inner.toLowerCase())
const parts = [...match[2].matchAll(/\{([^}]+)\}/g)].map(symbol => symbol[1])
if (parts.some(part => /[WUBRGC]/i.test(part))) symbols = match[2].toUpperCase()
else if (parts[0]) amount = parseValue(parts[0].toLowerCase())
}
if (target && amount) {
return [{ op: 'cost_reduction', target, amount, condition: costCondition }]
if (target && (amount || symbols)) {
return [{
op: 'cost_reduction',
target,
...(amount ? { amount } : {}),
...(symbols ? { symbols } : {}),
...(costCondition ? { condition: costCondition } : {}),
}]
}
}
@@ -2101,6 +2209,28 @@ function compileLine(rawLine: string, name: string, known: Set<string>, isSpell:
if (/^[•·]/.test(line) || /^choose (?:one|two|three|four|five|one or both|one or more)\b/.test(line.toLowerCase())) {
return { kind: 'unsupported', reason: 'modal', text: line }
}
if (/^if you control a commander, you may cast this without paying its mana cost\.?$/.test(lower)) {
return { kind: 'alternative_cost', costs: [], condition: { kind: 'you_control_commander' }, text: line }
}
const overload = lower.match(/^overload ((?:\{[^}]+\})+)$/)
if (overload) return { kind: 'overload', cost: overload[1].toUpperCase(), text: line }
const hideaway = lower.match(/^hideaway (\d+)(?:, hideaway (\d+))?$/)
if (hideaway) {
const effects: Effect[] = [hideaway[1], hideaway[2]]
.filter((amount): amount is string => Boolean(amount))
.map(amount => ({ op: 'hideaway', amount: { kind: 'number', value: Number(amount) } }))
return {
kind: 'triggered',
event: { kind: 'enters', subject: { kind: 'self' } },
effects,
optional: false,
text: line,
}
}
const chapter = body.match(/^([ivx]+(?:, [ivx]+)*) — (.+)$/i)
if (chapter) {
const effects = parseEffects(resolveIt(chapter[2], 'this'))

View File

@@ -58,11 +58,12 @@ function formatSelector(selector: ObjectSelector): string {
if (selector.token) parts.push('token')
if (selector.token === false) parts.push('nontoken')
if (selector.attached) parts.push(selector.attached)
const joiner = selector.match === 'any' ? ' or ' : ' and '
if (selector.colors?.length) {
parts.push(selector.colors.map(color => COLOR_NAMES[color] ?? color).join(' and '))
parts.push(selector.colors.map(color => COLOR_NAMES[color] ?? color).join(joiner))
}
if (selector.supertypes?.length) parts.push(...selector.supertypes)
if (selector.subtypes?.length) parts.push(selector.subtypes.join(' '))
if (selector.supertypes?.length) parts.push(selector.supertypes.join(joiner))
if (selector.subtypes?.length) parts.push(selector.subtypes.join(joiner))
if (selector.types?.length) {
parts.push(selector.types.join(selector.match === 'any' ? ' or ' : ' '))
}
@@ -281,7 +282,7 @@ export function formatEffect(effect: Effect): string {
case 'surveil':
return `surveil(${effect.player}, ${formatValue(effect.amount)})`
case 'search':
return `search(${effect.player}, ${formatSelector(effect.selector)}, ${formatValue(effect.amount)}, to ${effect.destination}${effect.zones?.length === 2 ? ', library+graveyard' : ''}${effect.tapped ? ', tapped' : ''}${effect.shuffle ? ', shuffle' : ''})`
return `search(${effect.player}, ${formatSelector(effect.selector)}, ${formatValue(effect.amount)}, to ${effect.destination}${effect.zones?.length === 2 ? ', library+graveyard' : ''}${effect.tapped ? ', tapped' : ''}${effect.split ? `, then ${effect.split.destination}${effect.split.tapped ? ' tapped' : ''}` : ''}${effect.shuffle ? ', shuffle' : ''})`
case 'shuffle':
return `shuffle(${effect.player})`
case 'add_mana':
@@ -329,6 +330,12 @@ export function formatEffect(effect: Effect): string {
return `schedule(${effect.when}):\n${indent(effect.effects.map(formatEffect).join('\n'))}`
case 'damage_divided':
return `damage_divided(${formatValue(effect.amount)}, ${formatTarget(effect.target)})`
case 'exile_graveyards':
return 'exile_graveyards()'
case 'hideaway':
return `hideaway(${formatValue(effect.amount)})`
case 'play_exiled':
return `play_exiled(${effect.player}${effect.free ? ', free' : ''})`
}
}
@@ -460,6 +467,16 @@ function formatCondition(condition: Condition): string {
return "you don't"
case 'otherwise':
return 'otherwise'
case 'you_control_commander':
return 'you control a commander'
case 'distinct_names':
return `you control ${condition.atLeast}+ ${formatSelector(condition.selector)} with different names`
case 'opponent_damaged_this_turn':
return `an opponent was dealt ${condition.atLeast}+ damage this turn`
case 'attacked_with_creatures':
return `you attacked with ${condition.atLeast}+ creatures this turn`
case 'library_at_most':
return `a library has ${condition.atMost} or fewer cards in it`
}
}
@@ -536,7 +553,13 @@ function formatStaticEffect(effect: StaticEffect): string {
case 'replacement':
return `replace(${effect.what}${effect.target ? `, ${formatTarget(effect.target)}` : ''}, instead ${effect.instead})`
case 'cost_reduction':
return `cost_reduction(${formatTarget(effect.target)}, ${formatValue(effect.amount)}${effect.condition ? `, if ${formatCondition(effect.condition)}` : ''})`
return `cost_reduction(${formatTarget(effect.target)}, ${effect.symbols ?? (effect.amount ? formatValue(effect.amount) : '0')}${effect.condition ? `, if ${formatCondition(effect.condition)}` : ''})`
case 'cost_increase':
return `cost_increase(${formatValue(effect.amount)}${effect.spellType ? `, ${effect.spellType}` : ''})`
case 'search_restriction':
return `search_restriction(${effect.who}, ${formatValue(effect.amount)})`
case 'exile_instead_of_graveyard':
return `exile_instead_of_graveyard(${effect.owner ?? ''})`
}
}
@@ -575,6 +598,12 @@ export function formatAbility(ability: Ability): string {
return `spell${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}`
case 'additional_cost':
return `additional cost${ability.optional ? ' (may)' : ''}: ${ability.costs.map(formatCost).join(', ')}`
case 'alternative_cost': {
const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : ''
return `alternative cost${condition}: ${ability.costs.length ? ability.costs.map(formatCost).join(', ') : 'free'}`
}
case 'overload':
return `overload ${ability.cost}`
case 'chapter':
return `chapter ${ability.chapters.join(', ')}${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}`
case 'level_band': {

View File

@@ -350,6 +350,17 @@ function parseQualifierSuffix(rest: string, selector: ObjectSelector): string {
}
}
match = text.match(/^(.+?) with mana value (\w+)$/)
if (match) {
const amount = parseNumber(match[2])
if (amount !== undefined) {
selector.manaValue = { atLeast: amount, atMost: amount }
text = match[1].trim()
changed = true
continue
}
}
match = text.match(/^(.+?) with (.+)$/)
if (match && SELECTOR_KEYWORDS.has(match[2])) {
selector.keywords = [...(selector.keywords ?? []), match[2]]
@@ -805,6 +816,29 @@ export function parseCondition(text: string): Condition | undefined {
}
if (trimmed === "you've cast a spell this turn") return { kind: 'cast_spell_this_turn' }
if (trimmed === 'you have a full party') return { kind: 'full_party' }
if (trimmed === 'you control a commander') return { kind: 'you_control_commander' }
if (trimmed === 'each player has no cards in hand') {
return { kind: 'cards_in_hand_at_most', who: 'each_player', atMost: 0 }
}
const opponentDamage = trimmed.match(/^an opponent was dealt (\w+) or more damage this turn$/)
if (opponentDamage) {
const amount = parseNumber(opponentDamage[1])
if (amount !== undefined) return { kind: 'opponent_damaged_this_turn', atLeast: amount }
}
const attackedCreatures = trimmed.match(/^you attacked with (\w+) or more creatures this turn$/)
if (attackedCreatures) {
const amount = parseNumber(attackedCreatures[1])
if (amount !== undefined) return { kind: 'attacked_with_creatures', atLeast: amount }
}
const libraryAtMost = trimmed.match(/^a library has (\w+) or fewer cards in it$/)
if (libraryAtMost) {
const amount = parseNumber(libraryAtMost[1])
if (amount !== undefined) return { kind: 'library_at_most', atMost: amount }
}
const graveyard = trimmed.match(/^there are (\w+) or more cards in (your|an opponent's|target player's) graveyard$/)
if (graveyard) {
@@ -888,6 +922,13 @@ export function parseCondition(text: string): Condition | undefined {
const above = trimmed.match(/^you have at least (\d+) life more than your starting life total$/)
if (above) return { kind: 'life_above_starting', player: 'you', amount: Number(above[1]) }
const distinctNames = trimmed.match(/^you control (\w+) or more (.+?) with different names$/)
if (distinctNames) {
const amount = parseNumber(distinctNames[1])
const selector = parseSelector(distinctNames[2])
if (amount !== undefined && selector) return { kind: 'distinct_names', selector, atLeast: amount }
}
const control = trimmed.match(/^you control (?:at least )?(one|two|three|four|five|six|seven|eight|nine|ten|\d+) (?:or more )?(.+)$/)
if (control) {
const selector = parseSelector(control[2])

View File

@@ -816,6 +816,16 @@ function parseEffectExpr(text: string, line: SourceLine): Effect {
}
case 'proliferate':
return { op: 'proliferate' }
case 'exile_graveyards':
return { op: 'exile_graveyards' }
case 'hideaway':
return { op: 'hideaway', amount: parseValueText(arg(args, 0, line), line) }
case 'play_exiled':
return {
op: 'play_exiled',
player: parsePlayer(arg(args, 0, line), line),
free: args[1]?.trim() === 'free' || undefined,
}
case 'create_token': {
const rest = args.slice(2).join(', ').trim()
if (rest.startsWith('copy of ')) {
@@ -903,6 +913,20 @@ function parseEffectExpr(text: string, line: SourceLine): Effect {
if (!['hand', 'battlefield', 'graveyard', 'top', 'bottom'].includes(destination)) {
fail(line, `unknown search destination "${destination}"`)
}
const splitIndex = args.findIndex(value => /^then /.test(value.trim()))
let split: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean } | undefined
if (splitIndex >= 0) {
const splitText = args[splitIndex].trim().replace(/^then /, '')
const splitTapped = / tapped$/.test(splitText)
const splitDestination = splitText.replace(/ tapped$/, '')
if (!['hand', 'battlefield', 'graveyard', 'top', 'bottom'].includes(splitDestination)) {
fail(line, `unknown search destination "${splitDestination}"`)
}
split = {
destination: splitDestination as 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom',
tapped: splitTapped,
}
}
const before = args.slice(1, destinationIndex)
const amountText = before[before.length - 1]
if (amountText === undefined) fail(line, 'search needs an amount')
@@ -914,6 +938,7 @@ function parseEffectExpr(text: string, line: SourceLine): Effect {
destination: destination as 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom',
tapped: args.includes('tapped'),
shuffle: args.includes('shuffle'),
...(split ? { split } : {}),
...(args.includes('library+graveyard') ? { zones: ['library', 'graveyard'] as ('library' | 'graveyard')[] } : {}),
}
}
@@ -1164,6 +1189,7 @@ function parseConditionText(text: string, line: SourceLine): Condition {
return { kind: 'cast_spell_this_turn', noncreature: true }
}
if (trimmed === 'you have a full party') return { kind: 'full_party' }
if (trimmed === 'you control a commander') return { kind: 'you_control_commander' }
if (trimmed === 'no spells were cast last turn') return { kind: 'no_spells_last_turn' }
if (trimmed === 'no creatures attacked this turn') return { kind: 'no_attackers' }
if (trimmed === "tribute wasn't paid") return { kind: 'tribute_not_paid' }
@@ -1188,8 +1214,17 @@ function parseConditionText(text: string, line: SourceLine): Condition {
if (trimmed === 'otherwise') return { kind: 'otherwise' }
if (trimmed === 'defending player controls') return fail(line, 'missing defending-player selector')
let match = trimmed.match(/^you control (\d+)\+ creatures with different powers$/)
let match = trimmed.match(/^an opponent was dealt (\d+)\+ damage this turn$/)
if (match) return { kind: 'opponent_damaged_this_turn', atLeast: Number(match[1]) }
match = trimmed.match(/^you attacked with (\d+)\+ creatures this turn$/)
if (match) return { kind: 'attacked_with_creatures', atLeast: Number(match[1]) }
match = trimmed.match(/^a library has (\d+) or fewer cards in it$/)
if (match) return { kind: 'library_at_most', atMost: Number(match[1]) }
match = trimmed.match(/^you control (\d+)\+ creatures with different powers$/)
if (match) return { kind: 'distinct_powers', atLeast: Number(match[1]) }
match = trimmed.match(/^you control (\d+)\+ (.+?) with different names$/)
if (match) return { kind: 'distinct_names', selector: parseSelector(match[2], line), atLeast: Number(match[1]) }
match = trimmed.match(/^you control a creature with (power|toughness) greater than its base (?:power|toughness)$/)
if (match) {
return { kind: 'creature_power_greater_than_base', controller: 'you', stat: match[1] as 'power' | 'toughness' }
@@ -1572,13 +1607,39 @@ function parseStaticEffect(text: string, line: SourceLine): StaticEffect {
}
case 'cost_reduction': {
const rest = args[2]?.trim()
const value = arg(args, 1, line).trim()
return {
op: 'cost_reduction',
target: parseTarget(arg(args, 0, line), line),
amount: parseValueText(arg(args, 1, line), line),
...(/^(?:\{[^}]+\})+$/.test(value)
? { symbols: value }
: { amount: parseValueText(value, line) }),
...(rest?.startsWith('if ') ? { condition: parseConditionText(rest.slice(3), line) } : {}),
}
}
case 'cost_increase': {
const spellType = args[1]?.trim()
if (spellType && spellType !== 'noncreature' && spellType !== 'creature') {
fail(line, `unknown spell type "${spellType}"`)
}
return {
op: 'cost_increase',
amount: parseValueText(arg(args, 0, line), line),
...(spellType ? { spellType: spellType as 'noncreature' | 'creature' } : {}),
}
}
case 'search_restriction': {
const who = arg(args, 0, line)
if (who !== 'opponent' && who !== 'you') fail(line, `unknown search restriction player "${who}"`)
return { op: 'search_restriction', who, amount: parseValueText(arg(args, 1, line), line) }
}
case 'exile_instead_of_graveyard': {
const owner = args[0]?.trim()
if (owner && owner !== 'opponent' && owner !== 'you') {
fail(line, `unknown replacement owner "${owner}"`)
}
return { op: 'exile_instead_of_graveyard', ...(owner ? { owner: owner as 'opponent' | 'you' } : {}) }
}
case 'unsupported':
return fail(line, 'unsupported is an ability, not a static effect')
default:
@@ -1643,6 +1704,20 @@ function parseAbilityBlock(block: Block): Ability {
return { kind: 'additional_cost', costs: parseCosts(costsText, block.header), optional: Boolean(match[1]), text: header }
}
match = header.match(/^alternative cost(?: if (.+?))?: ?(.*)$/)
if (match) {
const costsText = match[2].trim()
return {
kind: 'alternative_cost',
costs: costsText === 'free' ? [] : parseCosts(costsText, block.header),
...(match[1] ? { condition: parseConditionText(match[1], block.header) } : {}),
text: header,
}
}
match = header.match(/^overload ((?:\{[^}]+\})+)$/)
if (match) return { kind: 'overload', cost: match[1], text: header }
if (!header.endsWith(':')) fail(block.header, `expected an ability block, got "${header}"`)
let rest = header.slice(0, -1)

View File

@@ -137,7 +137,7 @@ Static effects:
control(target)
choose(creature_type|color|card_name|player|opponent|number)
replace(dies|leaves_battlefield|discard|draw[, target], instead exile|return_to_hand|return_to_library|prevent)
cost_reduction(target, amount[, if <condition>])
cost_reduction(target, amount|{R}{G}[, if <condition>])
Common conditions: you control <selector>, you control at least N <selector>,
an opponent controls <selector>, it is your turn, it isn't your turn,

View File

@@ -3,6 +3,8 @@
export type Zone = 'battlefield' | 'hand' | 'graveyard' | 'library' | 'exile' | 'stack' | 'command'
export type SearchDestination = 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'
export type PlayerRef =
| 'you'
| 'opponent'
@@ -184,6 +186,11 @@ export type Condition =
| { kind: 'if_you_do' }
| { kind: 'if_you_dont' }
| { kind: 'otherwise' }
| { kind: 'you_control_commander' }
| { kind: 'distinct_names'; selector: ObjectSelector; atLeast: number }
| { kind: 'opponent_damaged_this_turn'; atLeast: number }
| { kind: 'attacked_with_creatures'; atLeast: number }
| { kind: 'library_at_most'; atMost: number }
export type TriggerEvent =
| { kind: 'enters'; subject: Target }
@@ -230,7 +237,7 @@ export type Effect =
| { op: 'untap'; target: Target }
| { op: 'scry'; player: PlayerRef; amount: Value }
| { op: 'surveil'; player: PlayerRef; amount: Value }
| { op: 'search'; player: PlayerRef; selector: ObjectSelector; amount: Value; destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean; shuffle: boolean; zones?: ('library' | 'graveyard')[] }
| { op: 'search'; player: PlayerRef; selector: ObjectSelector; amount: Value; destination: SearchDestination; tapped: boolean; shuffle: boolean; zones?: ('library' | 'graveyard')[]; split?: { destination: SearchDestination; tapped: boolean } }
| { op: 'shuffle'; player: PlayerRef }
| { op: 'add_mana'; player: PlayerRef; mana: ManaSpec }
| { op: 'fight'; a: Target; b: Target }
@@ -252,6 +259,9 @@ export type Effect =
| { op: 'put_from_among'; player: PlayerRef; selector?: ObjectSelector; amount: Value; destination: 'hand' | 'graveyard' | 'battlefield' | 'top' | 'bottom' }
| { op: 'dig'; player: PlayerRef; amount: Value; pick: Value; upTo?: boolean; pickSelector?: ObjectSelector; to: 'hand' | 'battlefield'; rest: 'bottom' | 'graveyard' | 'top'; order?: 'any' | 'random'; optional?: boolean; tapped?: boolean }
| { op: 'damage_divided'; amount: Value; target: Target }
| { op: 'exile_graveyards' }
| { op: 'hideaway'; amount: Value }
| { op: 'play_exiled'; player: PlayerRef; free?: boolean }
export type StaticEffect =
| { op: 'pump'; target: Target; power: Value; toughness: Value }
@@ -264,7 +274,10 @@ export type StaticEffect =
| { op: 'control'; target: Target }
| { op: 'choose'; what: 'creature_type' | 'color' | 'card_name' | 'player' | 'opponent' | 'number' }
| { op: 'replacement'; what: 'dies' | 'leaves_battlefield' | 'discard' | 'draw'; instead: 'exile' | 'return_to_hand' | 'return_to_library' | 'prevent'; target?: Target }
| { op: 'cost_reduction'; target: Target; amount: Value; condition?: Condition }
| { op: 'cost_reduction'; target: Target; amount?: Value; symbols?: string; condition?: Condition }
| { op: 'cost_increase'; amount: Value; spellType?: 'noncreature' | 'creature' }
| { op: 'search_restriction'; who: 'opponent' | 'you'; amount: Value }
| { op: 'exile_instead_of_graveyard'; owner?: 'opponent' | 'you' }
export type Ability =
| KeywordAbility
@@ -308,6 +321,17 @@ export type Ability =
optional: boolean
text: string
}
| {
kind: 'alternative_cost'
costs: Cost[]
condition?: Condition
text: string
}
| {
kind: 'overload'
cost: string
text: string
}
| {
kind: 'chapter'
chapters: string[]

View File

@@ -0,0 +1,45 @@
// Scryfall's creature-type catalog (api.scryfall.com/catalog/creature-types).
// Update when a set introduces a new type.
export const CREATURE_TYPES = [
'Advisor', 'Aenar', 'Aetherborn', 'Alien', 'Ally', 'Andorian', 'Android', 'Angel', 'Antelope',
'Ape', 'Archer', 'Archon', 'Armadillo', 'Army', 'Artificer', 'Assassin', 'Assembly-Worker',
'Astartes', 'Atog', 'Aurochs', 'Automaton', 'Avatar', 'Azra', 'Badger', 'Bajoran', 'Balloon',
'Barbarian', 'Bard', 'Basilisk', 'Bat', 'Bear', 'Beast', 'Beaver', 'Beeble', 'Beholder',
'Berserker', 'Betazoid', 'Bird', 'Bison', 'Blinkmoth', 'Boar', 'Borg', 'Brainiac', 'Bringer',
'Brushwagg', "C'tan", 'Caitian', 'Camarid', 'Camel', 'Capybara', 'Cardassian', 'Caribou',
'Carrier', 'Cat', 'Centaur', 'Chicken', 'Child', 'Chimera', 'Citizen', 'Cleric', 'Clown',
'Cockatrice', 'Construct', 'Coward', 'Coyote', 'Crab', 'Crocodile', 'Custodes', 'Cyberman',
'Cyclops', 'Dalek', 'Dauthi', 'Demigod', 'Demon', 'Denobulan', 'Deserter', 'Detective', 'Devil',
'Dinosaur', 'Djinn', 'Doctor', 'Dog', 'Dragon', 'Drake', 'Dreadnought', 'Drix', 'Drone', 'Druid',
'Dryad', 'Dwarf', 'Echidna', 'Efreet', 'Egg', 'El-Aurian', 'Elder', 'Eldrazi', 'Elemental',
'Elephant', 'Elf', 'Elk', 'Employee', 'Eternal', 'Excalbian', 'Eye', 'Faerie', 'Ferengi',
'Ferret', 'Fish', 'Flagbearer', 'Fox', 'Fractal', 'Frog', 'Fungus', 'Gamer', 'Gamma', 'Gargoyle',
'Germ', 'Giant', 'Giraffe', 'Gith', 'Glimmer', 'Gnoll', 'Gnome', 'Goat', 'Goblin', 'God',
'Golem', 'Gorgon', 'Gorn', 'Graveborn', 'Gremlin', 'Griffin', 'Guest', 'Hag', 'Halfling',
'Hamster', 'Harpy', 'Head', 'Hedgehog', 'Hellion', 'Hero', 'Hippo', 'Hippogriff', 'Hirogen',
'Homarid', 'Homunculus', 'Horror', 'Horse', 'Human', 'Hydra', 'Hyena', 'Illusion', 'Illyrian',
'Imp', 'Incarnation', 'Inhuman', 'Inkling', 'Inquisitor', 'Insect', 'Jackal', 'Jellyfish',
'Juggernaut', 'Kangaroo', 'Kavu', 'Kelpien', 'Kirin', 'Kithkin', 'Klingon', 'Knight', 'Kobold',
'Kor', 'Kraken', 'Kree', 'Kwejian', 'Lamia', 'Lammasu', 'Lanthanite', 'Leech', 'Lemur',
'Leviathan', 'Lhurgoyf', 'Licid', 'Lizard', 'Llama', 'Lobster', 'Manticore', 'Masticore',
'Medusan', 'Mercenary', 'Merfolk', 'Metathran', 'Mindless-One', 'Minion', 'Minotaur', 'Mite',
'Mole', 'Monger', 'Mongoose', 'Monk', 'Monkey', 'Moogle', 'Moonfolk', 'Mount', 'Mouse', 'Mutant',
'Myr', 'Mystic', "Na'kuhl", 'Naga', 'Nautilus', 'Necron', 'Nephilim', 'Nightmare', 'Nightstalker',
'Ninja', 'Noble', 'Noggle', 'Nomad', 'Nymph', 'Octopus', 'Officer', 'Ogre', 'Ooze', 'Orb', 'Orc',
'Orgg', 'Orion', 'Otter', 'Ouphe', 'Ox', 'Oyster', 'Pangolin', 'Peasant', 'Pegasus', 'Pentavite',
'Performer', 'Pest', 'Phelddagrif', 'Phoenix', 'Phyrexian', 'Pilot', 'Pincher', 'Pirate',
'Plant', 'Platypus', 'Porcupine', 'Possum', 'Praetor', 'Primarch', 'Prism', 'Processor', 'Q',
'Qu', 'Rabbit', 'Raccoon', 'Ranger', 'Rat', 'Rebel', 'Reflection', 'Reveler', 'Rhino', 'Rigger',
'Robot', 'Rogue', 'Romulan', 'Rukh', 'Sable', 'Salamander', 'Samurai', 'Sand', 'Saproling',
'Satyr', 'Scarecrow', 'Scientist', 'Scion', 'Scorpion', 'Scout', 'Sculpture', 'Seal', 'Serf',
'Serpent', 'Servo', 'Shade', 'Shaman', 'Shapeshifter', 'Shark', 'Sheep', "Shi'ar", 'Siren',
'Skeleton', 'Skrull', 'Skunk', 'Slith', 'Sliver', 'Sloth', 'Slug', 'Snail', 'Snake', 'Soldier',
'Soltari', 'Sorcerer', 'Spawn', 'Specter', 'Spellshaper', 'Sphinx', 'Spider', 'Spike', 'Spirit',
'Splinter', 'Sponge', 'Spy', 'Squid', 'Squirrel', 'Starfish', 'Surrakar', 'Survivor', 'Symbiote',
'Synth', 'Talosian', 'Teddy', 'Tellarite', 'Tentacle', 'Tetravite', 'Thalakos', 'Tholian',
'Thopter', 'Thrull', 'Tiefling', 'Time Lord', 'Tosk', 'Toy', 'Treefolk', 'Tribble', 'Trill',
'Trilobite', 'Triskelavite', 'Troll', 'Turtle', 'Tyranid', 'Unicorn', 'Urzan', 'Utrom',
'Vampire', 'Varmint', 'Vedalken', 'Villain', 'Volver', 'Vorta', 'Vulcan', 'Wall', 'Walrus',
'Warlock', 'Warrior', 'Weasel', 'Weird', 'Werewolf', 'Whale', 'Wizard', 'Wolf', 'Wolverine',
'Wombat', 'Worm', 'Wraith', 'Wurm', 'Xindi', 'Yeti', 'Zombie', 'Zubera',
]

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')
}

View File

@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'
import { getCard, type Card } from '../cards.js'
import { deletePlaymatImage, PlaymatError, scryfallArtUrl, storePlaymatImage } from '../images.js'
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'
@@ -25,6 +26,8 @@ export interface ActionPayload {
targets?: TargetChoice[]
x?: number
mode?: number
overload?: boolean
choice?: string
position?: { x?: unknown; y?: unknown }
attackers?: { attackerId: string; defenderId: string }[]
blocks?: { blockerId: string; attackerId: string }[]
@@ -54,6 +57,8 @@ export interface CardView {
attacking?: string
blockedBy: string[]
blocking?: string
/** Creature type chosen as this permanent entered, if any. */
chosenType?: string
abilities: { index: number; kind: string; text?: string }[]
/** Viewer-specific: can this card be played from hand right now? */
playable?: boolean
@@ -115,6 +120,17 @@ export interface MatchView {
remaining: number
destination: string
cards: CardView[]
/** Every card in the searched zones, populated only for its chooser. */
library?: CardView[]
}
/** Present while an "as this enters, choose..." prompt waits for its controller. */
pendingChoice?: {
player: string
what: string
sourceId: string
sourceName: string
/** Choices to offer, populated only for the chooser. */
options: string[]
}
}
}
@@ -403,6 +419,7 @@ export function performAction(matchId: string, token: string | undefined, action
targets,
x: Number.isFinite(action.x) ? Number(action.x) : 0,
mode: Number.isFinite(action.mode) ? Number(action.mode) : 0,
overload: action.overload === true,
}
try {
@@ -425,6 +442,10 @@ export function performAction(matchId: string, token: string | undefined, action
case 'choose_search':
game.chooseSearchCard(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)
break
case 'attack':
if (!Array.isArray(action.attackers)) throw new MatchError('Invalid attackers')
game.declareAttackers(seat.playerId, action.attackers.map(entry => ({
@@ -490,6 +511,7 @@ function cardView(game: Game, object: GameObject, abilities = true): CardView {
attacking: object.attacking,
blockedBy: [...object.blockedBy],
blocking: object.blocking,
chosenType: object.chosenCreatureType,
abilities: abilities
? (definition.abilities ?? []).map((ability, index) => ({
index,
@@ -548,6 +570,7 @@ function serialize(match: Match, viewerId: string): MatchView {
const viewer = game.getPlayer(viewerId)
const search = game.pendingSearch
const choice = game.pendingChoice
view.game = {
turn: game.turn,
activePlayer: game.activePlayer,
@@ -568,6 +591,15 @@ function serialize(match: Match, viewerId: string): MatchView {
playable: game.canPlayCard(viewerId, id),
})),
manaPool: { ...viewer.manaPool },
pendingChoice: choice
? {
player: choice.playerId,
what: choice.what,
sourceId: choice.sourceId,
sourceName: game.objects.get(choice.sourceId)?.definition.name ?? 'Permanent',
options: choice.playerId === viewerId ? [...CREATURE_TYPES] : [],
}
: undefined,
pendingSearch: search
? {
player: search.playerId,
@@ -576,6 +608,9 @@ function serialize(match: Match, viewerId: string): MatchView {
cards: search.playerId === viewerId
? game.searchCandidates(viewerId).map(object => cardView(game, object, false))
: [],
...(search.playerId === viewerId
? { library: game.searchPool(viewerId).map(object => cardView(game, object, false)) }
: {}),
}
: undefined,
}

View File

@@ -64,6 +64,8 @@ export interface PlayerState {
creaturesDiedThisTurn: number
nonlandPermanentsEnteredThisTurn: number
attackedThisTurn: boolean
creaturesAttackedThisTurn: number
damageTakenThisTurn: number
energy: number
poison: number
}
@@ -90,6 +92,10 @@ export interface GameObject {
blocking?: string
attachments: string[]
attachedTo?: string
/** Cards exiled with this object, such as a card hidden by hideaway. */
linkedExile?: string[]
/** Creature type chosen as this permanent entered (Cavern of Souls). */
chosenCreatureType?: string
regenerationShields: number
activations: Record<number, number>
}
@@ -118,6 +124,7 @@ export interface ActionOptions {
targets?: TargetChoice[]
x?: number
mode?: number
overload?: boolean
}
/** A search that is waiting for its player to pick one of several matching cards. */
@@ -129,6 +136,15 @@ export interface PendingSearch {
tapped: boolean
shuffle: boolean
zones?: ('library' | 'graveyard')[]
/** Where the picks after the first one go (Cultivate-style searches). */
split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean }
}
/** An "as this enters, choose..." pause. Blocks all actions until its controller picks. */
export interface PendingChoice {
playerId: string
sourceId: string
what: 'creature_type'
}
export interface CombatAttack {