kjdskjdsk

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

View File

@@ -284,6 +284,8 @@ your public URLs. Both values are applied at runtime in the production image.
| `GET` | `/me/decks` | The account's saved decks | | `GET` | `/me/decks` | The account's saved decks |
| `PUT` | `/me/decks/:id` | Create or replace a saved deck | | `PUT` | `/me/decks/:id` | Create or replace a saved deck |
| `DELETE` | `/me/decks/:id` | Delete a saved deck | | `DELETE` | `/me/decks/:id` | Delete a saved deck |
| `POST` | `/me/decks/:id/share` | Create (or reuse) a share link token for a saved deck |
| `GET` | `/decks/share/:token` | Public read of a shared deck, used to import a copy |
| `GET` | `/me/preferences` | Saved playmat and card back | | `GET` | `/me/preferences` | Saved playmat and card back |
| `PUT` | `/me/preferences` | Update `{ playmat?, cardBack? }` | | `PUT` | `/me/preferences` | Update `{ playmat?, cardBack? }` |
| `POST` | `/decks/import` | Parse a text decklist into `{ commander, cards, errors }` | | `POST` | `/decks/import` | Parse a text decklist into `{ commander, cards, errors }` |

View File

@@ -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}.` | | `activated` | Cost `:` effect, including loyalty | `{T}: Add {G}.` |
| `static` | Continuous effect or restriction | `Creatures you control get +1/+1.` | | `static` | Continuous effect or restriction | `Creatures you control get +1/+1.` |
| `spell` | Effect line of an instant or sorcery | `Draw two cards.` | | `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 —` | | `unsupported` | Preserved text plus a reason | `Choose one —` |
### Effects ### 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 | | `sacrifice` | `player`, `target`, optional `unless` cost |
| `counter` | `what`, `target`, optional `unless` cost | | `counter` | `what`, `target`, optional `unless` cost |
| `return_to_hand`, `return_to_battlefield`, `put_on_top` | `target` | | `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`) | | `add_mana` | `player`, `mana` (`symbols` or `any_color`) |
| `scry`, `surveil` | `player`, `amount` | | `scry`, `surveil` | `player`, `amount` |
| `fight` | two targets | | `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 | | `restriction` | target, rule, duration |
| `keyword_action` | `action`, optional `amount`, `detail`, `target` | | `keyword_action` | `action`, optional `amount`, `detail`, `target` |
| `proliferate` | no payload | | `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 ### 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`. `source_toughness`, `cards_in_hand`, or `event_amount`.
- **Costs** are mana symbols, tap/untap, tapping another permanent, energy, - **Costs** are mana symbols, tap/untap, tapping another permanent, energy,
loyalty, life, discard, sacrifice, self-exile, mill, and removing counters. loyalty, life, discard, sacrifice, self-exile, mill, and removing counters.
- **Conditions** cover controlling permanents, turn ownership, tapped source, - **Conditions** cover controlling permanents, commander control, turn ownership,
life totals, and graveyard size. 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 - **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 next turn, end of combat, controller's next untap step, and while the source
remains. remains.

View File

@@ -58,7 +58,7 @@ const bolt: CardDefinition = {
| ------ | ------- | | ------ | ------- |
| `start()` | Shuffles libraries, draws opening hands, begins turn 1. | | `start()` | Shuffles libraries, draws opening hands, begins turn 1. |
| `playLand(playerId, cardId)` | Plays a land from hand; once per turn, main phase, empty stack. | | `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. | | `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. | | `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. | | `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. | | `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. | | `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. | | `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. | | `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. | | `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. | | `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 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 chosen automatically, which keeps scripted games short. A search effect that matches
several cards pauses instead: other actions are refused until its controller calls 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 ## 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 - Zones: library, hand, battlefield, graveyard, exile, stack, and command zone. Tokens
cease to exist when they leave the battlefield. cease to exist when they leave the battlefield.
- Commander: command-zone casting, `{2}` tax per previous cast from the command - 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 zone, free alternative costs while you control a commander, return to the command
loss at 21 combat damage from one commander. Deck construction is validated by zone instead of graveyard/exile/hand/library, and a loss at 21 combat damage from
`validateCommanderDeck`. one commander. Deck construction is validated by `validateCommanderDeck`.
- Mana: colored, generic, hybrid, Phyrexian, `{X}`, and `{S}` costs; manual mana - Mana: colored, generic, hybrid, Phyrexian, `{X}`, and `{S}` costs; manual mana
abilities plus automatic tapping of untapped mana sources when paying. abilities plus automatic tapping of untapped mana sources when paying.
- Costs: tap, untap, tap another permanent, pay life, discard, sacrifice, exile, - Costs: tap, untap, tap another permanent, pay life, discard, sacrifice, exile,
putting/removing counters, mill, energy, and choice costs. putting/removing counters, mill, energy, and choice costs. Static cost reductions
- Abilities: spell effects, activated abilities, triggered abilities (enters, and increases apply while their source is on the battlefield.
leaves, dies, attacks, blocks, cast, draw, life, upkeep, end step, combat), static - Abilities: spell effects, overload, activated abilities, triggered abilities
effects, and basic replacement effects for entering tapped/with counters. (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, - Effects: damage, draw, discard, mill, life, pump/set P/T, grant keyword,
counters, proliferate, tokens, destroy, exile, sacrifice, counter spell/ability, counters, proliferate, tokens, destroy, exile, exile all graveyards, sacrifice,
zone returns, tap/untap, search/shuffle, add mana, fight, regenerate, energy, counter spell/ability, zone returns, tap/untap, search/shuffle, add mana, fight,
attach, restrictions, conditional and modal effects, dig, and divided damage. 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, - Combat keywords: flying, reach, first strike, double strike, trample, deathtouch,
lifelink, vigilance, haste, indestructible. Regeneration shields replace lifelink, vigilance, haste, indestructible. Regeneration shields replace
destruction. 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 - 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 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. 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. - Opening hands are kept automatically; there is no mulligan flow.
- Replacement/prevention effects, layers, and dependency ordering are simplified. - Replacement/prevention effects, layers, and dependency ordering are simplified.
Continuous effects apply in creation order rather than in full rules order. Continuous effects apply in creation order rather than in full rules order.

View File

@@ -69,9 +69,11 @@ const deckSchema = new Schema({
commander: { type: deckCardSchema, required: true }, commander: { type: deckCardSchema, required: true },
cards: { type: [deckCardSchema], default: [] }, cards: { type: [deckCardSchema], default: [] },
cardBack: { type: String, default: null }, cardBack: { type: String, default: null },
shareToken: String,
updatedAt: { type: Number, required: true }, updatedAt: { type: Number, required: true },
}) })
deckSchema.index({ owner: 1, deckId: 1 }, { unique: 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 User = mongoose.models.User ?? mongoose.model('User', userSchema)
const Session = mongoose.models.Session ?? mongoose.model('Session', sessionSchema) const Session = mongoose.models.Session ?? mongoose.model('Session', sessionSchema)
@@ -83,6 +85,7 @@ interface DeckRow {
commander: DeckCardInput commander: DeckCardInput
cards: DeckCardInput[] cards: DeckCardInput[]
cardBack?: string | null cardBack?: string | null
shareToken?: string
updatedAt: number updatedAt: number
} }
@@ -305,6 +308,34 @@ export function registerAccountRoutes(app: FastifyInstance): void {
return { ok: true } 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 => { app.get('/me/preferences', async request => {
const user = await authenticate(request) const user = await authenticate(request)
return preferences(user.id) return preferences(user.id)

View File

@@ -448,6 +448,27 @@ function parseDigDestination(text: string): 'hand' | 'graveyard' | 'battlefield'
return 'bottom' 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 { function parseSearch(text: string): Effect | undefined {
const match = text.match(/^search your (library|library and\/or graveyard) for (.+)$/) const match = text.match(/^search your (library|library and\/or graveyard) for (.+)$/)
if (!match) return undefined if (!match) return undefined
@@ -476,34 +497,53 @@ function parseSearch(text: string): Effect | undefined {
const revealPrefix = /^reveal (?:it|them|that card|those cards),? (?:and )?/ const revealPrefix = /^reveal (?:it|them|that card|those cards),? (?:and )?/
let destinationText = rest.replace(revealPrefix, '') let destinationText = rest.replace(revealPrefix, '')
let shuffle = false 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 } : {}) } 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 } : {}) } 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 } : {}) } 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( 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)?$/, /^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 if (!put) continue
const destination = const parsedDestination = parseSearchDestination(put[1])
put[1] === 'into your hand' if (!parsedDestination) continue
? 'hand'
: put[1].startsWith('onto the battlefield')
? 'battlefield'
: put[1] === 'into your graveyard'
? 'graveyard'
: put[1] === 'on top of your library'
? 'top'
: 'bottom'
shuffle = /then shuffle$/.test(destinationText) shuffle = /then shuffle$/.test(destinationText)
const tapped = /\btapped\b/.test(put[1]) return {
return { op: 'search', player: 'you', selector, amount, destination, tapped, shuffle, ...(zones ? { zones } : {}) } op: 'search',
player: 'you',
selector,
amount,
destination: parsedDestination.destination,
tapped: parsedDestination.tapped,
shuffle,
...(zones ? { zones } : {}),
}
} }
return undefined return undefined
@@ -750,6 +790,8 @@ function parseEffect(text: string): Effect | Effect[] | undefined {
if (target) return { op: 'destroy', target } if (target) return { op: 'destroy', target }
} }
if (sentence === 'exile all graveyards') return { op: 'exile_graveyards' }
match = sentence.match(/^exile (.+)$/) match = sentence.match(/^exile (.+)$/)
if (match) { if (match) {
const target = parseGroupTarget(match[1]) 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' } 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 return undefined
} }
@@ -1359,6 +1404,14 @@ function parseEffects(text: string): { effects: Effect[]; optional: boolean } |
return undefined 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) const conditional = sentence.match(/^if (.+?), (.+)$/i)
if (conditional) { if (conditional) {
const raw = conditional[1].trim().toLowerCase() const raw = conditional[1].trim().toLowerCase()
@@ -1630,8 +1683,28 @@ function parseStaticTarget(text: string): Target | undefined {
return 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 { 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 (.+)$/) let match = sentence.match(/^(?:its|this's) (base )?power and toughness are each equal to (.+)$/)
if (match) { if (match) {
@@ -1875,6 +1948,33 @@ function parseStaticEffects(text: string): StaticEffect[] | undefined {
return [{ op: 'replacement', what: 'leaves_battlefield', instead: 'exile', target: { kind: 'self' } }] 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 costText = sentence
let costCondition: Condition | undefined let costCondition: Condition | undefined
let costAmount: Value | undefined let costAmount: Value | undefined
@@ -1896,17 +1996,25 @@ function parseStaticEffects(text: string): StaticEffect[] | undefined {
} }
match = costText.match(/^(.+?) costs? ((?:\{[^}]+\})+) less to cast(?: for each (.+))?$/) match = costText.match(/^(.+?) costs? ((?:\{[^}]+\})+) less to cast(?: for each (.+))?$/)
if (match) { if (match) {
const target = parseStaticTarget(match[1]) const target = parseCostReductionTarget(match[1])
let amount: Value | undefined = costAmount let amount: Value | undefined = costAmount
let symbols: string | undefined
if (!amount && match[3]) { if (!amount && match[3]) {
const selector = parseSelector(match[3]) const selector = parseSelector(match[3])
if (selector) amount = { kind: 'count', selector } if (selector) amount = { kind: 'count', selector }
} else if (!amount) { } else if (!amount) {
const inner = match[2].match(/\{([^}]+)\}/)?.[1] const parts = [...match[2].matchAll(/\{([^}]+)\}/g)].map(symbol => symbol[1])
if (inner) amount = parseValue(inner.toLowerCase()) if (parts.some(part => /[WUBRGC]/i.test(part))) symbols = match[2].toUpperCase()
else if (parts[0]) amount = parseValue(parts[0].toLowerCase())
} }
if (target && amount) { if (target && (amount || symbols)) {
return [{ op: 'cost_reduction', target, amount, condition: costCondition }] 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())) { 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 } 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) const chapter = body.match(/^([ivx]+(?:, [ivx]+)*) — (.+)$/i)
if (chapter) { if (chapter) {
const effects = parseEffects(resolveIt(chapter[2], 'this')) const effects = parseEffects(resolveIt(chapter[2], 'this'))

View File

@@ -58,11 +58,12 @@ function formatSelector(selector: ObjectSelector): string {
if (selector.token) parts.push('token') if (selector.token) parts.push('token')
if (selector.token === false) parts.push('nontoken') if (selector.token === false) parts.push('nontoken')
if (selector.attached) parts.push(selector.attached) if (selector.attached) parts.push(selector.attached)
const joiner = selector.match === 'any' ? ' or ' : ' and '
if (selector.colors?.length) { 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.supertypes?.length) parts.push(selector.supertypes.join(joiner))
if (selector.subtypes?.length) parts.push(selector.subtypes.join(' ')) if (selector.subtypes?.length) parts.push(selector.subtypes.join(joiner))
if (selector.types?.length) { if (selector.types?.length) {
parts.push(selector.types.join(selector.match === 'any' ? ' or ' : ' ')) parts.push(selector.types.join(selector.match === 'any' ? ' or ' : ' '))
} }
@@ -281,7 +282,7 @@ export function formatEffect(effect: Effect): string {
case 'surveil': case 'surveil':
return `surveil(${effect.player}, ${formatValue(effect.amount)})` return `surveil(${effect.player}, ${formatValue(effect.amount)})`
case 'search': 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': case 'shuffle':
return `shuffle(${effect.player})` return `shuffle(${effect.player})`
case 'add_mana': 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'))}` return `schedule(${effect.when}):\n${indent(effect.effects.map(formatEffect).join('\n'))}`
case 'damage_divided': case 'damage_divided':
return `damage_divided(${formatValue(effect.amount)}, ${formatTarget(effect.target)})` 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" return "you don't"
case 'otherwise': case 'otherwise':
return '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': case 'replacement':
return `replace(${effect.what}${effect.target ? `, ${formatTarget(effect.target)}` : ''}, instead ${effect.instead})` return `replace(${effect.what}${effect.target ? `, ${formatTarget(effect.target)}` : ''}, instead ${effect.instead})`
case 'cost_reduction': 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'))}` return `spell${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}`
case 'additional_cost': case 'additional_cost':
return `additional cost${ability.optional ? ' (may)' : ''}: ${ability.costs.map(formatCost).join(', ')}` 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': case 'chapter':
return `chapter ${ability.chapters.join(', ')}${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}` return `chapter ${ability.chapters.join(', ')}${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}`
case 'level_band': { case 'level_band': {

View File

@@ -350,6 +350,17 @@ function parseQualifierSuffix(rest: string, selector: ObjectSelector): string {
} }
} }
match = text.match(/^(.+?) with mana value (\w+)$/)
if (match) {
const amount = parseNumber(match[2])
if (amount !== undefined) {
selector.manaValue = { atLeast: amount, atMost: amount }
text = match[1].trim()
changed = true
continue
}
}
match = text.match(/^(.+?) with (.+)$/) match = text.match(/^(.+?) with (.+)$/)
if (match && SELECTOR_KEYWORDS.has(match[2])) { if (match && SELECTOR_KEYWORDS.has(match[2])) {
selector.keywords = [...(selector.keywords ?? []), 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'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 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$/) const graveyard = trimmed.match(/^there are (\w+) or more cards in (your|an opponent's|target player's) graveyard$/)
if (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$/) 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]) } 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 )?(.+)$/) const control = trimmed.match(/^you control (?:at least )?(one|two|three|four|five|six|seven|eight|nine|ten|\d+) (?:or more )?(.+)$/)
if (control) { if (control) {
const selector = parseSelector(control[2]) const selector = parseSelector(control[2])

View File

@@ -816,6 +816,16 @@ function parseEffectExpr(text: string, line: SourceLine): Effect {
} }
case 'proliferate': case 'proliferate':
return { op: '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': { case 'create_token': {
const rest = args.slice(2).join(', ').trim() const rest = args.slice(2).join(', ').trim()
if (rest.startsWith('copy of ')) { if (rest.startsWith('copy of ')) {
@@ -903,6 +913,20 @@ function parseEffectExpr(text: string, line: SourceLine): Effect {
if (!['hand', 'battlefield', 'graveyard', 'top', 'bottom'].includes(destination)) { if (!['hand', 'battlefield', 'graveyard', 'top', 'bottom'].includes(destination)) {
fail(line, `unknown search destination "${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 before = args.slice(1, destinationIndex)
const amountText = before[before.length - 1] const amountText = before[before.length - 1]
if (amountText === undefined) fail(line, 'search needs an amount') 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', destination: destination as 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom',
tapped: args.includes('tapped'), tapped: args.includes('tapped'),
shuffle: args.includes('shuffle'), shuffle: args.includes('shuffle'),
...(split ? { split } : {}),
...(args.includes('library+graveyard') ? { zones: ['library', 'graveyard'] as ('library' | 'graveyard')[] } : {}), ...(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 } return { kind: 'cast_spell_this_turn', noncreature: true }
} }
if (trimmed === 'you have a full party') return { kind: 'full_party' } 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 spells were cast last turn') return { kind: 'no_spells_last_turn' }
if (trimmed === 'no creatures attacked this turn') return { kind: 'no_attackers' } if (trimmed === 'no creatures attacked this turn') return { kind: 'no_attackers' }
if (trimmed === "tribute wasn't paid") return { kind: 'tribute_not_paid' } 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 === 'otherwise') return { kind: 'otherwise' }
if (trimmed === 'defending player controls') return fail(line, 'missing defending-player selector') 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]) } 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)$/) match = trimmed.match(/^you control a creature with (power|toughness) greater than its base (?:power|toughness)$/)
if (match) { if (match) {
return { kind: 'creature_power_greater_than_base', controller: 'you', stat: match[1] as 'power' | 'toughness' } 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': { case 'cost_reduction': {
const rest = args[2]?.trim() const rest = args[2]?.trim()
const value = arg(args, 1, line).trim()
return { return {
op: 'cost_reduction', op: 'cost_reduction',
target: parseTarget(arg(args, 0, line), line), 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) } : {}), ...(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': case 'unsupported':
return fail(line, 'unsupported is an ability, not a static effect') return fail(line, 'unsupported is an ability, not a static effect')
default: 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 } 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}"`) if (!header.endsWith(':')) fail(block.header, `expected an ability block, got "${header}"`)
let rest = header.slice(0, -1) let rest = header.slice(0, -1)

View File

@@ -137,7 +137,7 @@ Static effects:
control(target) control(target)
choose(creature_type|color|card_name|player|opponent|number) 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) 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>, Common conditions: you control <selector>, you control at least N <selector>,
an opponent controls <selector>, it is your turn, it isn't your turn, an opponent controls <selector>, it is your turn, it isn't your turn,

View File

@@ -3,6 +3,8 @@
export type Zone = 'battlefield' | 'hand' | 'graveyard' | 'library' | 'exile' | 'stack' | 'command' export type Zone = 'battlefield' | 'hand' | 'graveyard' | 'library' | 'exile' | 'stack' | 'command'
export type SearchDestination = 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'
export type PlayerRef = export type PlayerRef =
| 'you' | 'you'
| 'opponent' | 'opponent'
@@ -184,6 +186,11 @@ export type Condition =
| { kind: 'if_you_do' } | { kind: 'if_you_do' }
| { kind: 'if_you_dont' } | { kind: 'if_you_dont' }
| { kind: 'otherwise' } | { 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 = export type TriggerEvent =
| { kind: 'enters'; subject: Target } | { kind: 'enters'; subject: Target }
@@ -230,7 +237,7 @@ export type Effect =
| { op: 'untap'; target: Target } | { op: 'untap'; target: Target }
| { op: 'scry'; player: PlayerRef; amount: Value } | { op: 'scry'; player: PlayerRef; amount: Value }
| { op: 'surveil'; 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: 'shuffle'; player: PlayerRef }
| { op: 'add_mana'; player: PlayerRef; mana: ManaSpec } | { op: 'add_mana'; player: PlayerRef; mana: ManaSpec }
| { op: 'fight'; a: Target; b: Target } | { 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: '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: '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: 'damage_divided'; amount: Value; target: Target }
| { op: 'exile_graveyards' }
| { op: 'hideaway'; amount: Value }
| { op: 'play_exiled'; player: PlayerRef; free?: boolean }
export type StaticEffect = export type StaticEffect =
| { op: 'pump'; target: Target; power: Value; toughness: Value } | { op: 'pump'; target: Target; power: Value; toughness: Value }
@@ -264,7 +274,10 @@ export type StaticEffect =
| { op: 'control'; target: Target } | { op: 'control'; target: Target }
| { op: 'choose'; what: 'creature_type' | 'color' | 'card_name' | 'player' | 'opponent' | 'number' } | { 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: '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 = export type Ability =
| KeywordAbility | KeywordAbility
@@ -308,6 +321,17 @@ export type Ability =
optional: boolean optional: boolean
text: string text: string
} }
| {
kind: 'alternative_cost'
costs: Cost[]
condition?: Condition
text: string
}
| {
kind: 'overload'
cost: string
text: string
}
| { | {
kind: 'chapter' kind: 'chapter'
chapters: string[] chapters: string[]

View File

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

View File

@@ -23,6 +23,7 @@ import type {
GameConfig, GameConfig,
ManaColor, ManaColor,
ManaPool, ManaPool,
PendingChoice,
PendingSearch, PendingSearch,
Phase, Phase,
PlayerState, PlayerState,
@@ -30,6 +31,7 @@ import type {
Step, Step,
TargetChoice, TargetChoice,
} from './types.js' } from './types.js'
import { CREATURE_TYPES } from './creature-types.js'
export class GameError extends Error {} export class GameError extends Error {}
@@ -120,6 +122,37 @@ function parseManaCost(symbols: string, x = 0): ManaCost {
return cost 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 { function manaValueOf(definition: CardDefinition): number {
if (definition.manaValue !== undefined) return definition.manaValue if (definition.manaValue !== undefined) return definition.manaValue
const cost = parseManaCost(definition.manaCost ?? '') const cost = parseManaCost(definition.manaCost ?? '')
@@ -166,6 +199,12 @@ export class Game {
winner?: string winner?: string
/** Blocks all other actions until the searching player picks a card. */ /** Blocks all other actions until the searching player picks a card. */
pendingSearch?: PendingSearch 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 config: GameConfig
private readonly rng: () => number private readonly rng: () => number
@@ -214,6 +253,8 @@ export class Game {
creaturesDiedThisTurn: 0, creaturesDiedThisTurn: 0,
nonlandPermanentsEnteredThisTurn: 0, nonlandPermanentsEnteredThisTurn: 0,
attackedThisTurn: false, attackedThisTurn: false,
creaturesAttackedThisTurn: 0,
damageTakenThisTurn: 0,
energy: 0, energy: 0,
poison: 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.status = 'active'
this.turn = 1 this.turn = 1
this.activePlayer = this.firstPlayer this.activePlayer = this.firstPlayer
@@ -302,9 +354,10 @@ export class Game {
const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId
// A commander may go to the command zone instead of the graveyard, exile, // A commander may go to the command zone instead of the graveyard, exile,
// hand, or library. This engine always takes that replacement. // 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' ? 'command'
: zone : zone
if (destination === 'graveyard' && this.exilesInsteadOfGraveyard(object)) destination = 'exile'
const from = object.zone const from = object.zone
this.removeFromZone(object) this.removeFromZone(object)
object.zone = destination object.zone = destination
@@ -318,6 +371,7 @@ export class Game {
object.blockedBy = [] object.blockedBy = []
object.blocking = undefined object.blocking = undefined
object.activations = {} object.activations = {}
object.chosenCreatureType = undefined
object.enteredTurn = this.turn object.enteredTurn = this.turn
this.getPlayer(object.controller).battlefield.push(object.id) this.getPlayer(object.controller).battlefield.push(object.id)
if (from !== 'battlefield') { if (from !== 'battlefield') {
@@ -326,12 +380,14 @@ export class Game {
} }
if (!options.silent) { if (!options.silent) {
this.applyEntersReplacements(object) this.applyEntersReplacements(object)
this.queueEnterChoices(object)
this.dispatchEvent({ kind: 'enters', player: object.controller, subject: object }) this.dispatchEvent({ kind: 'enters', player: object.controller, subject: object })
} }
} }
} else { } else {
object.position = undefined object.position = undefined
object.controller = object.owner object.controller = object.owner
object.chosenCreatureType = undefined
const owner = this.getPlayer(object.owner) const owner = this.getPlayer(object.owner)
if (destination === 'hand') owner.hand.push(object.id) if (destination === 'hand') owner.hand.push(object.id)
else if (destination === 'graveyard') owner.graveyard.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 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) .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 targets = this.selectTargets(effects, object, playerId, options.targets ?? [], options.mode ?? 0)
const tax = fromCommand ? (player.commanderCasts[object.id] ?? 0) * 2 : 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 }) this.moveToZone(object, 'stack', { controller: playerId, silent: true })
if (fromCommand) player.commanderCasts[object.id] = (player.commanderCasts[object.id] ?? 0) + 1 if (fromCommand) player.commanderCasts[object.id] = (player.commanderCasts[object.id] ?? 0) + 1
@@ -545,11 +615,80 @@ export class Game {
return item 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 { activateAbility(playerId: string, sourceId: string, abilityIndex: number, options: ActionOptions = {}): StackItem | undefined {
this.requirePriority(playerId) this.requirePriority(playerId)
const source = this.getObject(sourceId) const source = this.getObject(sourceId)
if (source.zone !== 'battlefield') throw new GameError('Ability source is not on the battlefield') 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 (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] const ability = (source.definition.abilities ?? [])[abilityIndex]
if (!ability || ability.kind !== 'activated') throw new GameError('That is not an activated ability') 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') 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 attacker.attacking = attack.defenderId
if (!this.hasKeyword(attacker, 'Vigilance')) attacker.tapped = true if (!this.hasKeyword(attacker, 'Vigilance')) attacker.tapped = true
this.getPlayer(playerId).attackedThisTurn = true this.getPlayer(playerId).attackedThisTurn = true
this.getPlayer(playerId).creaturesAttackedThisTurn++
this.dispatchEvent({ kind: 'attacks', player: playerId, subject: attacker }) 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.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.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.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') if (this.priority !== playerId) throw new GameError('You do not have priority')
const seen = new Set<string>() const seen = new Set<string>()
@@ -702,6 +843,7 @@ export class Game {
pass(playerId?: string): void { pass(playerId?: string): void {
if (this.status !== 'active') throw new GameError('Game is not active') 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.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 const actual = playerId ?? this.priority
if (this.priority !== actual) throw new GameError('You do not have priority') if (this.priority !== actual) throw new GameError('You do not have priority')
const alive = this.alivePlayers().length const alive = this.alivePlayers().length
@@ -740,7 +882,8 @@ export class Game {
/** Convenience for tests and scripted games: resolve the stack without advancing phases. */ /** Convenience for tests and scripted games: resolve the stack without advancing phases. */
resolveStack(): void { resolveStack(): void {
let guard = 0 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) this.pass(this.priority)
} }
} }
@@ -755,7 +898,7 @@ export class Game {
this.step = 'end_step' this.step = 'end_step'
this.dispatchEvent({ kind: 'end_step', player: playerId }) this.dispatchEvent({ kind: 'end_step', player: playerId })
this.resolveStack() this.resolveStack()
if (this.status !== 'active' || this.pendingSearch) return if (this.status !== 'active' || this.pendingSearch || this.pendingChoice) return
this.finishTurn() this.finishTurn()
} }
@@ -764,7 +907,7 @@ export class Game {
* right now. Used for the client's playable state and for auto-passing. * right now. Used for the client's playable state and for auto-passing.
*/ */
canPlayCard(playerId: string, cardId: string): boolean { 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 player = this.getPlayer(playerId)
const fromCommand = player.command.includes(cardId) const fromCommand = player.command.includes(cardId)
if (!fromCommand && !player.hand.includes(cardId)) return false if (!fromCommand && !player.hand.includes(cardId)) return false
@@ -780,9 +923,20 @@ export class Game {
if (!this.canCastAtThisTime(playerId, object)) return false if (!this.canCastAtThisTime(playerId, object)) return false
const tax = fromCommand ? (player.commanderCasts[cardId] ?? 0) * 2 : 0 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 return false
} }
if (alternative && extra && !this.canAffordMana(playerId, `{${extra}}`, 0)) return false
return this.hasLegalTargets(object, playerId) return this.hasLegalTargets(object, playerId)
} }
@@ -793,12 +947,18 @@ export class Game {
chooseSearchCard(playerId: string, cardId: string): void { chooseSearchCard(playerId: string, cardId: string): void {
const pending = this.pendingSearch const pending = this.pendingSearch
if (!pending) throw new GameError('No search is waiting for a choice') 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') if (pending.playerId !== playerId) throw new GameError('You are not searching your library')
const object = this.searchCandidates(playerId).find(candidate => candidate.id === cardId) const object = this.searchCandidates(playerId).find(candidate => candidate.id === cardId)
if (!object) throw new GameError('That card is not a legal choice') if (!object) throw new GameError('That card is not a legal choice')
this.moveSearchedCard(object, playerId, pending.destination, pending.tapped) this.moveSearchedCard(object, playerId, pending.destination, pending.tapped)
pending.remaining-- 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) { if (pending.remaining <= 0 || !this.searchCandidates(playerId).length) {
this.pendingSearch = undefined this.pendingSearch = undefined
if (pending.shuffle) this.shuffleLibrary(this.getPlayer(playerId)) if (pending.shuffle) this.shuffleLibrary(this.getPlayer(playerId))
@@ -816,17 +976,45 @@ export class Game {
return this.findSearchCandidates(playerId, pending.selector, pending.zones) 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 * 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. * first player who can act, or when the turn ends, so turns never run on.
*/ */
autoAdvance(): void { 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++ this.autoAdvanceDepth++
const turn = this.turn const turn = this.turn
try { try {
let guard = 0 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 const actor = this.priority
if (!actor || this.hasMeaningfulAction(actor)) break if (!actor || this.hasMeaningfulAction(actor)) break
this.pass(actor) this.pass(actor)
@@ -853,6 +1041,8 @@ export class Game {
player.creaturesDiedThisTurn = 0 player.creaturesDiedThisTurn = 0
player.nonlandPermanentsEnteredThisTurn = 0 player.nonlandPermanentsEnteredThisTurn = 0
player.attackedThisTurn = false player.attackedThisTurn = false
player.creaturesAttackedThisTurn = 0
player.damageTakenThisTurn = 0
player.manaPool = emptyPool() player.manaPool = emptyPool()
this.removeExpiringEffects(player.id) this.removeExpiringEffects(player.id)
@@ -1688,6 +1878,12 @@ export class Game {
} }
break 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': { case 'sacrifice': {
const players = this.playersForEffect(effect.player, context) const players = this.playersForEffect(effect.player, context)
if (effect.unless && this.tryPayUnless(effect.unless, players[0], context.source, context)) break if (effect.unless && this.tryPayUnless(effect.unless, players[0], context.source, context)) break
@@ -1751,7 +1947,7 @@ export class Game {
case 'search': { case 'search': {
const amount = Math.max(0, this.value(effect.amount, context)) const amount = Math.max(0, this.value(effect.amount, context))
for (const playerId of this.playersForEffect(effect.player, 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 break
} }
@@ -1835,10 +2031,87 @@ export class Game {
} }
break 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( private dig(
context: EffectContext, context: EffectContext,
effect: Extract<Effect, { op: 'dig' }>, effect: Extract<Effect, { op: 'dig' }>,
@@ -1965,6 +2238,7 @@ export class Game {
const defender = this.getPlayer(target.id) const defender = this.getPlayer(target.id)
defender.commanderDamage[source.id] = (defender.commanderDamage[source.id] ?? 0) + amount defender.commanderDamage[source.id] = (defender.commanderDamage[source.id] ?? 0) + amount
} }
this.getPlayer(target.id).damageTakenThisTurn += amount
this.loseLife(target.id, amount) this.loseLife(target.id, amount)
this.dispatchEvent({ kind: 'deals_damage', player: source.controller, subject: source, recipient: 'player', amount, combat }) this.dispatchEvent({ kind: 'deals_damage', player: source.controller, subject: source, recipient: 'player', amount, combat })
} else if (target.kind === 'object') { } else if (target.kind === 'object') {
@@ -2206,6 +2480,18 @@ export class Game {
return this.objectsMatching(target.selector, source) 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 { private applyEntersReplacements(object: GameObject): void {
for (const staticSource of this.staticAbilities()) { for (const staticSource of this.staticAbilities()) {
for (const effect of staticSource.ability.effects) { 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 { private hasRestriction(object: GameObject, rule: string): boolean {
for (const staticSource of this.staticAbilities()) { for (const staticSource of this.staticAbilities()) {
for (const effect of staticSource.ability.effects) { for (const effect of staticSource.ability.effects) {
@@ -2278,11 +2574,22 @@ export class Game {
return this.getPlayer(controller).attackedThisTurn return this.getPlayer(controller).attackedThisTurn
case 'you_attacked_this_turn': case 'you_attacked_this_turn':
return this.getPlayer(controller).attackedThisTurn 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': case 'no_objects':
return this.objectsMatching(condition.selector, source).length === 0 return this.objectsMatching(condition.selector, source).length === 0
case 'cards_in_hand_at_most': case 'cards_in_hand_at_most': {
return this.playersForValue(condition.who, this.staticContext(source)) const players = this.playersForValue(condition.who, this.staticContext(source))
.some(playerId => this.getPlayer(playerId).hand.length <= condition.atMost) 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': case 'on_battlefield':
return source.zone === 'battlefield' return source.zone === 'battlefield'
case 'in_graveyard': case 'in_graveyard':
@@ -2291,6 +2598,16 @@ export class Game {
return !source.isToken return !source.isToken
case 'full_party': case 'full_party':
return false 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: default:
return false return false
} }
@@ -2382,7 +2699,7 @@ export class Game {
} }
private hasMeaningfulAction(playerId: string): boolean { 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) const player = this.getPlayer(playerId)
if (player.lost) return false if (player.lost) return false
@@ -2420,6 +2737,7 @@ export class Game {
ability: Extract<Ability, { kind: 'activated' }>, ability: Extract<Ability, { kind: 'activated' }>,
): boolean { ): boolean {
if (source.zone !== 'battlefield' || source.controller !== playerId) return false 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.condition && !this.checkCondition(ability.condition, source)) return false
if (ability.timing === 'sorcery' && !this.isMainPhaseWithEmptyStack(playerId)) return false if (ability.timing === 'sorcery' && !this.isMainPhaseWithEmptyStack(playerId)) return false
if (ability.costs.some(cost => cost.kind === 'tap') && this.isCreature(source) if (ability.costs.some(cost => cost.kind === 'tap') && this.isCreature(source)
@@ -2553,6 +2871,7 @@ export class Game {
object.attacking = undefined object.attacking = undefined
object.blockedBy = [] object.blockedBy = []
object.blocking = undefined object.blocking = undefined
object.linkedExile = undefined
for (let index = this.continuousEffects.length - 1; index >= 0; index--) { for (let index = this.continuousEffects.length - 1; index >= 0; index--) {
const effect = this.continuousEffects[index] const effect = this.continuousEffects[index]
@@ -2687,6 +3006,7 @@ export class Game {
tapped: boolean, tapped: boolean,
shuffle: boolean, shuffle: boolean,
zones?: ('library' | 'graveyard')[], zones?: ('library' | 'graveyard')[],
split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean },
): void { ): void {
// shortcut: a search only pauses itself; later effects in the same ability // 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. // 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 if (this.pendingSearch) return
const player = this.getPlayer(playerId) const player = this.getPlayer(playerId)
let remaining = amount let remaining = amount
let first = true
while (remaining > 0) { while (remaining > 0) {
const pickDestination = first ? destination : (split?.destination ?? destination)
const pickTapped = first ? tapped : (split?.tapped ?? tapped)
const candidates = this.findSearchCandidates(playerId, selector, zones) const candidates = this.findSearchCandidates(playerId, selector, zones)
if (!candidates.length) break if (!candidates.length) break
if (candidates.length > 1) { 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 return
} }
this.moveSearchedCard(candidates[0], playerId, destination, tapped) this.moveSearchedCard(candidates[0], playerId, pickDestination, pickTapped)
remaining-- remaining--
first = false
} }
if (shuffle) this.shuffleLibrary(player) if (shuffle) this.shuffleLibrary(player)
} }
@@ -2712,14 +3045,20 @@ export class Game {
selector: ObjectSelector, selector: ObjectSelector,
zones?: ('library' | 'graveyard')[], zones?: ('library' | 'graveyard')[],
): GameObject[] { ): GameObject[] {
const player = this.getPlayer(playerId)
const source = this.playerSource(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 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) if (allowed.includes('graveyard')) ids.push(...player.graveyard)
return ids.map(id => this.getObject(id)) return ids.map(id => this.getObject(id)).filter(object => object.owner === playerId)
.filter(object => object.owner === playerId
&& this.matchesSelector(object, selector, source, object.zone))
} }
private moveSearchedCard( 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 { private shuffleLibrary(player: PlayerState): void {
for (let index = player.library.length - 1; index > 0; index--) { for (let index = player.library.length - 1; index > 0; index--) {
const swap = Math.floor(this.rng() * (index + 1)) const swap = Math.floor(this.rng() * (index + 1))
@@ -2774,13 +3130,16 @@ export class Game {
const typeLine = object.definition.typeLine.toLowerCase() const typeLine = object.definition.typeLine.toLowerCase()
const words = new Set(typeLine.split(/[\s—–\-/,()]+/).filter(Boolean)) const words = new Set(typeLine.split(/[\s—–\-/,()]+/).filter(Boolean))
if (selector.types?.length) { const matchesWords = (values: string[]): boolean => {
const matches = selector.types.map(type => words.has(type.toLowerCase())) const matches = values.map(value => words.has(value.toLowerCase()))
if (selector.match === 'any' ? !matches.some(Boolean) : !matches.every(Boolean)) return false 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.excludeTypes?.some(type => words.has(type.toLowerCase()))) return false
if (selector.supertypes?.some(type => !words.has(type.toLowerCase()))) return false if (selector.supertypes?.length && !matchesWords(selector.supertypes)) return false
if (selector.subtypes?.some(type => !words.has(type.toLowerCase()))) return false if (selector.subtypes?.length && !matchesWords(selector.subtypes)) return false
if (selector.controller === 'you' && object.controller !== source.controller) return false if (selector.controller === 'you' && object.controller !== source.controller) return false
if (selector.controller === 'opponent' && 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 if (selector.owner === 'opponent' && object.owner === source.controller) return false
const colors = object.definition.colors ?? [] 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.tapped !== undefined && object.tapped !== selector.tapped) return false
if (selector.attacking !== undefined && Boolean(object.attacking) !== selector.attacking) return false if (selector.attacking !== undefined && Boolean(object.attacking) !== selector.attacking) return false
if (selector.token !== undefined && object.isToken !== selector.token) return false if (selector.token !== undefined && object.isToken !== selector.token) return false
@@ -2886,6 +3248,7 @@ export class Game {
private requirePriority(playerId: string): void { private requirePriority(playerId: string): void {
if (this.status !== 'active') throw new GameError('Game is not active') 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.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') if (this.priority !== playerId) throw new GameError('You do not have priority')
} }

View File

@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'
import { getCard, type Card } from '../cards.js' import { getCard, type Card } from '../cards.js'
import { deletePlaymatImage, PlaymatError, scryfallArtUrl, storePlaymatImage } from '../images.js' import { deletePlaymatImage, PlaymatError, scryfallArtUrl, storePlaymatImage } from '../images.js'
import { getCardDefinition } from './catalog.js' import { getCardDefinition } from './catalog.js'
import { CREATURE_TYPES } from './creature-types.js'
import { validateCommanderDeck } from './commander.js' import { validateCommanderDeck } from './commander.js'
import { Game, GameError } from './game.js' import { Game, GameError } from './game.js'
import type { CardDefinition, GameObject, ManaPool, TargetChoice } from './types.js' import type { CardDefinition, GameObject, ManaPool, TargetChoice } from './types.js'
@@ -25,6 +26,8 @@ export interface ActionPayload {
targets?: TargetChoice[] targets?: TargetChoice[]
x?: number x?: number
mode?: number mode?: number
overload?: boolean
choice?: string
position?: { x?: unknown; y?: unknown } position?: { x?: unknown; y?: unknown }
attackers?: { attackerId: string; defenderId: string }[] attackers?: { attackerId: string; defenderId: string }[]
blocks?: { blockerId: string; attackerId: string }[] blocks?: { blockerId: string; attackerId: string }[]
@@ -54,6 +57,8 @@ export interface CardView {
attacking?: string attacking?: string
blockedBy: string[] blockedBy: string[]
blocking?: string blocking?: string
/** Creature type chosen as this permanent entered, if any. */
chosenType?: string
abilities: { index: number; kind: string; text?: string }[] abilities: { index: number; kind: string; text?: string }[]
/** Viewer-specific: can this card be played from hand right now? */ /** Viewer-specific: can this card be played from hand right now? */
playable?: boolean playable?: boolean
@@ -115,6 +120,17 @@ export interface MatchView {
remaining: number remaining: number
destination: string destination: string
cards: CardView[] 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, targets,
x: Number.isFinite(action.x) ? Number(action.x) : 0, x: Number.isFinite(action.x) ? Number(action.x) : 0,
mode: Number.isFinite(action.mode) ? Number(action.mode) : 0, mode: Number.isFinite(action.mode) ? Number(action.mode) : 0,
overload: action.overload === true,
} }
try { try {
@@ -425,6 +442,10 @@ export function performAction(matchId: string, token: string | undefined, action
case 'choose_search': case 'choose_search':
game.chooseSearchCard(seat.playerId, requireId(action.cardId)) game.chooseSearchCard(seat.playerId, requireId(action.cardId))
break break
case 'choose_type':
if (typeof action.choice !== 'string') throw new MatchError('Missing type choice')
game.chooseCreatureType(seat.playerId, action.choice)
break
case 'attack': case 'attack':
if (!Array.isArray(action.attackers)) throw new MatchError('Invalid attackers') if (!Array.isArray(action.attackers)) throw new MatchError('Invalid attackers')
game.declareAttackers(seat.playerId, action.attackers.map(entry => ({ game.declareAttackers(seat.playerId, action.attackers.map(entry => ({
@@ -490,6 +511,7 @@ function cardView(game: Game, object: GameObject, abilities = true): CardView {
attacking: object.attacking, attacking: object.attacking,
blockedBy: [...object.blockedBy], blockedBy: [...object.blockedBy],
blocking: object.blocking, blocking: object.blocking,
chosenType: object.chosenCreatureType,
abilities: abilities abilities: abilities
? (definition.abilities ?? []).map((ability, index) => ({ ? (definition.abilities ?? []).map((ability, index) => ({
index, index,
@@ -548,6 +570,7 @@ function serialize(match: Match, viewerId: string): MatchView {
const viewer = game.getPlayer(viewerId) const viewer = game.getPlayer(viewerId)
const search = game.pendingSearch const search = game.pendingSearch
const choice = game.pendingChoice
view.game = { view.game = {
turn: game.turn, turn: game.turn,
activePlayer: game.activePlayer, activePlayer: game.activePlayer,
@@ -568,6 +591,15 @@ function serialize(match: Match, viewerId: string): MatchView {
playable: game.canPlayCard(viewerId, id), playable: game.canPlayCard(viewerId, id),
})), })),
manaPool: { ...viewer.manaPool }, 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 pendingSearch: search
? { ? {
player: search.playerId, player: search.playerId,
@@ -576,6 +608,9 @@ function serialize(match: Match, viewerId: string): MatchView {
cards: search.playerId === viewerId cards: search.playerId === viewerId
? game.searchCandidates(viewerId).map(object => cardView(game, object, false)) ? game.searchCandidates(viewerId).map(object => cardView(game, object, false))
: [], : [],
...(search.playerId === viewerId
? { library: game.searchPool(viewerId).map(object => cardView(game, object, false)) }
: {}),
} }
: undefined, : undefined,
} }

View File

@@ -64,6 +64,8 @@ export interface PlayerState {
creaturesDiedThisTurn: number creaturesDiedThisTurn: number
nonlandPermanentsEnteredThisTurn: number nonlandPermanentsEnteredThisTurn: number
attackedThisTurn: boolean attackedThisTurn: boolean
creaturesAttackedThisTurn: number
damageTakenThisTurn: number
energy: number energy: number
poison: number poison: number
} }
@@ -90,6 +92,10 @@ export interface GameObject {
blocking?: string blocking?: string
attachments: string[] attachments: string[]
attachedTo?: 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 regenerationShields: number
activations: Record<number, number> activations: Record<number, number>
} }
@@ -118,6 +124,7 @@ export interface ActionOptions {
targets?: TargetChoice[] targets?: TargetChoice[]
x?: number x?: number
mode?: number mode?: number
overload?: boolean
} }
/** A search that is waiting for its player to pick one of several matching cards. */ /** A search that is waiting for its player to pick one of several matching cards. */
@@ -129,6 +136,15 @@ export interface PendingSearch {
tapped: boolean tapped: boolean
shuffle: boolean shuffle: boolean
zones?: ('library' | 'graveyard')[] 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 { export interface CombatAttack {

View File

@@ -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', () => { test('"it" refers to the triggering object when unambiguous', () => {
const [ability] = creature('Whenever another creature enters, put a +1/+1 counter on it.') const [ability] = creature('Whenever another creature enters, put a +1/+1 counter on it.')
assert.equal(ability.kind, 'triggered') 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', () => { 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.') 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') 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 } }, 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)
}
})

View File

@@ -127,6 +127,104 @@ test('permanents can be repositioned by their controller and positions are clear
assert.equal(bear.position, undefined) 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', () => { test('enters triggers from compiled card code fire and resolve through the stack', () => {
const soulWarden = card('Soul Warden', { const soulWarden = card('Soul Warden', {
typeLine: 'Creature — Human Cleric', 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)) 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', () => { test('autoAdvance stops instead of passing while a search needs a pick', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }]) const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start() 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.throws(() => game.activateAbility('p1', source.id, 0), GameError)
assert.equal(source.counters.spore, 1) 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)
})

View File

@@ -6,8 +6,10 @@ import {
deleteDeck, deleteDeck,
exportDeckText, exportDeckText,
loadDecks, loadDecks,
loadSharedDeck,
newDeckId, newDeckId,
saveDeck, saveDeck,
shareDeck,
type ApiCard, type ApiCard,
type DeckCard, type DeckCard,
type SavedDeck, type SavedDeck,
@@ -26,6 +28,8 @@ interface DraftDeck {
definePageMeta({ middleware: 'auth' }) definePageMeta({ middleware: 'auth' })
const { public: { apiBase } } = useRuntimeConfig() const { public: { apiBase } } = useRuntimeConfig()
const route = useRoute()
const router = useRouter()
const BASIC_NAMES = ['Plains', 'Island', 'Swamp', 'Mountain', 'Forest'] const BASIC_NAMES = ['Plains', 'Island', 'Swamp', 'Mountain', 'Forest']
const decks = ref<SavedDeck[]>([]) const decks = ref<SavedDeck[]>([])
@@ -43,6 +47,8 @@ const importErrors = ref<string[]>([])
const importing = ref(false) const importing = ref(false)
const basics = ref<Record<string, ApiCard>>({}) const basics = ref<Record<string, ApiCard>>({})
const showExport = ref(false) const showExport = ref(false)
const shareLink = ref('')
const shareCopied = ref(false)
const count = computed(() => 1 + (draft.value?.cards.length ?? 0)) const count = computed(() => 1 + (draft.value?.cards.length ?? 0))
const grouped = computed(() => { const grouped = computed(() => {
@@ -115,6 +121,30 @@ async function reloadDecks() {
decks.value = (await loadDecks(apiBase)).sort((a, b) => b.updatedAt - a.updatedAt) decks.value = (await loadDecks(apiBase)).sort((a, b) => b.updatedAt - a.updatedAt)
} }
async function share(deck: SavedDeck) {
error.value = ''
try {
const token = await shareDeck(apiBase, deck.id)
shareLink.value = `${window.location.origin}/decks?share=${token}`
shareCopied.value = false
} catch (caught) {
error.value = errorMessage(caught)
}
}
async function copyShareLink() {
try {
await navigator.clipboard.writeText(shareLink.value)
shareCopied.value = true
} catch {
shareCopied.value = false
}
}
function closeShare() {
shareLink.value = ''
}
function selectDeck(deck: SavedDeck) { function selectDeck(deck: SavedDeck) {
draft.value = { draft.value = {
id: deck.id, id: deck.id,
@@ -314,6 +344,27 @@ function errorMessage(caught: unknown): string {
onMounted(async () => { onMounted(async () => {
await reloadDecks() await reloadDecks()
const sharedToken = route.query.share
if (typeof sharedToken === 'string' && sharedToken) {
try {
const deck = await loadSharedDeck(apiBase, sharedToken)
draft.value = {
id: newDeckId(),
name: deck.name,
commander: { ...deck.commander },
cards: deck.cards.map(card => ({ ...card })),
cardBack: deck.cardBack ?? undefined,
}
notice.value = 'Shared deck loaded. Save it to add it to your account.'
} catch (caught) {
error.value = errorMessage(caught)
}
// Drop the token from the URL so a reload does not import the deck again.
const query = { ...route.query }
delete query.share
await router.replace({ query })
}
try { try {
const data = await $fetch<{ cards: (ApiCard | null)[] }>(`${apiBase}/cards/resolve`, { const data = await $fetch<{ cards: (ApiCard | null)[] }>(`${apiBase}/cards/resolve`, {
method: 'POST', method: 'POST',
@@ -519,33 +570,50 @@ onMounted(async () => {
</header> </header>
<section class="decks-panel"> <section class="decks-panel">
<p v-if="error" class="error">{{ error }}</p>
<p v-if="!decks.length" class="muted">No saved decks yet.</p> <p v-if="!decks.length" class="muted">No saved decks yet.</p>
<div class="deck-grid"> <div class="deck-grid">
<button type="button" class="deck-tile import-tile" @click="openImport"> <button type="button" class="deck-tile import-tile" @click="openImport">
<span class="plus" aria-hidden="true">+</span> <span class="plus" aria-hidden="true">+</span>
<span class="deck-name">Import deck</span> <span class="deck-name">Import deck</span>
</button> </button>
<button <div v-for="deck in decks" :key="deck.id" class="deck-cell">
v-for="deck in decks" <button type="button" class="deck-tile" @click="selectDeck(deck)">
:key="deck.id" <span class="deck-stack">
type="button" <img :src="commanderImage(deck)" :alt="`${deck.commander.name} card`" loading="lazy">
class="deck-tile"
@click="selectDeck(deck)"
>
<span class="deck-stack">
<img :src="commanderImage(deck)" :alt="`${deck.commander.name} card`" loading="lazy">
</span>
<span class="deck-name">{{ deck.name }}</span>
<span class="deck-meta">
<span class="tag" :class="deck.cards.length + 1 === 100 ? 'good' : 'bad'">
{{ deck.cards.length + 1 }}/100
</span> </span>
<span class="muted deck-commander">{{ deck.commander.name }}</span> <span class="deck-name">{{ deck.name }}</span>
</span> <span class="deck-meta">
</button> <span class="tag" :class="deck.cards.length + 1 === 100 ? 'good' : 'bad'">
{{ deck.cards.length + 1 }}/100
</span>
<span class="muted deck-commander">{{ deck.commander.name }}</span>
</span>
</button>
<button
type="button"
class="mini share-button"
:aria-label="`Share ${deck.name}`"
@click="share(deck)"
>Share</button>
</div>
</div> </div>
</section> </section>
<div v-if="shareLink" class="modal-backdrop" @click.self="closeShare">
<div class="modal">
<h2>Share deck</h2>
<p class="muted">Anyone with this link can view and import a copy of the deck.</p>
<input :value="shareLink" readonly aria-label="Share link">
<div class="row wrap modal-actions">
<button type="button" @click="closeShare">Done</button>
<button type="button" class="primary" @click="copyShareLink">
{{ shareCopied ? 'Copied' : 'Copy link' }}
</button>
</div>
</div>
</div>
<div v-if="importOpen" class="modal-backdrop" @click.self="closeImport"> <div v-if="importOpen" class="modal-backdrop" @click.self="closeImport">
<form class="modal" @submit.prevent="importDeck"> <form class="modal" @submit.prevent="importDeck">
<h2>Import deck</h2> <h2>Import deck</h2>
@@ -609,6 +677,21 @@ onMounted(async () => {
gap: 1rem; gap: 1rem;
} }
.deck-cell {
display: flex;
flex-direction: column;
gap: 0.4rem;
min-width: 0;
}
.deck-cell .deck-tile {
flex: 1;
}
.share-button {
align-self: flex-end;
}
.deck-tile { .deck-tile {
display: flex; display: flex;
flex-direction: column; flex-direction: column;

View File

@@ -34,6 +34,7 @@ interface CardView {
attacking?: string attacking?: string
blockedBy: string[] blockedBy: string[]
blocking?: string blocking?: string
chosenType?: string
abilities: AbilityView[] abilities: AbilityView[]
playable?: boolean playable?: boolean
} }
@@ -77,11 +78,19 @@ interface MatchView {
log: string[] log: string[]
hand: CardView[] hand: CardView[]
manaPool: Record<string, number> manaPool: Record<string, number>
pendingChoice?: {
player: string
what: string
sourceId: string
sourceName: string
options: string[]
}
pendingSearch?: { pendingSearch?: {
player: string player: string
remaining: number remaining: number
destination: string destination: string
cards: CardView[] cards: CardView[]
library?: CardView[]
} }
} }
} }
@@ -126,9 +135,10 @@ const connection = ref<'connecting' | 'live' | 'reconnecting' | 'offline'>('conn
const castCardId = ref('') const castCardId = ref('')
const selectedTarget = ref('') const selectedTarget = ref('')
const castX = ref(0) const castX = ref(0)
const castOverload = ref(false)
const selectedAttackers = ref<string[]>([]) const selectedAttackers = ref<string[]>([])
const attackTargets = reactive<Record<string, string>>({}) const attackTargets = reactive<Record<string, string>>({})
const defenderId = ref('') const attackDropId = ref('')
const blockSelection = reactive<Record<string, string>>({}) const blockSelection = reactive<Record<string, string>>({})
const selectedCardId = ref('') const selectedCardId = ref('')
const menu = ref<{ cardId: string; x: number; y: number } | null>(null) const menu = ref<{ cardId: string; x: number; y: number } | null>(null)
@@ -202,6 +212,7 @@ const opponents = computed(() => (state.value?.players ?? []).filter(player => p
const canAct = computed(() => Boolean(state.value?.status === 'active' const canAct = computed(() => Boolean(state.value?.status === 'active'
&& game.value && game.value
&& !game.value.pendingSearch && !game.value.pendingSearch
&& !game.value.pendingChoice
&& game.value.priority === viewerId.value)) && game.value.priority === viewerId.value))
const isActive = computed(() => game.value?.activePlayer === viewerId.value) const isActive = computed(() => game.value?.activePlayer === viewerId.value)
const priorityName = computed(() => playerName(game.value?.priority)) const priorityName = computed(() => playerName(game.value?.priority))
@@ -222,9 +233,15 @@ const attackWindow = computed(() => Boolean(state.value?.status === 'active'
&& !game.value.stack.length && !game.value.stack.length
&& (game.value.phase === 'precombat_main' && (game.value.phase === 'precombat_main'
|| (game.value.phase === 'combat' && game.value.step === 'declare_attackers')))) || (game.value.phase === 'combat' && game.value.step === 'declare_attackers'))))
const draggingAttackerId = computed(() => {
const cardId = dragPreview.value?.cardId
if (!attackWindow.value || !cardId) return ''
return myUntappedCreatures.value.some(card => card.id === cardId) ? cardId : ''
})
const blockWindow = computed(() => Boolean(state.value?.status === 'active' const blockWindow = computed(() => Boolean(state.value?.status === 'active'
&& game.value && game.value
&& !game.value.pendingSearch && !game.value.pendingSearch
&& !game.value.pendingChoice
&& game.value.step === 'declare_blockers' && game.value.step === 'declare_blockers'
&& game.value.priority === viewerId.value)) && game.value.priority === viewerId.value))
const castCard = computed(() => { const castCard = computed(() => {
@@ -232,7 +249,27 @@ const castCard = computed(() => {
return state.value.game?.hand.find(card => card.id === castCardId.value) return state.value.game?.hand.find(card => card.id === castCardId.value)
?? me.value?.command?.find(card => card.id === castCardId.value) ?? me.value?.command?.find(card => card.id === castCardId.value)
}) })
const overloadAbility = computed(() => castCard.value?.abilities.find(ability => ability.kind === 'overload'))
const pendingSearch = computed(() => game.value?.pendingSearch) const pendingSearch = computed(() => game.value?.pendingSearch)
const searchFilter = ref('')
const searchInput = ref<HTMLInputElement | null>(null)
const searchLegalIds = computed(() => new Set(pendingSearch.value?.cards.map(card => card.id) ?? []))
const searchLibrary = computed(() => pendingSearch.value?.library ?? pendingSearch.value?.cards ?? [])
const filteredSearchLibrary = computed(() => {
const query = searchFilter.value.trim().toLowerCase()
return query
? searchLibrary.value.filter(card => card.name.toLowerCase().includes(query))
: searchLibrary.value
})
const pendingChoice = computed(() => game.value?.pendingChoice)
const choiceFilter = ref('')
const choiceInput = ref<HTMLInputElement | null>(null)
const filteredChoiceOptions = computed(() => {
const query = choiceFilter.value.trim().toLowerCase()
return query
? (pendingChoice.value?.options ?? []).filter(option => option.toLowerCase().includes(query))
: (pendingChoice.value?.options ?? [])
})
const browseView = computed(() => { const browseView = computed(() => {
const zone = browsingZone.value const zone = browsingZone.value
const player = state.value?.players.find(entry => entry.id === zone?.playerId) const player = state.value?.players.find(entry => entry.id === zone?.playerId)
@@ -243,13 +280,13 @@ const browseView = computed(() => {
cards: (zone.zone === 'graveyard' ? player.graveyard : player.exile) ?? [], cards: (zone.zone === 'graveyard' ? player.graveyard : player.exile) ?? [],
} }
}) })
const sidebarOpen = computed(() => Boolean(pendingSearch.value const sidebarOpen = computed(() => Boolean((pendingSearch.value && pendingSearch.value.player !== viewerId.value)
|| (pendingChoice.value && pendingChoice.value.player !== viewerId.value)
|| castCard.value || castCard.value
|| browseView.value || browseView.value
|| playmatOpen.value || playmatOpen.value
|| attackWindow.value || attackWindow.value
|| blockWindow.value || blockWindow.value
|| game.value?.stack.length
|| showLog.value)) || showLog.value))
const searchDestination = computed(() => { const searchDestination = computed(() => {
switch (pendingSearch.value?.destination) { switch (pendingSearch.value?.destination) {
@@ -448,9 +485,6 @@ async function connect() {
const next = JSON.parse(event.data) as MatchView const next = JSON.parse(event.data) as MatchView
applyState(next) applyState(next)
connection.value = 'live' connection.value = 'live'
if (!defenderId.value || !next.players.some(player => player.id === defenderId.value)) {
defenderId.value = next.players.find(player => player.id !== next.viewerId)?.id ?? ''
}
} catch { } catch {
// Ignore malformed keepalive frames. // Ignore malformed keepalive frames.
} }
@@ -679,11 +713,26 @@ function moveCardPreview(event: PointerEvent) {
const marginX = Math.min(0.49, drag.halfWidth / rect.width) const marginX = Math.min(0.49, drag.halfWidth / rect.width)
const marginY = Math.min(0.49, drag.halfHeight / rect.height) const marginY = Math.min(0.49, drag.halfHeight / rect.height)
const clamp = (value: number, margin: number) => Math.min(1 - margin, Math.max(margin, value)) const clamp = (value: number, margin: number) => Math.min(1 - margin, Math.max(margin, value))
const x = (event.clientX - drag.grabX - rect.left) / rect.width
const y = (event.clientY - drag.grabY - rect.top) / rect.height
const attackDrag = Boolean(attackWindow.value && myUntappedCreatures.value.some(card => card.id === drag.cardId))
dragPreview.value = { dragPreview.value = {
cardId: drag.cardId, cardId: drag.cardId,
x: clamp((event.clientX - drag.grabX - rect.left) / rect.width, marginX), x: attackDrag ? x : clamp(x, marginX),
y: clamp((event.clientY - drag.grabY - rect.top) / rect.height, marginY), y: attackDrag ? y : clamp(y, marginY),
} }
attackDropId.value = attackDropTargetAt(drag.cardId, event.clientX, event.clientY)
}
/** Topmost opponent panel under the pointer, ignoring the card being dragged. */
function attackDropTargetAt(cardId: string, x: number, y: number): string {
if (!attackWindow.value || !myUntappedCreatures.value.some(card => card.id === cardId)) return ''
for (const element of document.elementsFromPoint(x, y)) {
const panel = element.closest<HTMLElement>('.player')
const id = panel?.dataset.playerId
if (id && opponents.value.some(player => player.id === id)) return id
}
return ''
} }
async function endCardMove(event: PointerEvent) { async function endCardMove(event: PointerEvent) {
@@ -692,16 +741,30 @@ async function endCardMove(event: PointerEvent) {
cardDrag = null cardDrag = null
const preview = dragPreview.value const preview = dragPreview.value
dragPreview.value = null dragPreview.value = null
const attackTarget = attackDropTargetAt(drag.cardId, event.clientX, event.clientY)
attackDropId.value = ''
if (!drag.moved || !preview) return if (!drag.moved || !preview) return
// The click that follows a drag must not open the ability menu. // The click that follows a drag must not open the ability menu.
suppressCardClick = drag.cardId suppressCardClick = drag.cardId
setTimeout(() => { suppressCardClick = '' }, 0) setTimeout(() => { suppressCardClick = '' }, 0)
if (attackTarget) {
if (!selectedAttackers.value.includes(drag.cardId)) selectedAttackers.value.push(drag.cardId)
attackTargets[drag.cardId] = attackTarget
return
}
const target = myBattlefield.value.find(card => card.id === drag.cardId) const target = myBattlefield.value.find(card => card.id === drag.cardId)
if (!target) return if (!target) return
const rect = drag.board.getBoundingClientRect()
const marginX = Math.min(0.49, drag.halfWidth / rect.width)
const marginY = Math.min(0.49, drag.halfHeight / rect.height)
const previous = target.position const previous = target.position
target.position = { x: preview.x, y: preview.y } target.position = {
x: Math.min(1 - marginX, Math.max(marginX, preview.x)),
y: Math.min(1 - marginY, Math.max(marginY, preview.y)),
}
const ok = await act({ const ok = await act({
type: 'move_permanent', type: 'move_permanent',
cardId: drag.cardId, cardId: drag.cardId,
@@ -714,18 +777,21 @@ function cancelCardMove(event: PointerEvent) {
if (cardDrag?.pointerId !== event.pointerId) return if (cardDrag?.pointerId !== event.pointerId) return
cardDrag = null cardDrag = null
dragPreview.value = null dragPreview.value = null
attackDropId.value = ''
} }
function openCast(card: CardView) { function openCast(card: CardView) {
castCardId.value = card.id castCardId.value = card.id
selectedTarget.value = '' selectedTarget.value = ''
castX.value = 0 castX.value = 0
castOverload.value = false
error.value = '' error.value = ''
} }
function cancelCast() { function cancelCast() {
castCardId.value = '' castCardId.value = ''
selectedTarget.value = '' selectedTarget.value = ''
castOverload.value = false
} }
async function confirmCast() { async function confirmCast() {
@@ -736,6 +802,7 @@ async function confirmCast() {
cardId: castCard.value.id, cardId: castCard.value.id,
targets: target ? [target] : [], targets: target ? [target] : [],
x: castX.value, x: castX.value,
overload: castOverload.value,
}) })
if (ok) cancelCast() if (ok) cancelCast()
} }
@@ -750,19 +817,34 @@ async function activateFromMenu(card: CardView, ability: AbilityView) {
} }
async function chooseSearchCard(card: CardView) { async function chooseSearchCard(card: CardView) {
if (busy.value || !searchLegalIds.value.has(card.id)) return
await act({ type: 'choose_search', cardId: card.id }) await act({ type: 'choose_search', cardId: card.id })
} }
async function chooseCreatureType(type: string) {
if (busy.value) return
await act({ type: 'choose_type', choice: type })
}
async function attack() { async function attack() {
if (!selectedAttackers.value.length) return const attackers = selectedAttackers.value
const ok = await act({ .filter(attackerId => attackTargets[attackerId])
type: 'attack', .map(attackerId => ({ attackerId, defenderId: attackTargets[attackerId] }))
attackers: selectedAttackers.value.map(attackerId => ({ if (!attackers.length) return
attackerId, const ok = await act({ type: 'attack', attackers })
defenderId: attackTargets[attackerId] || defenderId.value, if (ok) {
})), selectedAttackers.value = []
}) for (const key of Object.keys(attackTargets)) delete attackTargets[key]
if (ok) selectedAttackers.value = [] }
}
function removeAttacker(cardId: string) {
selectedAttackers.value = selectedAttackers.value.filter(id => id !== cardId)
delete attackTargets[cardId]
}
function attackerName(cardId: string): string {
return myUntappedCreatures.value.find(card => card.id === cardId)?.name ?? 'Creature'
} }
async function declareBlocks() { async function declareBlocks() {
@@ -887,10 +969,25 @@ function resetAnimations() {
watch(() => game.value?.step, () => { watch(() => game.value?.step, () => {
selectedAttackers.value = [] selectedAttackers.value = []
attackDropId.value = ''
for (const key of Object.keys(attackTargets)) delete attackTargets[key] for (const key of Object.keys(attackTargets)) delete attackTargets[key]
for (const key of Object.keys(blockSelection)) delete blockSelection[key] for (const key of Object.keys(blockSelection)) delete blockSelection[key]
}) })
watch(() => Boolean(pendingSearch.value), async active => {
if (!active) return
searchFilter.value = ''
await nextTick()
searchInput.value?.focus()
})
watch(() => pendingChoice.value?.sourceId, async sourceId => {
if (!sourceId) return
choiceFilter.value = ''
await nextTick()
choiceInput.value?.focus()
})
onMounted(async () => { onMounted(async () => {
window.addEventListener('keydown', onKeydown) window.addEventListener('keydown', onKeydown)
decks.value = (await loadDecks(apiBase)).sort((a, b) => b.updatedAt - a.updatedAt) decks.value = (await loadDecks(apiBase)).sort((a, b) => b.updatedAt - a.updatedAt)
@@ -1065,11 +1162,14 @@ onUnmounted(() => {
v-for="(player, playerIndex) in state.players" v-for="(player, playerIndex) in state.players"
:key="player.id" :key="player.id"
class="panel player" class="panel player"
:data-player-id="player.id"
:class="{ :class="{
current: game.activePlayer === player.id, current: game.activePlayer === player.id,
dead: player.lost, dead: player.lost,
'anim-hit': playerHitAnimations[player.id], 'anim-hit': playerHitAnimations[player.id],
'anim-heal': playerHealAnimations[player.id], 'anim-heal': playerHealAnimations[player.id],
'attack-ready': draggingAttackerId && player.id !== viewerId && !player.lost,
'drop-hover': attackDropId === player.id,
}" }"
> >
<header class="player-head"> <header class="player-head">
@@ -1166,6 +1266,7 @@ onUnmounted(() => {
positioned: isPositioned(card), positioned: isPositioned(card),
dragging: dragPreview?.cardId === card.id, dragging: dragPreview?.cardId === card.id,
movable: card.controller === viewerId, movable: card.controller === viewerId,
'pending-attack': attackTargets[card.id],
'anim-enter': cardEnterAnimations[card.id], 'anim-enter': cardEnterAnimations[card.id],
'anim-damage': cardDamageAnimations[card.id], 'anim-damage': cardDamageAnimations[card.id],
'anim-attack': cardAttackAnimations[card.id], 'anim-attack': cardAttackAnimations[card.id],
@@ -1185,7 +1286,16 @@ onUnmounted(() => {
<CardHover :oracle-id="card.oracleId" :name="card.name"> <CardHover :oracle-id="card.oracleId" :name="card.name">
<GameCard :oracle-id="card.oracleId" :name="card.name" :tapped="card.tapped"> <GameCard :oracle-id="card.oracleId" :name="card.name" :tapped="card.tapped">
<span v-if="card.isCommander" class="overlay-tag commander" title="Commander">♛</span> <span v-if="card.isCommander" class="overlay-tag commander" title="Commander">♛</span>
<span v-if="card.attacking" class="overlay-tag attacking" title="Attacking">⚔</span> <span
v-if="card.chosenType"
class="overlay-tag chosen"
:title="`Chosen creature type: ${card.chosenType}`"
>{{ card.chosenType }}</span>
<span
v-if="card.attacking || attackTargets[card.id]"
class="overlay-tag attacking"
:title="`Attacking ${playerName(card.attacking || attackTargets[card.id])}`"
>⚔</span>
<span v-if="card.damage" class="overlay-tag card-damage" title="Damage">−{{ card.damage }}</span> <span v-if="card.damage" class="overlay-tag card-damage" title="Damage">−{{ card.damage }}</span>
<span v-if="card.power !== undefined" class="stats">{{ card.power }}/{{ card.toughness }}</span> <span v-if="card.power !== undefined" class="stats">{{ card.power }}/{{ card.toughness }}</span>
<div v-if="Object.keys(card.counters).length" class="overlay-counters"> <div v-if="Object.keys(card.counters).length" class="overlay-counters">
@@ -1228,6 +1338,28 @@ onUnmounted(() => {
</div> </div>
</section> </section>
<section class="stack-pile" :class="{ empty: !game.stack.length }" aria-live="polite" aria-label="Stack">
<h2 v-if="game.stack.length" class="stack-heading">
Stack <span class="muted">{{ game.stack.length }}</span>
</h2>
<TransitionGroup name="stack" tag="ol" class="stack-pile-list">
<li
v-for="(item, index) in [...game.stack].reverse()"
:key="item.id"
class="stack-card"
:class="[`kind-${item.kind}`, { 'is-top': index === 0 }]"
:style="{ zIndex: game.stack.length - index }"
:title="item.label"
>
<span class="stack-glyph" aria-hidden="true">{{ item.kind === 'spell' ? '✦' : '⟳' }}</span>
<span class="stack-copy">
<strong><SymbolText :text="item.label" /></strong>
<span class="muted">{{ playerName(item.controller) }}</span>
</span>
</li>
</TransitionGroup>
</section>
<section class="hand-panel"> <section class="hand-panel">
<div class="row wrap hand-head"> <div class="row wrap hand-head">
<h2>Your hand</h2> <h2>Your hand</h2>
@@ -1312,33 +1444,16 @@ onUnmounted(() => {
</div> </div>
</section> </section>
<section v-if="pendingSearch" class="panel side search-panel"> <section v-if="pendingSearch && pendingSearch.player !== viewerId" class="panel side search-panel">
<div class="row"> <h2>Search</h2>
<h2 class="grow">Search your library</h2> <p class="muted">{{ playerName(pendingSearch.player) }} is searching their library.</p>
<span v-if="pendingSearch.remaining > 1" class="tag">{{ pendingSearch.remaining }} left</span> </section>
</div>
<p v-if="pendingSearch.player === viewerId" class="muted"> <section v-if="pendingChoice && pendingChoice.player !== viewerId" class="panel side search-panel">
Choose a card to put {{ searchDestination }}. <h2>Choose a type</h2>
<p class="muted">
{{ playerName(pendingChoice.player) }} is choosing a creature type for {{ pendingChoice.sourceName }}.
</p> </p>
<p v-else class="muted">
{{ playerName(pendingSearch.player) }} is searching their library.
</p>
<div v-if="pendingSearch.cards.length" class="search-picks">
<button
v-for="card in pendingSearch.cards"
:key="card.id"
type="button"
class="search-pick"
:disabled="busy"
:title="`Choose ${card.name}`"
@click="chooseSearchCard(card)"
>
<CardHover :oracle-id="card.oracleId" :name="card.name">
<GameCard :oracle-id="card.oracleId" :name="card.name" />
</CardHover>
<span class="search-name">{{ card.name }}</span>
</button>
</div>
</section> </section>
<section v-if="castCard" class="panel side cast-panel"> <section v-if="castCard" class="panel side cast-panel">
@@ -1351,6 +1466,10 @@ onUnmounted(() => {
<ManaCost v-if="castCard.manaCost" :cost="castCard.manaCost" /> <ManaCost v-if="castCard.manaCost" :cost="castCard.manaCost" />
</p> </p>
<p v-if="castCard.oracleText" class="oracle small"><SymbolText :text="castCard.oracleText" /></p> <p v-if="castCard.oracleText" class="oracle small"><SymbolText :text="castCard.oracleText" /></p>
<label v-if="overloadAbility" class="row">
<input v-model="castOverload" type="checkbox">
<span>{{ overloadAbility.text ?? 'Overload' }}</span>
</label>
<label class="field"> <label class="field">
<span class="muted">Target</span> <span class="muted">Target</span>
<select v-model="selectedTarget"> <select v-model="selectedTarget">
@@ -1368,26 +1487,21 @@ onUnmounted(() => {
<section v-if="attackWindow" class="panel side"> <section v-if="attackWindow" class="panel side">
<h2>Attack</h2> <h2>Attack</h2>
<p class="muted">Choose creatures and who each one attacks.</p> <p class="muted">Drag an untapped creature onto a player to attack them.</p>
<div v-for="card in myUntappedCreatures" :key="card.id" class="check-row"> <div v-if="selectedAttackers.length" class="attack-list">
<input v-model="selectedAttackers" type="checkbox" :value="card.id"> <button
<span class="grow"> v-for="attackerId in selectedAttackers"
{{ card.name }} <span class="muted">{{ card.power }}/{{ card.toughness }}</span> :key="attackerId"
</span> type="button"
<select v-if="selectedAttackers.includes(card.id)" v-model="attackTargets[card.id]"> class="attack-pick"
<option v-for="player in opponents" :key="player.id" :value="player.id"> :title="`Remove ${attackerName(attackerId)} from the attack`"
{{ player.name }} @click="removeAttacker(attackerId)"
</option> >
</select> <span>{{ attackerName(attackerId) }}</span>
<span class="muted">⚔ {{ playerName(attackTargets[attackerId]) }} ✕</span>
</button>
</div> </div>
<label class="field"> <p v-else class="muted">No attackers chosen yet.</p>
<span class="muted">Default defender</span>
<select v-model="defenderId">
<option v-for="player in opponents" :key="player.id" :value="player.id">
{{ player.name }}
</option>
</select>
</label>
<button type="button" :disabled="busy || !selectedAttackers.length" @click="attack"> <button type="button" :disabled="busy || !selectedAttackers.length" @click="attack">
Attack with {{ selectedAttackers.length }} Attack with {{ selectedAttackers.length }}
</button> </button>
@@ -1410,15 +1524,6 @@ onUnmounted(() => {
</button> </button>
</section> </section>
<section v-if="game.stack.length" class="panel side"> <h2>Stack</h2>
<ol class="stack-list">
<li v-for="item in [...game.stack].reverse()" :key="item.id">
<strong><SymbolText :text="item.label" /></strong>
<span class="muted">{{ playerName(item.controller) }}</span>
</li>
</ol>
</section>
<section v-if="showLog" class="panel side log-panel"> <section v-if="showLog" class="panel side log-panel">
<h2>Log</h2> <h2>Log</h2>
<ul class="log-list"> <ul class="log-list">
@@ -1445,6 +1550,83 @@ onUnmounted(() => {
>End turn</button> >End turn</button>
</div> </div>
<Teleport to="body">
<div v-if="pendingChoice?.player === viewerId" class="search-backdrop">
<section class="search-modal" role="dialog" aria-modal="true" aria-labelledby="choice-title">
<header class="search-head">
<div class="grow">
<h2 id="choice-title">Choose a creature type</h2>
<p class="muted">{{ pendingChoice.sourceName }} enters.</p>
</div>
<span class="tag">{{ filteredChoiceOptions.length }} types</span>
</header>
<input
ref="choiceInput"
v-model="choiceFilter"
class="search-filter"
type="search"
placeholder="Search creature types"
autocomplete="off"
>
<p v-if="!filteredChoiceOptions.length" class="muted">No creature types match “{{ choiceFilter }}”.</p>
<div v-else class="choice-grid">
<button
v-for="type in filteredChoiceOptions"
:key="type"
type="button"
class="choice-option"
:disabled="busy"
@click="chooseCreatureType(type)"
>{{ type }}</button>
</div>
</section>
</div>
</Teleport>
<Teleport to="body">
<div v-if="pendingSearch?.player === viewerId" class="search-backdrop">
<section class="search-modal" role="dialog" aria-modal="true" aria-labelledby="search-title">
<header class="search-head">
<div class="grow">
<h2 id="search-title">Search your library</h2>
<p class="muted">
Choose a card to put {{ searchDestination }}.
<template v-if="pendingSearch.remaining > 1">({{ pendingSearch.remaining }} picks left)</template>
</p>
</div>
<span class="tag">{{ searchLegalIds.size }} can be chosen</span>
</header>
<input
ref="searchInput"
v-model="searchFilter"
class="search-filter"
type="search"
placeholder="Search by card name"
autocomplete="off"
>
<p v-if="!filteredSearchLibrary.length" class="muted">No cards match “{{ searchFilter }}”.</p>
<div v-else class="search-library">
<button
v-for="card in filteredSearchLibrary"
:key="card.id"
type="button"
class="search-card"
:class="{ legal: searchLegalIds.has(card.id) }"
:disabled="!searchLegalIds.has(card.id) || busy"
:title="searchLegalIds.has(card.id) ? `Choose ${card.name}` : `${card.name} does not match this search`"
@click="chooseSearchCard(card)"
>
<CardHover :oracle-id="card.oracleId" :name="card.name">
<GameCard :oracle-id="card.oracleId" :name="card.name" />
</CardHover>
<span class="search-name">{{ card.name }}</span>
</button>
</div>
<p class="muted small">Cards that do not match this search are dimmed.</p>
</section>
</div>
</Teleport>
<Teleport to="body"> <Teleport to="body">
<template v-if="menuOpen"> <template v-if="menuOpen">
<div class="menu-backdrop" @pointerdown="menuOpen = false" /> <div class="menu-backdrop" @pointerdown="menuOpen = false" />
@@ -1735,6 +1917,16 @@ onUnmounted(() => {
border-color: var(--accent); border-color: var(--accent);
} }
.player.attack-ready {
border-style: dashed;
border-color: var(--bad);
}
.player.drop-hover {
border-color: var(--bad);
box-shadow: inset 0 0 0 3px var(--bad), 0 0 24px rgb(224 122 122 / 35%);
}
.player.dead { .player.dead {
opacity: 0.6; opacity: 0.6;
} }
@@ -2077,6 +2269,12 @@ onUnmounted(() => {
outline-offset: 2px; outline-offset: 2px;
} }
.perm.pending-attack .game-card {
border-radius: 6px;
outline: 2px solid var(--bad);
outline-offset: 2px;
}
.perm:focus-visible { .perm:focus-visible {
outline: none; outline: none;
} }
@@ -2114,6 +2312,16 @@ onUnmounted(() => {
color: var(--warn); color: var(--warn);
} }
.overlay-tag.chosen {
bottom: 0.2rem;
left: 50%;
transform: translateX(-50%);
max-width: 80%;
overflow: hidden;
text-overflow: ellipsis;
color: var(--accent);
}
.overlay-tag.attacking { .overlay-tag.attacking {
top: 0.2rem; top: 0.2rem;
right: 0.2rem; right: 0.2rem;
@@ -2268,24 +2476,76 @@ onUnmounted(() => {
overflow-y: auto; overflow-y: auto;
} }
.search-picks { .search-backdrop {
position: fixed;
inset: 0;
z-index: 70;
display: grid; display: grid;
grid-template-columns: repeat(auto-fill, minmax(5.5rem, 1fr)); place-items: center;
gap: 0.4rem; padding: 1rem;
background: rgb(0 0 0 / 65%);
} }
.search-pick { .search-modal {
display: flex;
flex-direction: column;
gap: 0.75rem;
width: min(60rem, 100%);
max-height: calc(100vh - 2rem);
padding: 1rem;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 12px;
}
.search-head {
display: flex;
align-items: flex-start;
gap: 0.75rem;
}
.search-head h2,
.search-head p {
margin: 0;
}
.search-filter {
width: 100%;
flex: 0 0 auto;
}
.search-library {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(6.2rem, 1fr));
gap: 0.5rem;
min-height: 0;
flex: 1 1 auto;
overflow-y: auto;
}
.search-card {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.25rem; gap: 0.25rem;
padding: 0.25rem; padding: 0.25rem;
border-color: transparent;
opacity: 0.35;
text-align: center; text-align: center;
} }
.search-pick:hover:not(:disabled) { .search-card.legal {
border-color: var(--line);
opacity: 1;
}
.search-card.legal:hover:not(:disabled) {
border-color: var(--accent); border-color: var(--accent);
} }
.search-card:disabled {
cursor: not-allowed;
}
.search-name { .search-name {
overflow: hidden; overflow: hidden;
font-size: 0.72rem; font-size: 0.72rem;
@@ -2293,18 +2553,37 @@ onUnmounted(() => {
white-space: nowrap; white-space: nowrap;
} }
.check-row { .choice-grid {
display: flex; display: grid;
align-items: center; grid-template-columns: repeat(auto-fill, minmax(7rem, 1fr));
gap: 0.4rem; gap: 0.35rem;
font-size: 0.85rem; min-height: 0;
flex: 1 1 auto;
overflow-y: auto;
} }
.check-row select { .choice-option {
width: auto; font-size: 0.78rem;
flex: 0 0 auto; }
font-size: 0.75rem;
padding: 0.15rem 0.3rem; .attack-list {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.attack-pick {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
width: 100%;
font-size: 0.8rem;
text-align: left;
}
.attack-pick:hover {
border-color: var(--bad);
} }
.block-row { .block-row {
@@ -2465,17 +2744,134 @@ onUnmounted(() => {
transform: translateY(2.5em) scale(0.7); transform: translateY(2.5em) scale(0.7);
} }
.stack-list { .stack-pile {
margin: 0; position: absolute;
padding-left: 1.2rem; top: 5rem;
right: 24rem;
z-index: 22;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.25rem; gap: 0.35rem;
font-size: 0.85rem; width: min(15rem, calc(100% - 2rem));
pointer-events: none;
transition: opacity 160ms ease;
} }
.stack-list > li > span { .stack-pile.empty {
display: block; opacity: 0;
}
.stack-heading {
display: flex;
gap: 0.4rem;
align-items: baseline;
margin: 0;
font-size: 0.72rem;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--muted);
}
.stack-pile-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
.stack-pile-list > li + li {
margin-top: -2.9rem;
}
.stack-card {
display: flex;
align-items: center;
gap: 0.5rem;
min-height: 4.4rem;
padding: 0.5rem 0.65rem;
border: 1px solid #3c4d64;
border-left: 3px solid var(--accent);
border-radius: 8px;
background: #141a24;
box-shadow: 0 8px 18px rgb(0 0 0 / 50%);
transition: transform 260ms cubic-bezier(0.2, 0.8, 0.2, 1), box-shadow 220ms ease;
}
.stack-card.kind-ability {
border-left-color: #c9a86a;
}
.stack-card.is-top {
border-color: rgb(122 162 247 / 65%);
box-shadow:
0 0 0 1px rgb(122 162 247 / 25%),
0 0 20px rgb(122 162 247 / 25%),
0 10px 24px rgb(0 0 0 / 55%);
}
.stack-card.kind-ability.is-top {
border-color: rgb(201 168 106 / 60%);
box-shadow:
0 0 0 1px rgb(201 168 106 / 22%),
0 0 20px rgb(201 168 106 / 20%),
0 10px 24px rgb(0 0 0 / 55%);
}
.stack-glyph {
flex: 0 0 auto;
font-size: 1.05rem;
color: var(--accent);
}
.kind-ability .stack-glyph {
color: #c9a86a;
}
.stack-copy {
display: flex;
flex-direction: column;
gap: 0.1rem;
min-width: 0;
line-height: 1.2;
}
.stack-copy strong {
display: -webkit-box;
overflow: hidden;
font-size: 0.8rem;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.stack-copy .muted {
overflow: hidden;
font-size: 0.68rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.stack-enter-active {
transition: transform 300ms cubic-bezier(0.2, 0.9, 0.25, 1.15), opacity 200ms ease, filter 300ms ease;
}
.stack-leave-active {
transition: transform 200ms ease-in, opacity 180ms ease-in;
}
.stack-enter-from {
opacity: 0;
filter: brightness(1.9);
transform: translate(4rem, -1.2rem) rotate(6deg) scale(0.82);
}
.stack-leave-to {
opacity: 0;
transform: translate(3rem, -0.8rem) rotate(3deg) scale(0.9);
}
.stack-move {
transition: transform 280ms cubic-bezier(0.2, 0.8, 0.2, 1);
} }
.log-panel { .log-panel {
@@ -2514,6 +2910,12 @@ onUnmounted(() => {
.mana-burst { .mana-burst {
animation: none; animation: none;
} }
.stack-enter-active,
.stack-leave-active,
.stack-move {
transition: none;
}
} }
@media (max-width: 1000px) { @media (max-width: 1000px) {
@@ -2589,6 +2991,15 @@ onUnmounted(() => {
overflow: visible; overflow: visible;
} }
.stack-pile {
position: static;
width: auto;
}
.stack-pile.empty {
display: none;
}
.hand-panel { .hand-panel {
position: static; position: static;
width: auto; width: auto;

View File

@@ -83,6 +83,21 @@ export async function deleteDeck(apiBase: string, id: string): Promise<void> {
}) })
} }
export async function shareDeck(apiBase: string, id: string): Promise<string> {
const { token } = await $fetch<{ token: string }>(
`${apiBase}/me/decks/${encodeURIComponent(id)}/share`,
{ method: 'POST', headers: authHeaders() },
)
return token
}
export async function loadSharedDeck(apiBase: string, token: string): Promise<SavedDeck> {
const { deck } = await $fetch<{ deck: SavedDeck }>(
`${apiBase}/decks/share/${encodeURIComponent(token)}`,
)
return deck
}
export function isBasicLand(card: DeckCard): boolean { export function isBasicLand(card: DeckCard): boolean {
return /\bbasic\b/i.test(card.typeLine) && /\bland\b/i.test(card.typeLine) return /\bbasic\b/i.test(card.typeLine) && /\bland\b/i.test(card.typeLine)
} }