kjdskjdsk
This commit is contained in:
@@ -165,6 +165,8 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities:
|
||||
| `activated` | Cost `:` effect, including loyalty | `{T}: Add {G}.` |
|
||||
| `static` | Continuous effect or restriction | `Creatures you control get +1/+1.` |
|
||||
| `spell` | Effect line of an instant or sorcery | `Draw two cards.` |
|
||||
| `alternative_cost` | Alternative cast with a condition, possibly free | `If you control a commander, you may cast this without paying its mana cost.` |
|
||||
| `overload` | Overload alternate cost; the engine widens the spell's targets | `Overload {6}{U}` |
|
||||
| `unsupported` | Preserved text plus a reason | `Choose one —` |
|
||||
|
||||
### Effects
|
||||
@@ -182,7 +184,7 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities:
|
||||
| `sacrifice` | `player`, `target`, optional `unless` cost |
|
||||
| `counter` | `what`, `target`, optional `unless` cost |
|
||||
| `return_to_hand`, `return_to_battlefield`, `put_on_top` | `target` |
|
||||
| `search`, `shuffle` | player, selector, destination |
|
||||
| `search`, `shuffle` | player, selector, destination, optional `split` destination |
|
||||
| `add_mana` | `player`, `mana` (`symbols` or `any_color`) |
|
||||
| `scry`, `surveil` | `player`, `amount` |
|
||||
| `fight` | two targets |
|
||||
@@ -191,6 +193,9 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities:
|
||||
| `restriction` | target, rule, duration |
|
||||
| `keyword_action` | `action`, optional `amount`, `detail`, `target` |
|
||||
| `proliferate` | no payload |
|
||||
| `hideaway` | `amount`; exiles the top card and links it to the source |
|
||||
| `play_exiled` | `player`, optional `free`; plays a card linked with `hideaway` |
|
||||
| `exile_graveyards` | no payload; exiles all cards from every graveyard |
|
||||
|
||||
### Targets, values, costs
|
||||
|
||||
@@ -202,8 +207,12 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities:
|
||||
`source_toughness`, `cards_in_hand`, or `event_amount`.
|
||||
- **Costs** are mana symbols, tap/untap, tapping another permanent, energy,
|
||||
loyalty, life, discard, sacrifice, self-exile, mill, and removing counters.
|
||||
- **Conditions** cover controlling permanents, turn ownership, tapped source,
|
||||
life totals, and graveyard size.
|
||||
- **Conditions** cover controlling permanents, commander control, turn ownership,
|
||||
tapped source, life totals, graveyard/hand/library size, total power, distinct
|
||||
permanent names, and this-turn attacks and damage.
|
||||
- **Static effects** include pumps, keyword grants, restrictions, enters
|
||||
tapped/with counters, control, choices, replacements, cost reduction/increase,
|
||||
search restriction, and exiling cards instead of putting them into graveyards.
|
||||
- **Durations** cover permanent, end of turn, your next turn, the end of your
|
||||
next turn, end of combat, controller's next untap step, and while the source
|
||||
remains.
|
||||
|
||||
@@ -58,7 +58,7 @@ const bolt: CardDefinition = {
|
||||
| ------ | ------- |
|
||||
| `start()` | Shuffles libraries, draws opening hands, begins turn 1. |
|
||||
| `playLand(playerId, cardId)` | Plays a land from hand; once per turn, main phase, empty stack. |
|
||||
| `castSpell(playerId, cardId, { targets, x, mode })` | Puts a spell on the stack and pays its mana cost. Accepts a commander in the command zone and adds commander tax. |
|
||||
| `castSpell(playerId, cardId, { targets, x, mode, overload })` | Puts a spell on the stack and pays its mana cost. Accepts a commander in the command zone, adds commander tax, and can pay the overload cost instead. |
|
||||
| `activateAbility(playerId, sourceId, abilityIndex, { targets, x, mode })` | Activates an ability on a permanent. Mana abilities resolve immediately. |
|
||||
| `movePermanent(playerId, cardId, x, y)` | Cosmetic board layout for a permanent you control; coordinates are 0..1 within the battlefield. |
|
||||
| `declareAttackers(playerId, [{ attackerId, defenderId }])` | Starts combat from the precombat main if needed. |
|
||||
@@ -66,6 +66,7 @@ const bolt: CardDefinition = {
|
||||
| `resolveCombatDamage()` | Deals combat damage manually; passing priority also does this. |
|
||||
| `pass(playerId?)` | Passes priority; when everyone passes, resolves the top of the stack or advances the phase. |
|
||||
| `chooseSearchCard(playerId, cardId)` | Finishes one pick of a paused library search. |
|
||||
| `chooseCreatureType(playerId, type)` | Answers an "as this enters, choose a creature type" prompt. |
|
||||
| `resolveStack()` | Convenience for tests/scripts: passes priority until the stack is empty. Does not advance phases. |
|
||||
| `endTurn(playerId)` | Ends the active player's turn, skipping remaining phases. Requires an empty stack. |
|
||||
| `canPlayCard(playerId, cardId)` | Whether a hand or command-zone card can legally be played now, including timing, mana, and targets. |
|
||||
@@ -78,7 +79,13 @@ non-flash spells can only be cast in the active player's main phase with an empt
|
||||
stack. Targets may be supplied explicitly; if omitted, the first legal target is
|
||||
chosen automatically, which keeps scripted games short. A search effect that matches
|
||||
several cards pauses instead: other actions are refused until its controller calls
|
||||
`chooseSearchCard` (the match API uses the `choose_search` action).
|
||||
`chooseSearchCard` (the match API uses the `choose_search` action). The match API also
|
||||
sends the chooser the full searched pool (`searchPool`) so the UI can show and filter
|
||||
the library; only `searchCandidates` are legal picks. A permanent with "as this enters,
|
||||
choose a creature type" also pauses play: `pendingChoice` records the controller and
|
||||
the permanent, and the match API refuses other priority actions until `chooseCreatureType`
|
||||
(the `choose_type` action) receives one of the creature types in `CREATURE_TYPES`.
|
||||
The chosen type is stored on the object and cleared when it leaves the battlefield.
|
||||
|
||||
## Turn structure
|
||||
|
||||
@@ -100,20 +107,27 @@ shown to players who can actually do something.
|
||||
- Zones: library, hand, battlefield, graveyard, exile, stack, and command zone. Tokens
|
||||
cease to exist when they leave the battlefield.
|
||||
- Commander: command-zone casting, `{2}` tax per previous cast from the command
|
||||
zone, return to the command zone instead of graveyard/exile/hand/library, and a
|
||||
loss at 21 combat damage from one commander. Deck construction is validated by
|
||||
`validateCommanderDeck`.
|
||||
zone, free alternative costs while you control a commander, return to the command
|
||||
zone instead of graveyard/exile/hand/library, and a loss at 21 combat damage from
|
||||
one commander. Deck construction is validated by `validateCommanderDeck`.
|
||||
- Mana: colored, generic, hybrid, Phyrexian, `{X}`, and `{S}` costs; manual mana
|
||||
abilities plus automatic tapping of untapped mana sources when paying.
|
||||
- Costs: tap, untap, tap another permanent, pay life, discard, sacrifice, exile,
|
||||
putting/removing counters, mill, energy, and choice costs.
|
||||
- Abilities: spell effects, activated abilities, triggered abilities (enters,
|
||||
leaves, dies, attacks, blocks, cast, draw, life, upkeep, end step, combat), static
|
||||
effects, and basic replacement effects for entering tapped/with counters.
|
||||
putting/removing counters, mill, energy, and choice costs. Static cost reductions
|
||||
and increases apply while their source is on the battlefield.
|
||||
- Abilities: spell effects, overload, activated abilities, triggered abilities
|
||||
(enters, leaves, dies, attacks, blocks, cast, draw, life, upkeep, end step,
|
||||
combat), static effects, and basic replacement effects for entering tapped/with
|
||||
counters and exiling cards instead of putting them into graveyards.
|
||||
- Effects: damage, draw, discard, mill, life, pump/set P/T, grant keyword,
|
||||
counters, proliferate, tokens, destroy, exile, sacrifice, counter spell/ability,
|
||||
zone returns, tap/untap, search/shuffle, add mana, fight, regenerate, energy,
|
||||
attach, restrictions, conditional and modal effects, dig, and divided damage.
|
||||
counters, proliferate, tokens, destroy, exile, exile all graveyards, sacrifice,
|
||||
counter spell/ability, zone returns, tap/untap, search/shuffle, add mana, fight,
|
||||
regenerate, energy, attach, restrictions, conditional and modal effects, dig,
|
||||
divided damage, hideaway, and playing a card exiled with hideaway.
|
||||
- Restrictions and conditions: activated abilities can be disabled, opponents can
|
||||
be limited to the top N cards when searching, cards can begin the game on the
|
||||
battlefield from the opening hand, and conditions can count commander control or
|
||||
distinct permanent names.
|
||||
- Combat keywords: flying, reach, first strike, double strike, trample, deathtouch,
|
||||
lifelink, vigilance, haste, indestructible. Regeneration shields replace
|
||||
destruction.
|
||||
@@ -136,6 +150,16 @@ shown to players who can actually do something.
|
||||
- Modal spells choose a mode by index (`options.mode`); optional "you may" choices
|
||||
are not modelled. An optional `pay` is simply not paid when unaffordable. Search
|
||||
effects with several matching cards do pause for the player's pick.
|
||||
- "As this enters, choose a creature type" pauses for a pick and stores the type on
|
||||
the permanent, but no effect reads the chosen type yet. The other `choose` kinds
|
||||
(color, card name, player, opponent, number) are accepted and ignored. Cavern of
|
||||
Souls' mana is not restricted to the chosen type and does not make the spell
|
||||
uncounterable.
|
||||
- Hideaway automatically exiles the top card and does not track cards as face down.
|
||||
`play_exiled` only supports the free "without paying its mana cost" case.
|
||||
- Overload widens only top-level effect targets; a nested modal or conditional target
|
||||
keeps its printed target. Free alternative costs are modelled only for controlling
|
||||
a commander, and search restrictions cap the searching player's own library.
|
||||
- Opening hands are kept automatically; there is no mulligan flow.
|
||||
- Replacement/prevention effects, layers, and dependency ordering are simplified.
|
||||
Continuous effects apply in creation order rather than in full rules order.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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'))
|
||||
|
||||
@@ -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': {
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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[]
|
||||
|
||||
45
backend/src/game/creature-types.ts
Normal file
45
backend/src/game/creature-types.ts
Normal 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',
|
||||
]
|
||||
@@ -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')
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -56,6 +56,62 @@ test('search effect keeps destination, tapped, and shuffle', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('search can put the chosen card on top of the library', () => {
|
||||
const [ability] = spell('Search your library for a creature card, reveal it, then shuffle and put the card on top.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['creature'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'top',
|
||||
tapped: false,
|
||||
shuffle: true,
|
||||
})
|
||||
})
|
||||
|
||||
test('a two-card search can split between the battlefield and hand', () => {
|
||||
const [ability] = spell('Search your library for up to two basic land cards, reveal those cards, put one onto the battlefield tapped and the other into your hand, then shuffle.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'], supertypes: ['basic'] },
|
||||
amount: { kind: 'number', value: 2 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
split: { destination: 'hand', tapped: false },
|
||||
})
|
||||
})
|
||||
|
||||
test('"if you search your library this way, shuffle" keeps the search', () => {
|
||||
const [ability] = spell('Search your library for a card named Sol Ring, reveal it, and put it into your hand. If you search your library this way, shuffle.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { name: 'sol ring', types: [] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'hand',
|
||||
tapped: false,
|
||||
shuffle: true,
|
||||
})
|
||||
})
|
||||
|
||||
test('search selectors support an exact mana value', () => {
|
||||
const [ability] = spell('Search your library for an artifact card with mana value 3, reveal it, put it into your hand, then shuffle.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
const effect = ability.effects[0]
|
||||
assert.equal(effect.op, 'search')
|
||||
if (effect.op !== 'search') return
|
||||
assert.deepEqual(effect.selector, { types: ['artifact'], manaValue: { atLeast: 3, atMost: 3 } })
|
||||
})
|
||||
|
||||
test('"it" refers to the triggering object when unambiguous', () => {
|
||||
const [ability] = creature('Whenever another creature enters, put a +1/+1 counter on it.')
|
||||
assert.equal(ability.kind, 'triggered')
|
||||
@@ -283,6 +339,53 @@ test('counter-removal costs parse and round-trip through pseudocode', () => {
|
||||
}])
|
||||
})
|
||||
|
||||
test('hideaway lands exile a card and gate playing it on their condition', () => {
|
||||
const lands: Array<[string, string, string]> = [
|
||||
["Clive's Hideaway", `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
{T}: Add {C}.
|
||||
{2}, {T}: You may play the exiled card without paying its mana cost if you control four or more legendary creatures.`, 'you_control'],
|
||||
['Howltooth Hollow', `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
This land enters tapped.
|
||||
{T}: Add {B}.
|
||||
{B}, {T}: You may play the exiled card without paying its mana cost if each player has no cards in hand.`, 'cards_in_hand_at_most'],
|
||||
['Mosswort Bridge', `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
This land enters tapped.
|
||||
{T}: Add {G}.
|
||||
{G}, {T}: You may play the exiled card without paying its mana cost if creatures you control have total power 10 or greater.`, 'total_power'],
|
||||
['Shelldock Isle', `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
This land enters tapped.
|
||||
{T}: Add {U}.
|
||||
{U}, {T}: You may play the exiled card without paying its mana cost if a library has twenty or fewer cards in it.`, 'library_at_most'],
|
||||
['Spinerock Knoll', `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
This land enters tapped.
|
||||
{T}: Add {R}.
|
||||
{R}, {T}: You may play the exiled card without paying its mana cost if an opponent was dealt 7 or more damage this turn.`, 'opponent_damaged_this_turn'],
|
||||
['Windbrisk Heights', `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
This land enters tapped.
|
||||
{T}: Add {W}.
|
||||
{W}, {T}: You may play the exiled card without paying its mana cost if you attacked with three or more creatures this turn.`, 'attacked_with_creatures'],
|
||||
]
|
||||
|
||||
for (const [name, text, condition] of lands) {
|
||||
const abilities = compileText(text, name, [], 'Land')
|
||||
assert.equal(abilities.filter(ability => ability.kind === 'unsupported').length, 0, name)
|
||||
|
||||
const hideaway = abilities.find(ability => ability.kind === 'triggered' && ability.effects.some(effect => effect.op === 'hideaway'))
|
||||
assert.equal(hideaway?.kind, 'triggered', name)
|
||||
if (hideaway?.kind !== 'triggered') continue
|
||||
assert.deepEqual(hideaway.effects, [{ op: 'hideaway', amount: { kind: 'number', value: 4 } }], name)
|
||||
|
||||
const activated = abilities.at(-1)
|
||||
assert.equal(activated?.kind, 'activated', name)
|
||||
if (activated?.kind !== 'activated') continue
|
||||
const [effect] = activated.effects
|
||||
assert.equal(effect.op, 'conditional', name)
|
||||
if (effect.op !== 'conditional') continue
|
||||
assert.equal(effect.condition.kind, condition, name)
|
||||
assert.deepEqual(effect.effects, [{ op: 'play_exiled', player: 'you', free: true }], name)
|
||||
}
|
||||
})
|
||||
|
||||
test('a trigger returns its own card from the graveyard', () => {
|
||||
const [ability] = creature('When this dies, return this from your graveyard to the battlefield with a finality counter on it.')
|
||||
assert.equal(ability.kind, 'triggered')
|
||||
@@ -295,3 +398,152 @@ test('a trigger returns its own card from the graveyard', () => {
|
||||
counters: { counter: 'finality', amount: { kind: 'number', value: 1 } },
|
||||
}])
|
||||
})
|
||||
|
||||
test('Commander-batch oracle lines compile to dedicated nodes', () => {
|
||||
const [free] = spell('If you control a commander, you may cast this without paying its mana cost.')
|
||||
assert.equal(free.kind, 'alternative_cost')
|
||||
if (free.kind !== 'alternative_cost') return
|
||||
assert.deepEqual(free.condition, { kind: 'you_control_commander' })
|
||||
assert.deepEqual(free.costs, [])
|
||||
|
||||
const [overload] = spell('Overload {6}{U}')
|
||||
assert.deepEqual(overload, { kind: 'overload', cost: '{6}{U}', text: 'Overload {6}{U}' })
|
||||
|
||||
const [graves] = creature('When this enters, exile all graveyards.')
|
||||
assert.equal(graves.kind, 'triggered')
|
||||
if (graves.kind !== 'triggered') return
|
||||
assert.deepEqual(graves.effects, [{ op: 'exile_graveyards' }])
|
||||
|
||||
const [rest] = creature('If a card or token would be put into a graveyard from anywhere, exile it instead.')
|
||||
assert.equal(rest.kind, 'static')
|
||||
if (rest.kind !== 'static') return
|
||||
assert.deepEqual(rest.effects, [{ op: 'exile_instead_of_graveyard' }])
|
||||
|
||||
const [leyline] = creature("If a card would be put into an opponent's graveyard from anywhere, exile it instead.")
|
||||
assert.equal(leyline.kind, 'static')
|
||||
if (leyline.kind !== 'static') return
|
||||
assert.deepEqual(leyline.effects, [{ op: 'exile_instead_of_graveyard', owner: 'opponent' }])
|
||||
|
||||
const [thalia] = creature('Noncreature spells cost {1} more to cast.')
|
||||
assert.equal(thalia.kind, 'static')
|
||||
if (thalia.kind !== 'static') return
|
||||
assert.deepEqual(thalia.effects, [{
|
||||
op: 'cost_increase',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
spellType: 'noncreature',
|
||||
}])
|
||||
|
||||
const [linvala] = creature("Activated abilities of creatures your opponents control can't be activated.")
|
||||
assert.equal(linvala.kind, 'static')
|
||||
if (linvala.kind !== 'static') return
|
||||
assert.deepEqual(linvala.effects, [{
|
||||
op: 'restriction',
|
||||
target: { kind: 'object', selector: { controller: 'opponent', types: ['creature'] }, mode: 'each' },
|
||||
rule: 'cant_activate',
|
||||
}])
|
||||
|
||||
const [aven] = creature('If an opponent would search a library, that player searches the top four cards of that library instead.')
|
||||
assert.equal(aven.kind, 'static')
|
||||
if (aven.kind !== 'static') return
|
||||
assert.deepEqual(aven.effects, [{
|
||||
op: 'search_restriction',
|
||||
who: 'opponent',
|
||||
amount: { kind: 'number', value: 4 },
|
||||
}])
|
||||
|
||||
const [field] = compileText(
|
||||
'Whenever this or another land you control enters, if you control seven or more lands with different names, create a 2/2 black Zombie creature token.',
|
||||
'Field of the Dead',
|
||||
[],
|
||||
'Land',
|
||||
)
|
||||
assert.equal(field.kind, 'triggered')
|
||||
if (field.kind !== 'triggered') return
|
||||
assert.deepEqual(field.condition, {
|
||||
kind: 'distinct_names',
|
||||
selector: { types: ['land'] },
|
||||
atLeast: 7,
|
||||
})
|
||||
})
|
||||
|
||||
test('spell cost reductions compile their conditions and mana symbols', () => {
|
||||
const [bears] = creature('Creature spells you cast cost {1} less to cast.')
|
||||
assert.equal(bears.kind, 'static')
|
||||
if (bears.kind !== 'static') return
|
||||
assert.deepEqual(bears.effects, [{
|
||||
op: 'cost_reduction',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { controller: 'you', types: ['creature'] },
|
||||
mode: 'each',
|
||||
},
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}])
|
||||
|
||||
const [cantrips] = creature('Instant and sorcery spells cost {2} less to cast.')
|
||||
assert.equal(cantrips.kind, 'static')
|
||||
if (cantrips.kind !== 'static') return
|
||||
assert.deepEqual(cantrips.effects, [{
|
||||
op: 'cost_reduction',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { match: 'any', types: ['instant', 'sorcery'] },
|
||||
mode: 'each',
|
||||
},
|
||||
amount: { kind: 'number', value: 2 },
|
||||
}])
|
||||
|
||||
const [legendary] = creature('Legendary spells you cast cost {R}{G} less to cast. This effect reduces only the amount of colored mana you pay.')
|
||||
assert.equal(legendary.kind, 'static')
|
||||
if (legendary.kind !== 'static') return
|
||||
assert.deepEqual(legendary.effects, [{
|
||||
op: 'cost_reduction',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { controller: 'you', supertypes: ['legendary'], types: [] },
|
||||
mode: 'each',
|
||||
},
|
||||
symbols: '{R}{G}',
|
||||
}])
|
||||
|
||||
const [tribal] = creature("Each spell you cast that's a Demon, Horror, or Nightmare costs {1} less to cast.")
|
||||
assert.equal(tribal.kind, 'static')
|
||||
if (tribal.kind !== 'static') return
|
||||
assert.deepEqual(tribal.effects, [{
|
||||
op: 'cost_reduction',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { controller: 'you', match: 'any', subtypes: ['demon', 'horror', 'nightmare'], types: [] },
|
||||
mode: 'each',
|
||||
},
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}])
|
||||
})
|
||||
|
||||
test('new abilities, effects and conditions round-trip through pseudocode', () => {
|
||||
const abilities: Ability[] = [
|
||||
...spell('If you control a commander, you may cast this without paying its mana cost.'),
|
||||
...spell('Overload {6}{U}'),
|
||||
...creature('When this enters, exile all graveyards.'),
|
||||
...creature('If a card or token would be put into a graveyard from anywhere, exile it instead.'),
|
||||
...creature("If a card would be put into an opponent's graveyard from anywhere, exile it instead."),
|
||||
...creature('Noncreature spells cost {1} more to cast.'),
|
||||
...creature('Creature spells you cast cost {1} less to cast.'),
|
||||
...creature('Legendary spells you cast cost {R}{G} less to cast.'),
|
||||
...creature("Each spell you cast that's a Demon, Horror, or Nightmare costs {1} less to cast."),
|
||||
...creature("Activated abilities of creatures your opponents control can't be activated."),
|
||||
...creature('If an opponent would search a library, that player searches the top four cards of that library instead.'),
|
||||
...compileText(
|
||||
'Whenever this or another land you control enters, if you control seven or more lands with different names, create a 2/2 black Zombie creature token.',
|
||||
'Field of the Dead',
|
||||
[],
|
||||
'Land',
|
||||
),
|
||||
]
|
||||
for (const ability of abilities) {
|
||||
const pseudo = formatAbility(ability)
|
||||
const reparsed = parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]
|
||||
assert.ok(reparsed)
|
||||
assert.equal(formatAbility(reparsed), pseudo)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -127,6 +127,104 @@ test('permanents can be repositioned by their controller and positions are clear
|
||||
assert.equal(bear.position, undefined)
|
||||
})
|
||||
|
||||
test('hideaway exiles a card and its linked ability plays it for free once the condition is met', () => {
|
||||
const hideawayLand = card('Hideaway Test', {
|
||||
typeLine: 'Land',
|
||||
abilities: [
|
||||
{
|
||||
kind: 'triggered',
|
||||
event: { kind: 'enters', subject: { kind: 'self' } },
|
||||
effects: [{ op: 'hideaway', amount: { kind: 'number', value: 4 } }],
|
||||
optional: false,
|
||||
text: 'Hideaway 4',
|
||||
},
|
||||
{
|
||||
kind: 'activated',
|
||||
costs: [],
|
||||
effects: [{
|
||||
op: 'conditional',
|
||||
condition: { kind: 'total_power', controller: 'you', atLeast: 10 },
|
||||
effects: [{ op: 'play_exiled', player: 'you', free: true }],
|
||||
}],
|
||||
optional: false,
|
||||
text: 'Play the exiled card without paying its mana cost if creatures you control have total power 10 or greater.',
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const hidden = game.addCard('p1', creature('Hidden Bear', 2, 2), 'library')
|
||||
const library = game.getPlayer('p1').library
|
||||
library.splice(library.indexOf(hidden.id), 1)
|
||||
library.unshift(hidden.id)
|
||||
const land = game.addCard('p1', hideawayLand, 'hand')
|
||||
|
||||
game.playLand('p1', land.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(hidden.zone, 'exile')
|
||||
assert.deepEqual(land.linkedExile, [hidden.id])
|
||||
|
||||
game.activateAbility('p1', land.id, 1)
|
||||
game.resolveStack()
|
||||
assert.equal(hidden.zone, 'exile')
|
||||
|
||||
game.addCard('p1', creature('Big Bear', 10, 10), 'battlefield')
|
||||
game.activateAbility('p1', land.id, 1)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(hidden.zone, 'battlefield')
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(hidden.id))
|
||||
})
|
||||
|
||||
test('playing a card hidden by hideaway uses the land drop', () => {
|
||||
const hideawayLand = card('Hideaway Land', {
|
||||
typeLine: 'Land',
|
||||
abilities: [
|
||||
{
|
||||
kind: 'triggered',
|
||||
event: { kind: 'enters', subject: { kind: 'self' } },
|
||||
effects: [{ op: 'hideaway', amount: { kind: 'number', value: 1 } }],
|
||||
optional: false,
|
||||
text: 'Hideaway 1',
|
||||
},
|
||||
{
|
||||
kind: 'activated',
|
||||
costs: [],
|
||||
effects: [{
|
||||
op: 'conditional',
|
||||
condition: { kind: 'total_power', controller: 'you', atLeast: 0 },
|
||||
effects: [{ op: 'play_exiled', player: 'you', free: true }],
|
||||
}],
|
||||
optional: false,
|
||||
text: 'Play the exiled card without paying its mana cost.',
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const hidden = game.addCard('p1', land('Island', 'U'), 'library')
|
||||
const library = game.getPlayer('p1').library
|
||||
library.splice(library.indexOf(hidden.id), 1)
|
||||
library.unshift(hidden.id)
|
||||
const source = game.addCard('p1', hideawayLand, 'hand')
|
||||
|
||||
game.playLand('p1', source.id)
|
||||
game.resolveStack()
|
||||
assert.equal(hidden.zone, 'exile')
|
||||
|
||||
game.getPlayer('p1').landPlayedThisTurn = true
|
||||
game.activateAbility('p1', source.id, 1)
|
||||
game.resolveStack()
|
||||
assert.equal(hidden.zone, 'exile')
|
||||
|
||||
game.getPlayer('p1').landPlayedThisTurn = false
|
||||
game.activateAbility('p1', source.id, 1)
|
||||
game.resolveStack()
|
||||
assert.equal(hidden.zone, 'battlefield')
|
||||
assert.equal(game.getPlayer('p1').landPlayedThisTurn, true)
|
||||
})
|
||||
|
||||
test('enters triggers from compiled card code fire and resolve through the stack', () => {
|
||||
const soulWarden = card('Soul Warden', {
|
||||
typeLine: 'Creature — Human Cleric',
|
||||
@@ -414,6 +512,69 @@ test('search effects let the player pick among multiple matching cards', () => {
|
||||
assert.ok(game.getPlayer('p1').library.includes(forestObject.id))
|
||||
})
|
||||
|
||||
test('as-enters creature type choices pause until the controller picks', () => {
|
||||
const cavern = card('Cavern of Souls', {
|
||||
typeLine: 'Land',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'choose', what: 'creature_type' }],
|
||||
text: 'As this enters, choose a creature type.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const object = game.addCard('p1', cavern, 'hand')
|
||||
game.playLand('p1', object.id)
|
||||
|
||||
assert.equal(game.pendingChoice?.sourceId, object.id)
|
||||
assert.equal(game.pendingChoice?.playerId, 'p1')
|
||||
assert.throws(() => game.pass('p1'), GameError)
|
||||
assert.throws(() => game.chooseCreatureType('p2', 'Elf'), GameError)
|
||||
assert.throws(() => game.chooseCreatureType('p1', 'Not A Type'), GameError)
|
||||
|
||||
game.chooseCreatureType('p1', 'elf')
|
||||
assert.equal(object.chosenCreatureType, 'Elf')
|
||||
assert.equal(game.pendingChoice, undefined)
|
||||
|
||||
game.moveToZone(object, 'graveyard')
|
||||
assert.equal(object.chosenCreatureType, undefined)
|
||||
game.moveToZone(object, 'battlefield', { silent: false })
|
||||
assert.equal(game.pendingChoice?.sourceId, object.id)
|
||||
})
|
||||
|
||||
test('a split search sends the first pick to the battlefield and the next to hand', () => {
|
||||
const forest = land('Forest', 'G')
|
||||
const island = land('Island', 'U')
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const forestObject = game.addCard('p1', forest, 'library')
|
||||
const islandObject = game.addCard('p1', island, 'library')
|
||||
const cultivate = game.addCard('p1', spell('Cultivate', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'], supertypes: ['basic'] },
|
||||
amount: { kind: 'number', value: 2 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
split: { destination: 'hand', tapped: false },
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', cultivate.id)
|
||||
game.resolveStack()
|
||||
|
||||
game.chooseSearchCard('p1', islandObject.id)
|
||||
assert.equal(game.pendingSearch?.destination, 'hand')
|
||||
game.chooseSearchCard('p1', forestObject.id)
|
||||
|
||||
assert.equal(game.pendingSearch, undefined)
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(islandObject.id))
|
||||
assert.equal(islandObject.tapped, true)
|
||||
assert.ok(game.getPlayer('p1').hand.includes(forestObject.id))
|
||||
})
|
||||
|
||||
test('autoAdvance stops instead of passing while a search needs a pick', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
@@ -645,3 +806,427 @@ test('counter-removal costs are paid and fail when counters run out', () => {
|
||||
assert.throws(() => game.activateAbility('p1', source.id, 0), GameError)
|
||||
assert.equal(source.counters.spore, 1)
|
||||
})
|
||||
|
||||
test('a free alternative cost needs a commander and skips the mana cost', () => {
|
||||
const maneuver = card('Flawless Maneuver', {
|
||||
typeLine: 'Instant',
|
||||
manaCost: '{2}{W}',
|
||||
manaValue: 3,
|
||||
abilities: [
|
||||
{
|
||||
kind: 'alternative_cost',
|
||||
costs: [],
|
||||
condition: { kind: 'you_control_commander' },
|
||||
text: 'If you control a commander, you may cast this spell without paying its mana cost.',
|
||||
},
|
||||
{
|
||||
kind: 'spell',
|
||||
effects: [{
|
||||
op: 'grant',
|
||||
target: { kind: 'object', selector: { controller: 'you', types: ['creature'] }, mode: 'each' },
|
||||
keyword: 'Indestructible',
|
||||
duration: 'until_end_of_turn',
|
||||
}],
|
||||
optional: false,
|
||||
text: 'Creatures you control gain indestructible until end of turn.',
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = new Game({
|
||||
seed: 1,
|
||||
startingHandSize: 0,
|
||||
commander: true,
|
||||
players: [
|
||||
{ id: 'p1', deck: [card('Filler')], commander: creature('Test Commander', 2, 2) },
|
||||
{ id: 'p2', deck: [card('Filler')], commander: creature('Other Commander', 2, 2) },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
const spell = game.addCard('p1', maneuver, 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', spell.id), false)
|
||||
assert.throws(() => game.castSpell('p1', spell.id), GameError)
|
||||
|
||||
game.moveToZone(game.getPlayer('p1').commanderId!, 'battlefield', { silent: true })
|
||||
|
||||
assert.equal(game.canPlayCard('p1', spell.id), true)
|
||||
game.castSpell('p1', spell.id)
|
||||
assert.equal(game.stack.length, 1)
|
||||
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 })
|
||||
})
|
||||
|
||||
test('overload pays the overload cost and widens the spell target', () => {
|
||||
const rift = card('Cyclonic Rift', {
|
||||
typeLine: 'Instant',
|
||||
manaCost: '{U}',
|
||||
manaValue: 1,
|
||||
abilities: [
|
||||
{
|
||||
kind: 'spell',
|
||||
effects: [{
|
||||
op: 'return_to_hand',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { controller: 'opponent', types: ['permanent'], excludeTypes: ['land'] },
|
||||
mode: 'target',
|
||||
},
|
||||
}],
|
||||
optional: false,
|
||||
text: "Return target nonland permanent you don't control to its owner's hand.",
|
||||
},
|
||||
{ kind: 'overload', cost: '{1}{U}', text: 'Overload {1}{U}' },
|
||||
],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const island = game.addCard('p1', land('Island', 'U'), 'battlefield')
|
||||
const wastes = game.addCard('p1', land('Wastes', 'C'), 'battlefield')
|
||||
const ownCreature = game.addCard('p1', creature('Own Bear', 2, 2), 'battlefield')
|
||||
const theirCreature = game.addCard('p2', creature('Their Bear', 2, 2), 'battlefield')
|
||||
const theirArtifact = game.addCard('p2', card('Their Rock', {
|
||||
typeLine: 'Artifact',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
}), 'battlefield')
|
||||
const theirLand = game.addCard('p2', land('Forest', 'G'), 'battlefield')
|
||||
const spell = game.addCard('p1', rift, 'hand')
|
||||
|
||||
game.castSpell('p1', spell.id, { overload: true })
|
||||
|
||||
assert.equal(island.tapped, true)
|
||||
assert.equal(wastes.tapped, true)
|
||||
game.resolveStack()
|
||||
|
||||
assert.ok(game.getPlayer('p2').hand.includes(theirCreature.id))
|
||||
assert.ok(game.getPlayer('p2').hand.includes(theirArtifact.id))
|
||||
assert.ok(game.getPlayer('p2').battlefield.includes(theirLand.id))
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(ownCreature.id))
|
||||
})
|
||||
|
||||
test('a noncreature cost increase taxes spells but not creatures', () => {
|
||||
const thalia = card('Thalia, Guardian of Thraben', {
|
||||
typeLine: 'Legendary Creature — Human Soldier',
|
||||
power: 2,
|
||||
toughness: 1,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'cost_increase', amount: { kind: 'number', value: 1 }, spellType: 'noncreature' }],
|
||||
text: 'Noncreature spells cost {1} more to cast.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', thalia, 'battlefield')
|
||||
const first = game.addCard('p1', land('Wastes', 'C'), 'battlefield')
|
||||
const instant = game.addCard('p1', spell('Ponder', [
|
||||
{ op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } },
|
||||
], '{1}'), 'hand')
|
||||
const bears = game.addCard('p1', card('Grizzly Bears', {
|
||||
typeLine: 'Creature — Bear',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
manaCost: '{1}',
|
||||
}), 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', instant.id), false)
|
||||
assert.equal(game.canPlayCard('p1', bears.id), true)
|
||||
|
||||
game.addCard('p1', land('Wastes', 'C'), 'battlefield')
|
||||
assert.equal(game.canPlayCard('p1', instant.id), true)
|
||||
game.castSpell('p1', instant.id)
|
||||
assert.equal(first.tapped, true)
|
||||
})
|
||||
|
||||
test('spell cost reductions match the spell type and controller', () => {
|
||||
const baral = card('Baral, Chief of Compliance', {
|
||||
typeLine: 'Legendary Creature — Human Wizard',
|
||||
power: 1,
|
||||
toughness: 3,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'cost_reduction',
|
||||
target: { kind: 'object', selector: { controller: 'you', types: ['instant', 'sorcery'], match: 'any' }, mode: 'each' },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}],
|
||||
text: 'Instant and sorcery spells you cast cost {1} less to cast.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', baral, 'battlefield')
|
||||
const wastes = game.addCard('p1', land('Wastes', 'C'), 'battlefield')
|
||||
const sorcery = game.addCard('p1', card('Divination', {
|
||||
typeLine: 'Sorcery',
|
||||
manaCost: '{2}',
|
||||
abilities: [{ kind: 'spell', effects: [{ op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } }], optional: false, text: 'Draw a card.' }],
|
||||
}), 'hand')
|
||||
const bears = game.addCard('p1', card('Grizzly Bears', {
|
||||
typeLine: 'Creature — Bear',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
manaCost: '{2}',
|
||||
}), 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', sorcery.id), true)
|
||||
assert.equal(game.canPlayCard('p1', bears.id), false)
|
||||
|
||||
game.castSpell('p1', sorcery.id)
|
||||
assert.equal(wastes.tapped, true)
|
||||
})
|
||||
|
||||
test('a colored cost reduction removes matching pips and nothing else', () => {
|
||||
const edgewalker = card('Edgewalker', {
|
||||
typeLine: 'Creature — Human Cleric',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'cost_reduction',
|
||||
target: { kind: 'object', selector: { controller: 'you', types: ['creature'], match: 'any', subtypes: ['cleric', 'soldier'] }, mode: 'each' },
|
||||
symbols: '{W}{B}',
|
||||
}],
|
||||
text: 'Cleric spells you cast cost {W}{B} less to cast.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', edgewalker, 'battlefield')
|
||||
game.addCard('p1', land('Plains', 'W'), 'battlefield')
|
||||
game.addCard('p1', land('Swamp', 'B'), 'battlefield')
|
||||
const cleric = game.addCard('p1', card('Cleric Test', {
|
||||
typeLine: 'Creature — Human Cleric',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
colors: ['W', 'B'],
|
||||
manaCost: '{1}{W}{B}',
|
||||
manaValue: 3,
|
||||
}), 'hand')
|
||||
const soldier = game.addCard('p1', card('Soldier Test', {
|
||||
typeLine: 'Creature — Human Soldier',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
colors: ['W', 'B'],
|
||||
manaCost: '{1}{W}{B}',
|
||||
manaValue: 3,
|
||||
}), 'hand')
|
||||
const bear = game.addCard('p1', card('Bear Test', {
|
||||
typeLine: 'Creature — Bear',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
colors: ['W', 'B'],
|
||||
manaCost: '{1}{W}{B}',
|
||||
manaValue: 3,
|
||||
}), 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', cleric.id), true)
|
||||
assert.equal(game.canPlayCard('p1', soldier.id), true)
|
||||
assert.equal(game.canPlayCard('p1', bear.id), false)
|
||||
game.castSpell('p1', cleric.id)
|
||||
})
|
||||
|
||||
test('Linvala stops only opponents from activating creature abilities', () => {
|
||||
const linvala = card('Linvala, Keeper of Silence', {
|
||||
typeLine: 'Legendary Creature — Angel',
|
||||
power: 3,
|
||||
toughness: 4,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'restriction',
|
||||
target: { kind: 'object', selector: { controller: 'opponent', types: ['creature'] }, mode: 'each' },
|
||||
rule: 'cant_activate',
|
||||
}],
|
||||
text: "Activated abilities of creatures your opponents control can't be activated.",
|
||||
}],
|
||||
})
|
||||
const drawAbility = {
|
||||
kind: 'activated' as const,
|
||||
costs: [],
|
||||
effects: [{ op: 'draw' as const, player: 'you' as const, amount: { kind: 'number' as const, value: 1 } }],
|
||||
optional: false,
|
||||
text: 'Draw a card.',
|
||||
}
|
||||
const game = setup([{ id: 'p1', deck: [card('Filler'), card('Filler')] }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', linvala, 'battlefield')
|
||||
const own = game.addCard('p1', creature('Own Cleric', 1, 1, [drawAbility]), 'battlefield')
|
||||
const theirs = game.addCard('p2', creature('Their Cleric', 1, 1, [drawAbility]), 'battlefield')
|
||||
|
||||
game.activateAbility('p1', own.id, 0)
|
||||
assert.equal(game.stack.length, 1)
|
||||
|
||||
game.resolveStack()
|
||||
game.pass('p1')
|
||||
assert.throws(() => game.activateAbility('p2', theirs.id, 0), /cannot activate/)
|
||||
})
|
||||
|
||||
test('Aven Mindcensor limits an opponent search to the top four cards', () => {
|
||||
const aven = card('Aven Mindcensor', {
|
||||
typeLine: 'Creature — Bird Wizard',
|
||||
power: 2,
|
||||
toughness: 1,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'search_restriction', who: 'opponent', amount: { kind: 'number', value: 4 } }],
|
||||
text: 'If an opponent would search a library, that player searches the top four cards of that library instead.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2', deck: [] }])
|
||||
game.start()
|
||||
game.addCard('p1', aven, 'battlefield')
|
||||
for (const name of ['Forest', 'Island', 'Mountain', 'Plains', 'Swamp', 'Wastes']) {
|
||||
game.addCard('p2', land(name, 'C'), 'library')
|
||||
}
|
||||
const topFour = game.getPlayer('p2').library.slice(0, 4)
|
||||
const growth = game.addCard('p2', spell('Rampant Growth', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'battlefield',
|
||||
shuffle: true,
|
||||
}]), 'hand')
|
||||
|
||||
game.pass('p1')
|
||||
game.castSpell('p2', growth.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.deepEqual(
|
||||
game.searchCandidates('p2').map(object => object.id).sort(),
|
||||
[...topFour].sort(),
|
||||
)
|
||||
})
|
||||
|
||||
test('Rest in Peace exiles all graveyards and replaces later graveyard moves', () => {
|
||||
const rest = card('Rest in Peace', {
|
||||
typeLine: 'Enchantment',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [
|
||||
{
|
||||
kind: 'triggered',
|
||||
event: { kind: 'enters', subject: { kind: 'self' } },
|
||||
effects: [{ op: 'exile_graveyards' }],
|
||||
optional: false,
|
||||
text: 'When this enchantment enters, exile all graveyards.',
|
||||
},
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'exile_instead_of_graveyard' }],
|
||||
text: 'If a card or token would be put into a graveyard from anywhere, exile it instead.',
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const oldSpell = game.addCard('p1', spell('Old Spell', []), 'graveyard')
|
||||
const oldCreature = game.addCard('p2', creature('Old Bear', 2, 2), 'graveyard')
|
||||
const doomed = game.addCard('p1', creature('Doomed Bear', 2, 2), 'battlefield')
|
||||
|
||||
game.addCard('p1', rest, 'battlefield', { silent: false })
|
||||
game.resolveStack()
|
||||
|
||||
assert.ok(game.getPlayer('p1').exile.includes(oldSpell.id))
|
||||
assert.ok(game.getPlayer('p2').exile.includes(oldCreature.id))
|
||||
assert.deepEqual(game.getPlayer('p1').graveyard, [])
|
||||
assert.deepEqual(game.getPlayer('p2').graveyard, [])
|
||||
|
||||
game.moveToZone(doomed, 'graveyard')
|
||||
|
||||
assert.equal(doomed.zone, 'exile')
|
||||
assert.ok(game.getPlayer('p1').exile.includes(doomed.id))
|
||||
})
|
||||
|
||||
test("Leyline of the Void exiles only opponents' cards and starts on the battlefield", () => {
|
||||
const leyline = card('Leyline of the Void', {
|
||||
typeLine: 'Enchantment',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'restriction', target: { kind: 'self' }, rule: 'begin_on_battlefield' }],
|
||||
text: 'If this card is in your opening hand, you may begin the game with it on the battlefield.',
|
||||
},
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'exile_instead_of_graveyard', owner: 'opponent' }],
|
||||
text: "If a card would be put into an opponent's graveyard from anywhere, exile it instead.",
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = new Game({
|
||||
seed: 3,
|
||||
startingHandSize: 0,
|
||||
players: [{ id: 'p1', deck: [card('Filler')] }, { id: 'p2', deck: [card('Filler')] }],
|
||||
})
|
||||
const leylineObject = game.addCard('p1', leyline, 'hand')
|
||||
game.start()
|
||||
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(leylineObject.id))
|
||||
assert.ok(!game.getPlayer('p1').hand.includes(leylineObject.id))
|
||||
|
||||
const theirs = game.addCard('p2', creature('Their Bear', 2, 2), 'battlefield')
|
||||
const own = game.addCard('p1', creature('Own Bear', 2, 2), 'battlefield')
|
||||
game.moveToZone(theirs, 'graveyard')
|
||||
game.moveToZone(own, 'graveyard')
|
||||
|
||||
assert.equal(theirs.zone, 'exile')
|
||||
assert.equal(own.zone, 'graveyard')
|
||||
})
|
||||
|
||||
test('Field of the Dead makes a Zombie at seven differently named lands', () => {
|
||||
const field = card('Field of the Dead', {
|
||||
typeLine: 'Land',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'triggered',
|
||||
event: {
|
||||
kind: 'enters',
|
||||
subject: {
|
||||
kind: 'object',
|
||||
selector: { other: true, controller: 'you', types: ['land'] },
|
||||
mode: 'each',
|
||||
includeSelf: true,
|
||||
},
|
||||
},
|
||||
condition: { kind: 'distinct_names', selector: { types: ['land'] }, atLeast: 7 },
|
||||
effects: [{
|
||||
op: 'create_token',
|
||||
player: 'you',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
token: {
|
||||
types: ['creature'],
|
||||
subtypes: ['zombie'],
|
||||
colors: ['B'],
|
||||
power: { kind: 'number', value: 2 },
|
||||
toughness: { kind: 'number', value: 2 },
|
||||
},
|
||||
}],
|
||||
optional: false,
|
||||
text: 'Whenever this or another land you control enters, if you control seven or more lands with different names, create a 2/2 black Zombie creature token.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', field, 'battlefield')
|
||||
for (const name of ['Forest', 'Island', 'Mountain', 'Plains']) {
|
||||
game.addCard('p1', land(name, 'C'), 'battlefield')
|
||||
}
|
||||
|
||||
game.addCard('p1', land('Swamp', 'C'), 'battlefield', { silent: false })
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p1').battlefield
|
||||
.map(id => game.getObject(id)).filter(object => object.isToken).length, 0)
|
||||
|
||||
game.addCard('p1', land('Wastes', 'C'), 'battlefield', { silent: false })
|
||||
game.resolveStack()
|
||||
|
||||
const tokens = game.getPlayer('p1').battlefield
|
||||
.map(id => game.getObject(id)).filter(object => object.isToken)
|
||||
assert.equal(tokens.length, 1)
|
||||
assert.equal(tokens[0].definition.typeLine.toLowerCase().includes('zombie'), true)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user