Fa triggers malament

This commit is contained in:
2026-10-29 20:30:29 +01:00
parent bc05b63083
commit 9ec486274f
16 changed files with 2287 additions and 128 deletions

View File

@@ -162,7 +162,7 @@ permanents.withType('creature').withSubtype('dragon').withColor('red')
``` ```
Available filters include `withType`, `withSubtype`, `withSupertype`, Available filters include `withType`, `withSubtype`, `withSupertype`,
`withColor`, `withKeyword`, `withoutKeyword`, `withoutType`, `other`, `tapped`, `withColor`, `withoutColor`, `withKeyword`, `withoutKeyword`, `withoutType`, `other`, `tapped`,
`untapped`, `attacking`, `token`, `nontoken`, `equipped`, `enchanted`, `untapped`, `attacking`, `token`, `nontoken`, `equipped`, `enchanted`,
`youControl`, `opponentControls`, `controlledBy`, `ownedBy`, `named`, `youControl`, `opponentControls`, `controlledBy`, `ownedBy`, `named`,
`inZone`, `withCounter`, `powerAtLeast`/`powerAtMost`, `inZone`, `withCounter`, `powerAtLeast`/`powerAtMost`,
@@ -198,6 +198,7 @@ damage(target(permanents.withType('creature')), 3)
draw(you, 2) draw(you, 2)
gainLife(you, 1) gainLife(you, 1)
createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1 })) createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1 }))
createToken(you, 1, token({ name: 'Monster', types: ['enchantment'], subtypes: ['aura', 'role'] }), { attachTo: target(permanents.withType('creature')) })
putCounters(target(permanents.withType('creature')), '+1/+1', 2) putCounters(target(permanents.withType('creature')), '+1/+1', 2)
destroy(target(permanents.withType('creature'))) destroy(target(permanents.withType('creature')))
addMana(you, mana('{G}{G}')) addMana(you, mana('{G}{G}'))
@@ -213,8 +214,9 @@ the cost builders in `source.ts`.
Static effects are also distinct, so their AST shape is unambiguous: Static effects are also distinct, so their AST shape is unambiguous:
`staticPump`, `staticGrant`, `staticRestrict`, `staticSetPt`, `grantAbility`, `staticPump`, `staticGrant`, `staticRestrict`, `staticSetPt`, `grantAbility`,
`entersTapped`, `entersWithCounters`, `control`, `choose`, `replace`, `entersTapped`, `entersWithCounters`, `control`, `choose`, `replace`,
`costReduction`, `costIncrease`, `searchRestriction` and `costReduction`, `costIncrease`, `searchRestriction`,
`exileInsteadOfGraveyard`. `entersTapped` takes an optional `unlessCost` builder `exileInsteadOfGraveyard` and `tokenMultiplier` (with optional
`who: 'each_player'` or `creatureOnly: true`). `entersTapped` takes an optional `unlessCost` builder
for "you may pay N life; if you don't, it enters tapped": for "you may pay N life; if you don't, it enters tapped":
`entersTapped(self, { unlessCost: payLife(2) })`. `entersTapped(self, { unlessCost: payLife(2) })`.
@@ -339,7 +341,7 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities:
| `pump` | `target`, `power`, `toughness`, `duration` | | `pump` | `target`, `power`, `toughness`, `duration` |
| `grant` | `target`, `keyword`, optional `value`, `duration` | | `grant` | `target`, `keyword`, optional `value`, `duration` |
| `put_counters`, `remove_counters` | `target`, `counter`, `amount` | | `put_counters`, `remove_counters` | `target`, `counter`, `amount` |
| `create_token` | `player`, `amount`, `token` | | `create_token` | `player`, `amount`, `token`, optional `attachTo` target |
| `destroy`, `exile`, `tap`, `untap`, `regenerate` | `target` | | `destroy`, `exile`, `tap`, `untap`, `regenerate` | `target` |
| `sacrifice` | `player`, `target`, optional `unless` cost | | `sacrifice` | `player`, `target`, optional `unless` cost |
| `counter` | `what`, `target`, optional `unless` cost | | `counter` | `what`, `target`, optional `unless` cost |
@@ -351,11 +353,18 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities:
| `energy` | `player`, `amount` | | `energy` | `player`, `amount` |
| `attach` | target to attach this/trigger object to | | `attach` | target to attach this/trigger object to |
| `restriction` | target, rule, duration | | `restriction` | target, rule, duration |
| `keyword_action` | `action`, optional `amount`, `detail`, `target` | | `keyword_action` | `action`, optional `amount`, `detail`, `target`; the engine implements `explore`, `incubate`, and `impulse` |
| `proliferate` | no payload | | `proliferate` | no payload |
| `hideaway` | `amount`; exiles the top card and links it to the source | | `hideaway` | `amount`; looks at that many cards and pauses for the controller to exile one face down, linking it to the source |
| `play_exiled` | `player`, optional `free`; plays a card linked with `hideaway` | | `play_exiled` | `player`, optional `free`; plays a card linked with `hideaway` |
| `exile_graveyards` | no payload; exiles all cards from every graveyard | | `exile_graveyards` | no payload; exiles all cards from every graveyard |
| `transform` | `target`; swaps the object's front and back faces |
A created token whose name or subtype matches one of the predefined tokens in
comprehensive rules 111.10 gets that token's full characteristics and abilities
from `src/game/tokens.ts`. The compiled `token` spec only needs enough information
to identify it, for example `token({ subtypes: ['treasure'] })` or
`token({ name: 'Monster', subtypes: ['aura', 'role'] })` for a Role.
### Targets, values, costs ### Targets, values, costs

View File

@@ -65,17 +65,19 @@ const bolt: CardDefinition = {
| `putOnBottom(playerId, cardId)` | Puts one chosen card from a mulliganed opening hand on the bottom of its owner's library. | | `putOnBottom(playerId, cardId)` | Puts one chosen card from a mulliganed opening hand on the bottom of its owner's library. |
| `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, 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. | | `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, manaColor })` | Activates an ability on a permanent. Mana abilities resolve immediately; `manaColor` picks the color when the ability can make several. |
| `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. |
| `declareBlockers(playerId, [{ blockerId, attackerId }])` | Declares blocks for one defending player. In multiplayer, combat damage waits until every defending player has declared or passed. | | `declareBlockers(playerId, [{ blockerId, attackerId }])` | Declares blocks for one defending player. In multiplayer, combat damage waits until every defending player has declared or passed. |
| `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. |
| `chooseHideawayCard(playerId, cardId)` | Exiles one of the cards looked at with hideaway; the rest go to the bottom in a random order. |
| `chooseCreatureType(playerId, type)` | Answers an "as this enters, choose a creature type" prompt. | | `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. |
| `legalTargetsForCard(playerId, cardId)`, `legalTargetsForAbility(playerId, sourceId, abilityIndex)` | Legal `TargetChoice`s for a spell or activated ability, so the UI can offer only real targets. |
| `autoAdvance()` | Passes priority for players with nothing meaningful to do; stops when someone can act or the turn ends. | | `autoAdvance()` | Passes priority for players with nothing meaningful to do; stops when someone can act or the turn ends. |
| `getPower`, `getToughness`, `hasKeyword` | Current characteristics after static and continuous effects. | | `getPower`, `getToughness`, `hasKeyword` | Current characteristics after static and continuous effects. |
| `addCard`, `moveToZone` | Setup helpers for placing cards directly into zones. | | `addCard`, `moveToZone` | Setup helpers for placing cards directly into zones. |
@@ -105,12 +107,12 @@ untap -> upkeep -> draw -> precombat main -> begin combat -> declare attackers
-> end step -> cleanup -> next player's turn -> end step -> cleanup -> next player's turn
``` ```
The starting player skips their first draw. Cleanup discards down to seven cards, The starting player draws on their first turn, as in multiplayer Commander. Cleanup
clears damage, expires `until_end_of_turn` and `until_end_of_your_next_turn` discards down to seven cards, clears damage, expires `until_end_of_turn` and
effects, and empties mana pools. The engine advances phases when every living `until_end_of_your_next_turn` effects, and empties mana pools. The engine advances
player passes in turn; it does not stop at every rules-defined priority window. phases when every living player passes in turn; it does not stop at every
The match manager calls `autoAdvance()` after each action, so priority is only rules-defined priority window. The match manager calls `autoAdvance()` after each
shown to players who can actually do something. action, so priority is only shown to players who can actually do something.
## Supported ## Supported
@@ -134,6 +136,14 @@ shown to players who can actually do something.
counter spell/ability, zone returns, tap/untap, search/shuffle, add mana, fight, counter spell/ability, zone returns, tap/untap, search/shuffle, add mana, fight,
regenerate, energy, attach, restrictions, conditional and modal effects, dig, regenerate, energy, attach, restrictions, conditional and modal effects, dig,
divided damage, hideaway, and playing a card exiled with hideaway. divided damage, hideaway, and playing a card exiled with hideaway.
- Tokens: the predefined tokens from comprehensive rules 111.10 (Treasure, Food,
Gold, Walker, Shard, Clue, Blood, Powerstone, Incubator, Map, Junk, Lander,
Mutagen, Vibranium, Heartwood, and the seven Role tokens). `tokens.ts` supplies
their characteristics and abilities when a created token names that subtype or
name. Role tokens can be created already attached to their target. Incubator
tokens carry their counters and can transform into a Phyrexian.
- Keyword actions: explore, incubate, and impulse. Impulse exiles the top card and
marks it playable from exile until the end of the current turn.
- Restrictions and conditions: activated abilities can be disabled, opponents can - 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 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 battlefield from the opening hand, and conditions can count commander control or
@@ -148,9 +158,27 @@ shown to players who can actually do something.
## Known limitations ## Known limitations
- Some effect nodes are accepted but intentionally do nothing yet: - Some effect nodes are accepted but intentionally do nothing yet:
`prevent_damage`, `gain_control`, `emblem`, `transform`, `schedule`, `level_up`, `prevent_damage`, `gain_control`, `emblem`, `schedule`, `level_up`,
`put_from_among`, `look_top`, `scry`, `surveil`, and `keyword_action`. `put_from_among`, `look_top`, `scry`, and `surveil`. Scry and surveil are
Unsupported oracle lines are already marked by the compiler and never reach here. no-ops, so an effect that scries and then draws still draws. `keyword_action`
implements explore, incubate, and impulse; any other action is ignored.
`transform` only works on an object that has a back face, currently the
Incubator token. Unsupported oracle lines are already marked by the compiler
and never reach here.
- Explore puts a revealed land card into its controller's hand. For a nonland
card, the exploring creature gets a +1/+1 counter and the card goes to the
graveyard; it does not ask whether to put that card on top instead.
- Impulse grants the engine's play-from-exile permission. The web client marks a
playable exiled card and offers a Play button in the exile browser; other clients
must expose the same cast/play path.
- Powerstone and Vibranium mana carries an "artifact spells" restriction that the
mana pool does not enforce, so it can currently pay for any spell.
- Role and other Aura static abilities use the `attached: enchanted` selector,
which matches any creature that has an Aura attached rather than only that
Aura's own enchanted creature. With several Auras, a pump can apply more widely
than printed.
- Ward is recorded as a keyword and shown on the permanent, but targeting does not
yet ask for its cost, so Royal Role's ward {1} is not enforced.
- Commander support covers single commanders. Partner, backgrounds, companions, - Commander support covers single commanders. Partner, backgrounds, companions,
and "choose a commander" variants are not modelled. The engine always takes the and "choose a commander" variants are not modelled. The engine always takes the
command-zone replacement instead of asking. command-zone replacement instead of asking.
@@ -167,8 +195,10 @@ shown to players who can actually do something.
(color, card name, player, opponent, number) are accepted and ignored. Cavern of (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 Souls' mana is not restricted to the chosen type and does not make the spell
uncounterable. uncounterable.
- Hideaway automatically exiles the top card and does not track cards as face down. - Hideaway pauses for its controller to exile one of the looked-at cards; the
`play_exiled` only supports the free "without paying its mana cost" case. rest go to the bottom in a random order. The exiled card stays face down and is
shown under its source, hidden from every player's card list. `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 - 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 keeps its printed target. Free alternative costs are modelled only for controlling
a commander, and search restrictions cap the searching player's own library. a commander, and search restrictions cap the searching player's own library.

View File

@@ -7,6 +7,7 @@ import {
parseSelector, parseSelector,
parseTarget, parseTarget,
parseValue, parseValue,
ROLE_NAMES,
} from './parse.js' } from './parse.js'
import type { import type {
Ability, Ability,
@@ -397,6 +398,11 @@ function parseTokenBody(text: string, tapped: boolean): TokenSpec | undefined {
} }
if (/\bcolorless\b/.test(rest)) colors.push('C') if (/\bcolorless\b/.test(rest)) colors.push('C')
const role = Object.entries(ROLE_NAMES).find(([name]) => rest.endsWith(`${name} role`))
if (role) {
return { name: role[1], types: ['enchantment'], subtypes: ['aura', 'role'], colors, tapped: tapped || undefined }
}
let power: Value | undefined let power: Value | undefined
let toughness: Value | undefined let toughness: Value | undefined
const pt = rest.match(/^(\d+|x)\/(\d+|x)\b/) const pt = rest.match(/^(\d+|x)\/(\d+|x)\b/)
@@ -777,6 +783,16 @@ function parseEffect(text: string): Effect | Effect[] | undefined {
} }
} }
match = sentence.match(/^create (?:(\w+) )?(?:a |an )?(.+?) tokens? attached to (.+)$/)
if (match) {
const amount = match[1] && !['a', 'an'].includes(match[1])
? parseValue(match[1])
: ({ kind: 'number', value: 1 } as Value)
const token = parseToken(match[2])
const attachTo = parseTarget(match[3])
if (amount && token && attachTo) return { op: 'create_token', player: 'you', amount, token, attachTo }
}
match = sentence.match(/^create (?:((?:that many)|\w+) )?(.+?) tokens?(?: (with .+))?$/) match = sentence.match(/^create (?:((?:that many)|\w+) )?(.+?) tokens?(?: (with .+))?$/)
if (match) { if (match) {
const amount = match[1] ? parseValue(match[1]) : ({ kind: 'number', value: 1 } as Value) const amount = match[1] ? parseValue(match[1]) : ({ kind: 'number', value: 1 } as Value)
@@ -1944,6 +1960,26 @@ function parseStaticEffects(text: string): StaticEffect[] | undefined {
if (what) return [{ op: 'choose', what }] if (what) return [{ op: 'choose', what }]
} }
match = sentence.match(/^if an effect would create one or more (tokens?|creature tokens?) under your control, it creates (twice|three times) that many of those tokens instead$/)
if (match) {
return [{
op: 'token_multiplier',
multiplier: match[2] === 'twice' ? 2 : 3,
who: 'you',
...(match[1] === 'creature tokens' ? { creatureOnly: true } : {}),
}]
}
match = sentence.match(/^if one or more (tokens?|creature tokens?) would be created( under your control)?, (twice|three times) that many of those tokens are created instead$/)
if (match) {
return [{
op: 'token_multiplier',
multiplier: match[3] === 'twice' ? 2 : 3,
who: match[2] ? 'you' : 'each_player',
...(match[1] === 'creature tokens' ? { creatureOnly: true } : {}),
}]
}
match = sentence.match(/^if this would be put into (?:a|your) graveyard from anywhere, exile it instead$/) match = sentence.match(/^if this would be put into (?:a|your) graveyard from anywhere, exile it instead$/)
if (match) { if (match) {
return [{ op: 'replacement', what: 'dies', instead: 'exile', target: { kind: 'self' } }] return [{ op: 'replacement', what: 'dies', instead: 'exile', target: { kind: 'self' } }]

View File

@@ -116,6 +116,9 @@ function formatSelector(selector: ObjectSelector): string {
if (selector.colors?.length) { if (selector.colors?.length) {
text += `.withColor(${selector.colors.map(color => quote(COLOR_NAMES[color] ?? color)).join(', ')})` text += `.withColor(${selector.colors.map(color => quote(COLOR_NAMES[color] ?? color)).join(', ')})`
} }
if (selector.excludeColors?.length) {
text += `.withoutColor(${selector.excludeColors.map(color => quote(COLOR_NAMES[color] ?? color)).join(', ')})`
}
if (selector.supertypes?.length) { if (selector.supertypes?.length) {
text += `.withSupertype(${selector.supertypes.map(quote).join(', ')})` text += `.withSupertype(${selector.supertypes.map(quote).join(', ')})`
} }
@@ -315,7 +318,7 @@ export function formatEffect(effect: Effect): string {
case 'create_token': case 'create_token':
return effect.copyOf return effect.copyOf
? `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, copyOf(${formatTarget(effect.copyOf)}${effect.notLegendary ? ', { notLegendary: true }' : ''}))` ? `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, copyOf(${formatTarget(effect.copyOf)}${effect.notLegendary ? ', { notLegendary: true }' : ''}))`
: `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, ${formatToken(effect.token)})` : `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, ${formatToken(effect.token)}${effect.attachTo ? `, { attachTo: ${formatTarget(effect.attachTo)} }` : ''})`
case 'destroy': case 'destroy':
return `destroy(${formatTarget(effect.target)})` return `destroy(${formatTarget(effect.target)})`
case 'exile': case 'exile':
@@ -560,6 +563,8 @@ function formatCondition(condition: Condition): string {
return `attackedWithCreatures(${condition.atLeast})` return `attackedWithCreatures(${condition.atLeast})`
case 'library_at_most': case 'library_at_most':
return `libraryAtMost(${condition.atMost})` return `libraryAtMost(${condition.atMost})`
case 'event_subject_toughness_at_most':
return `eventSubjectToughnessAtMost(${condition.amount})`
} }
} }
@@ -651,6 +656,11 @@ function formatStaticEffect(effect: StaticEffect): string {
return `searchRestriction(${quote(effect.who)}, ${formatValue(effect.amount)})` return `searchRestriction(${quote(effect.who)}, ${formatValue(effect.amount)})`
case 'exile_instead_of_graveyard': case 'exile_instead_of_graveyard':
return `exileInsteadOfGraveyard(${effect.owner ? quote(effect.owner) : ''})` return `exileInsteadOfGraveyard(${effect.owner ? quote(effect.owner) : ''})`
case 'token_multiplier':
return `tokenMultiplier(${effect.multiplier}${optionArg([
['who', effect.who === 'each_player' ? quote('each_player') : undefined],
['creatureOnly', effect.creatureOnly ? 'true' : undefined],
])})`
} }
} }

View File

@@ -144,6 +144,16 @@ const NON_CREATURE_SUBTYPES: Record<string, string> = {
desert: 'land', desert: 'land',
} }
export const ROLE_NAMES: Record<string, string> = {
cursed: 'Cursed',
monster: 'Monster',
royal: 'Royal',
sorcerer: 'Sorcerer',
virtuous: 'Virtuous',
wicked: 'Wicked',
'young hero': 'Young Hero',
}
function typeForSubtype(subtype: string): string { function typeForSubtype(subtype: string): string {
return NON_CREATURE_SUBTYPES[subtype] ?? 'creature' return NON_CREATURE_SUBTYPES[subtype] ?? 'creature'
} }
@@ -462,6 +472,7 @@ export function parseSelector(text: string): ObjectSelector | undefined {
const supertypes: string[] = [] const supertypes: string[] = []
const subtypes: string[] = [] const subtypes: string[] = []
const colors: string[] = [] const colors: string[] = []
const excludeColors: string[] = []
let match: ObjectSelector['match'] let match: ObjectSelector['match']
for (const rawWord of words) { for (const rawWord of words) {
@@ -506,6 +517,10 @@ export function parseSelector(text: string): ObjectSelector | undefined {
excludeTypes.push(negative[1]) excludeTypes.push(negative[1])
continue continue
} }
if (negative && COLOR_WORDS[negative[1]]) {
excludeColors.push(COLOR_WORDS[negative[1]])
continue
}
if (STATE_WORDS.has(word)) { if (STATE_WORDS.has(word)) {
if (word === 'token') selector.token = true if (word === 'token') selector.token = true
@@ -528,7 +543,7 @@ export function parseSelector(text: string): ObjectSelector | undefined {
if (!types.length) { if (!types.length) {
if (subtypes.length) { if (subtypes.length) {
types.push(typeForSubtype(subtypes[0])) types.push(typeForSubtype(subtypes[0]))
} else if (!(excludeTypes.length || colors.length || supertypes.length || selector.name)) { } else if (!(excludeTypes.length || excludeColors.length || colors.length || supertypes.length || selector.name)) {
return undefined return undefined
} }
} }
@@ -536,6 +551,7 @@ export function parseSelector(text: string): ObjectSelector | undefined {
selector.types = types selector.types = types
if (match) selector.match = match if (match) selector.match = match
if (excludeTypes.length) selector.excludeTypes = excludeTypes if (excludeTypes.length) selector.excludeTypes = excludeTypes
if (excludeColors.length) selector.excludeColors = excludeColors
if (supertypes.length) selector.supertypes = supertypes if (supertypes.length) selector.supertypes = supertypes
if (subtypes.length) selector.subtypes = subtypes if (subtypes.length) selector.subtypes = subtypes
if (colors.length) selector.colors = colors if (colors.length) selector.colors = colors

View File

@@ -522,7 +522,7 @@ const STATIC_OPS = new Set([
'pump', 'grant', 'grant_ability', 'restriction', 'enters_tapped', 'pump', 'grant', 'grant_ability', 'restriction', 'enters_tapped',
'enters_with_counters', 'set_pt', 'control', 'choose', 'replacement', 'enters_with_counters', 'set_pt', 'control', 'choose', 'replacement',
'cost_reduction', 'cost_increase', 'search_restriction', 'cost_reduction', 'cost_increase', 'search_restriction',
'exile_instead_of_graveyard', 'exile_instead_of_graveyard', 'token_multiplier',
]) ])
const COST_KINDS = new Set([ const COST_KINDS = new Set([
@@ -766,6 +766,18 @@ class Selector {
}) })
} }
withoutColor(...colors: unknown[]): Selector {
return this.with({
excludeColors: [
...(this.fields.excludeColors ?? []),
...colors.map(color => {
const text = asString(color, 'color').toLowerCase()
return COLOR_CODES[text] ?? text.toUpperCase()
}),
],
})
}
matchingAny(): Selector { matchingAny(): Selector {
return this.with({ match: 'any' }) return this.with({ match: 'any' })
} }
@@ -1249,7 +1261,10 @@ function proliferate(): Effect {
return { op: 'proliferate' } return { op: 'proliferate' }
} }
function createToken(player: unknown, amount: unknown, tokenValue: unknown): Effect { function createToken(player: unknown, amount: unknown, tokenValue: unknown, options?: unknown): Effect {
const attachTo = options && typeof options === 'object' && 'attachTo' in options
? asTarget((options as { attachTo: unknown }).attachTo)
: undefined
if (tokenValue instanceof CopyOf) { if (tokenValue instanceof CopyOf) {
return { return {
op: 'create_token', op: 'create_token',
@@ -1258,9 +1273,16 @@ function createToken(player: unknown, amount: unknown, tokenValue: unknown): Eff
token: { types: [], subtypes: [], colors: [] }, token: { types: [], subtypes: [], colors: [] },
copyOf: tokenValue.target, copyOf: tokenValue.target,
...(tokenValue.notLegendary ? { notLegendary: true } : {}), ...(tokenValue.notLegendary ? { notLegendary: true } : {}),
...(attachTo ? { attachTo } : {}),
} }
} }
return { op: 'create_token', player: asPlayer(player), amount: asValue(amount), token: asToken(tokenValue) } return {
op: 'create_token',
player: asPlayer(player),
amount: asValue(amount),
token: asToken(tokenValue),
...(attachTo ? { attachTo } : {}),
}
} }
function destroy(targetValue: unknown): Effect { function destroy(targetValue: unknown): Effect {
@@ -1603,6 +1625,19 @@ function replace(what: unknown, options?: unknown): StaticEffect {
} }
} }
function tokenMultiplier(multiplier: unknown, options?: unknown): StaticEffect {
const data = asOptions(options)
if (data.who !== undefined && data.who !== 'you' && data.who !== 'each_player') {
throw new Error("tokenMultiplier() who must be 'you' or 'each_player'")
}
return {
op: 'token_multiplier',
multiplier: asNumber(multiplier, 'token multiplier'),
who: data.who === 'each_player' ? 'each_player' : 'you',
...(data.creatureOnly === true ? { creatureOnly: true } : {}),
}
}
function costReduction(targetValue: unknown, amount: unknown, options?: unknown): StaticEffect { function costReduction(targetValue: unknown, amount: unknown, options?: unknown): StaticEffect {
const data = asOptions(options) const data = asOptions(options)
return { return {
@@ -2351,6 +2386,7 @@ function createApi(): Record<string, unknown> {
costIncrease, costIncrease,
searchRestriction, searchRestriction,
exileInsteadOfGraveyard, exileInsteadOfGraveyard,
tokenMultiplier,
// abilities // abilities
keyword, keyword,

View File

@@ -73,6 +73,7 @@ Selectors (chainable):
permanents, cards, creatures permanents, cards, creatures
.withType('land'), .withSubtype('dragon'), .withSupertype('legendary') .withType('land'), .withSubtype('dragon'), .withSupertype('legendary')
.withColor('white'|'blue'|'black'|'red'|'green'|'colorless') .withColor('white'|'blue'|'black'|'red'|'green'|'colorless')
.withoutColor('white'|'blue'|'black'|'red'|'green'|'colorless')
.withoutType('creature'), .withKeyword('flying'), .withoutKeyword('flying') .withoutType('creature'), .withKeyword('flying'), .withoutKeyword('flying')
.other(), .tapped(), .untapped(), .attacking(), .token(), .nontoken() .other(), .tapped(), .untapped(), .attacking(), .token(), .nontoken()
.equipped(), .enchanted(), .youControl(), .opponentControls(), .controlledBy('you'|'opponent'|'any') .equipped(), .enchanted(), .youControl(), .opponentControls(), .controlledBy('you'|'opponent'|'any')

View File

@@ -25,6 +25,7 @@ export interface ObjectSelector {
controller?: 'you' | 'opponent' | 'any' controller?: 'you' | 'opponent' | 'any'
owner?: 'you' | 'opponent' owner?: 'you' | 'opponent'
colors?: string[] colors?: string[]
excludeColors?: string[]
other?: boolean other?: boolean
attached?: 'equipped' | 'enchanted' attached?: 'equipped' | 'enchanted'
zone?: Zone zone?: Zone
@@ -191,6 +192,7 @@ export type Condition =
| { kind: 'opponent_damaged_this_turn'; atLeast: number } | { kind: 'opponent_damaged_this_turn'; atLeast: number }
| { kind: 'attacked_with_creatures'; atLeast: number } | { kind: 'attacked_with_creatures'; atLeast: number }
| { kind: 'library_at_most'; atMost: number } | { kind: 'library_at_most'; atMost: number }
| { kind: 'event_subject_toughness_at_most'; amount: number }
export type TriggerEvent = export type TriggerEvent =
| { kind: 'enters'; subject: Target } | { kind: 'enters'; subject: Target }
@@ -225,7 +227,7 @@ export type Effect =
| { op: 'put_counters'; target: Target; counter: string; amount: Value } | { op: 'put_counters'; target: Target; counter: string; amount: Value }
| { op: 'remove_counters'; target: Target; counter: string; amount: Value } | { op: 'remove_counters'; target: Target; counter: string; amount: Value }
| { op: 'proliferate' } | { op: 'proliferate' }
| { op: 'create_token'; player: PlayerRef; amount: Value; token: TokenSpec; copyOf?: Target; notLegendary?: boolean } | { op: 'create_token'; player: PlayerRef; amount: Value; token: TokenSpec; copyOf?: Target; notLegendary?: boolean; attachTo?: Target }
| { op: 'destroy'; target: Target } | { op: 'destroy'; target: Target }
| { op: 'exile'; target: Target } | { op: 'exile'; target: Target }
| { op: 'sacrifice'; player: PlayerRef; target: Target; unless?: Cost } | { op: 'sacrifice'; player: PlayerRef; target: Target; unless?: Cost }
@@ -278,6 +280,7 @@ export type StaticEffect =
| { op: 'cost_increase'; amount: Value; spellType?: 'noncreature' | 'creature' } | { op: 'cost_increase'; amount: Value; spellType?: 'noncreature' | 'creature' }
| { op: 'search_restriction'; who: 'opponent' | 'you'; amount: Value } | { op: 'search_restriction'; who: 'opponent' | 'you'; amount: Value }
| { op: 'exile_instead_of_graveyard'; owner?: 'opponent' | 'you' } | { op: 'exile_instead_of_graveyard'; owner?: 'opponent' | 'you' }
| { op: 'token_multiplier'; multiplier: number; who: 'you' | 'each_player'; creatureOnly?: boolean }
export type Ability = export type Ability =
| KeywordAbility | KeywordAbility

View File

@@ -33,6 +33,7 @@ import type {
TargetChoice, TargetChoice,
} from './types.js' } from './types.js'
import { CREATURE_TYPES } from './creature-types.js' import { CREATURE_TYPES } from './creature-types.js'
import { predefinedToken } from './tokens.js'
export class GameError extends Error {} export class GameError extends Error {}
@@ -65,6 +66,8 @@ interface EffectContext {
eventAmount?: number eventAmount?: number
x: number x: number
mode: number mode: number
/** Color picked for a mana ability, so choice effects produce it. */
manaColor?: ManaColor
} }
interface ContinuousEffect { interface ContinuousEffect {
@@ -167,19 +170,66 @@ function colorOfSymbol(symbol: string): ManaColor {
return 'C' return 'C'
} }
function tokenCard(token: { types: string[]; subtypes: string[]; name?: string; colors: string[]; power?: number; toughness?: number; keywords?: string[] }): CardDefinition { function tokenCard(token: {
name?: string
types: string[]
subtypes: string[]
colors: string[]
power?: number
toughness?: number
keywords?: string[]
}): { definition: CardDefinition; backFace?: CardDefinition } {
const predefined = predefinedToken(token)
const types = predefined?.types ?? token.types
const subtypes = predefined?.subtypes ?? token.subtypes
const colors = [...new Set([...(predefined?.colors ?? []), ...token.colors])]
const keywords = [...(predefined?.keywords ?? []), ...(token.keywords ?? [])]
const definition = tokenFace({
name: predefined?.name ?? token.name ?? (subtypes.map(capitalize).join(' ') || 'Token'),
types,
subtypes,
colors,
power: token.power ?? predefined?.power,
toughness: token.toughness ?? predefined?.toughness,
keywords,
abilities: predefined?.abilities,
})
const backFace = predefined?.backFace
? tokenFace({ ...predefined.backFace, keywords: predefined.backFace.keywords ?? [] })
: undefined
return { definition, backFace }
}
function capitalize(word: string): string {
return word[0]?.toUpperCase() + word.slice(1)
}
function tokenFace(fields: {
name: string
types: string[]
subtypes: string[]
colors: string[]
power?: number
toughness?: number
keywords?: string[]
abilities?: Ability[]
}): CardDefinition {
return { return {
oracleId: `token:${token.name ?? (token.subtypes.join(' ') || token.types.join(' '))}`, oracleId: `token:${fields.name}`,
name: token.name ?? (token.subtypes.map(word => word[0]?.toUpperCase() + word.slice(1)).join(' ') || 'Token'), name: fields.name,
typeLine: [token.types.join(' '), token.subtypes.length ? `— ${token.subtypes.join(' ')}` : ''].join(' ').trim(), typeLine: [fields.types.join(' '), fields.subtypes.length ? `— ${fields.subtypes.join(' ')}` : ''].join(' ').trim(),
manaValue: 0, manaValue: 0,
colors: token.colors, colors: fields.colors,
power: token.power, power: fields.power,
toughness: token.toughness, toughness: fields.toughness,
abilities: (token.keywords ?? []).map(keyword => ({ kind: 'keyword', keyword })), abilities: [
...(fields.abilities ?? []),
...(fields.keywords ?? []).map(keyword => ({ kind: 'keyword' as const, keyword })),
],
} }
} }
/** /**
* A deliberately small but real Magic rules engine: zones, priority, the stack, * A deliberately small but real Magic rules engine: zones, priority, the stack,
* turn phases, combat, state-based actions, mana, triggered/activated/static * turn phases, combat, state-based actions, mana, triggered/activated/static
@@ -431,6 +481,7 @@ export class Game {
const from = object.zone const from = object.zone
this.removeFromZone(object) this.removeFromZone(object)
object.zone = destination object.zone = destination
if (destination !== 'exile') object.faceDown = undefined
if (destination === 'battlefield') { if (destination === 'battlefield') {
object.controller = options.controller ?? object.owner object.controller = options.controller ?? object.owner
@@ -617,8 +668,10 @@ export class Game {
} }
if (this.stack.length) throw new GameError('Cannot play a land while the stack is not empty') if (this.stack.length) throw new GameError('Cannot play a land while the stack is not empty')
if (player.landPlayedThisTurn) throw new GameError('Already played a land this turn') if (player.landPlayedThisTurn) throw new GameError('Already played a land this turn')
if (!player.hand.includes(cardId)) throw new GameError('Card is not in hand')
const object = this.getObject(cardId) const object = this.getObject(cardId)
if (!player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) {
throw new GameError('Card is not in hand')
}
if (!this.isLand(object)) throw new GameError('That card is not a land') if (!this.isLand(object)) throw new GameError('That card is not a land')
player.landPlayedThisTurn = true player.landPlayedThisTurn = true
@@ -634,8 +687,10 @@ export class Game {
if (this.status !== 'active') throw new GameError('Game is not active') if (this.status !== 'active') throw new GameError('Game is not active')
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)) throw new GameError('Card is not in hand')
const object = this.getObject(cardId) const object = this.getObject(cardId)
if (!fromCommand && !player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) {
throw new GameError('Card is not in hand')
}
if (fromCommand && !object.isCommander) throw new GameError('That card cannot be cast from the command zone') if (fromCommand && !object.isCommander) throw new GameError('That card cannot be cast from the command zone')
if (this.isLand(object)) throw new GameError('Land cards are played, not cast') if (this.isLand(object)) throw new GameError('Land cards are played, not cast')
if (!this.canCastAtThisTime(playerId, object)) { if (!this.canCastAtThisTime(playerId, object)) {
@@ -773,9 +828,13 @@ export class Game {
if (ability.activationsPerTurn !== undefined && activations >= ability.activationsPerTurn) { if (ability.activationsPerTurn !== undefined && activations >= ability.activationsPerTurn) {
throw new GameError('Ability activation limit reached') throw new GameError('Ability activation limit reached')
} }
if (options.manaColor && !this.manaColorChoices(source, abilityIndex)?.includes(options.manaColor)) {
throw new GameError('That ability cannot produce that mana')
}
const targets = this.selectTargets(ability.effects, source, playerId, options.targets ?? [], options.mode ?? 0) const targets = this.selectTargets(ability.effects, source, playerId, options.targets ?? [], options.mode ?? 0)
const context = this.contextFor(source, playerId, targets, options.x ?? 0, options.mode ?? 0) const context = this.contextFor(source, playerId, targets, options.x ?? 0, options.mode ?? 0)
context.manaColor = options.manaColor
this.payCosts(ability.costs, playerId, source, context) this.payCosts(ability.costs, playerId, source, context)
source.activations[abilityIndex] = activations + 1 source.activations[abilityIndex] = activations + 1
@@ -980,8 +1039,8 @@ export class Game {
if (this.status !== 'active' || this.priority !== playerId || this.pendingSearch || this.pendingChoice) return false 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
const object = this.getObject(cardId) const object = this.getObject(cardId)
if (!fromCommand && !player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) return false
if (fromCommand && !object.isCommander) return false if (fromCommand && !object.isCommander) return false
if (this.isLand(object)) { if (this.isLand(object)) {
@@ -1010,6 +1069,13 @@ export class Game {
return this.hasLegalTargets(object, playerId) return this.hasLegalTargets(object, playerId)
} }
/** Junk and other impulse effects grant a one-turn play permission from exile. */
private playableFromExile(playerId: string, object: GameObject): boolean {
return object.zone === 'exile'
&& object.owner === playerId
&& object.playableFromExileTurn === this.turn
}
/** /**
* Finishes one pick of a paused library search. Searches pause when several * Finishes one pick of a paused library search. Searches pause when several
* cards match so the player chooses instead of taking the first one. * cards match so the player chooses instead of taking the first one.
@@ -1056,6 +1122,37 @@ export class Game {
return this.searchableObjects(playerId, pending.zones) return this.searchableObjects(playerId, pending.zones)
} }
/**
* Answers the hideaway look: exiles the chosen card linked to the source and
* puts the rest on the bottom of the library in a random order.
*/
chooseHideawayCard(playerId: string, cardId: string): void {
const pending = this.pendingChoice
if (!pending || pending.what !== 'hideaway') throw new GameError('No hideaway choice is waiting')
if (pending.playerId !== playerId) throw new GameError('You are not choosing this hideaway card')
const looked = (pending.cardIds ?? []).map(id => this.getObject(id))
const hidden = looked.find(object => object.id === cardId && object.zone === 'library')
if (!hidden) throw new GameError('That card is not a legal choice')
this.pendingChoices.shift()
this.moveToZone(hidden, 'exile', { silent: true })
const source = this.objects.get(pending.sourceId)
if (hidden.zone === 'exile') {
hidden.faceDown = true
if (source) source.linkedExile = [...(source.linkedExile ?? []), hidden.id]
}
const rest = looked.filter(object => object.id !== hidden.id)
for (let index = rest.length - 1; index > 0; index--) {
const swap = Math.floor(this.rng() * (index + 1))
const temp = rest[index]
rest[index] = rest[swap]
rest[swap] = temp
}
for (const object of rest) this.moveToZone(object, 'library', { silent: true })
this.logMessage(`${this.getPlayer(playerId).name} hides away a card`)
}
/** /**
* Answers an "as this enters, choose a creature type" prompt. The match API * Answers an "as this enters, choose a creature type" prompt. The match API
* uses the `choose_type` action. * uses the `choose_type` action.
@@ -1153,11 +1250,8 @@ export class Game {
if (this.status !== 'active') return if (this.status !== 'active') return
this.step = 'draw' this.step = 'draw'
// The first player skips their first draw step, as in Commander.
if (this.turn > 1) {
this.drawCard(player.id, false) this.drawCard(player.id, false)
if (this.status !== 'active') return if (this.status !== 'active') return
}
this.phase = 'precombat_main' this.phase = 'precombat_main'
this.step = 'main' this.step = 'main'
@@ -1441,6 +1535,28 @@ export class Game {
return this.neededColor(player, cost, this.manaAbilityAllowedColors(source, ability)) return this.neededColor(player, cost, this.manaAbilityAllowedColors(source, ability))
} }
/**
* Colors a mana ability lets its controller choose between. Undefined when
* the ability has no choice, such as fixed or single-color mana.
*/
manaColorChoices(source: GameObject, abilityIndex: number): ManaColor[] | undefined {
const ability = (source.definition.abilities ?? [])[abilityIndex]
if (!ability || ability.kind !== 'activated') return undefined
let colors: ManaColor[] | undefined
for (const effect of ability.effects) {
if (effect.op !== 'add_mana') continue
if (effect.mana.kind === 'symbols' && effect.mana.oneOf) {
colors = [...new Set(effect.mana.symbols.map(colorOfSymbol))]
} else if (effect.mana.kind === 'any_color') {
const allowed = this.anyColorRestrictionColors(effect.mana, source.controller)
colors = allowed
? MANA_COLORS.filter(color => color !== 'C' && allowed.has(color))
: ['W', 'U', 'B', 'R', 'G']
}
}
return colors && colors.length > 1 ? colors : undefined
}
private manaAbilityAllowedColors( private manaAbilityAllowedColors(
source: GameObject, source: GameObject,
ability: Extract<Ability, { kind: 'activated' }>, ability: Extract<Ability, { kind: 'activated' }>,
@@ -1543,6 +1659,11 @@ export class Game {
if (mana.restriction === 'a land you control could produce') { if (mana.restriction === 'a land you control could produce') {
return this.landManaColors(playerId, false, seen) return this.landManaColors(playerId, false, seen)
} }
if (mana.restriction === "commander's color identity") {
const commander = this.objects.get(this.getPlayer(playerId).commanderId ?? '')
const identity = commander?.definition.colorIdentity ?? []
return new Set(identity.filter((color): color is ManaColor => /^[WUBRG]$/.test(color)))
}
return undefined return undefined
} }
@@ -1747,6 +1868,10 @@ export class Game {
take({ kind: 'player', who: effect.player, mode: 'target' }, who) take({ kind: 'player', who: effect.player, mode: 'target' }, who)
} }
if ('target' in effect && effect.target) take(effect.target, undefined) if ('target' in effect && effect.target) take(effect.target, undefined)
if (effect.op === 'create_token') {
if (effect.copyOf) take(effect.copyOf, undefined)
if (effect.attachTo) take(effect.attachTo, undefined)
}
if (effect.op === 'fight') { if (effect.op === 'fight') {
take(effect.a, undefined) take(effect.a, undefined)
take(effect.b, undefined) take(effect.b, undefined)
@@ -1758,6 +1883,70 @@ export class Game {
return selected return selected
} }
/** Legal choices for a card's targets, so the UI can offer only real targets. */
legalTargetsForCard(playerId: string, cardId: string): TargetChoice[] {
const source = this.objects.get(cardId)
if (!source) return []
const effects = (source.definition.abilities ?? [])
.filter((ability): ability is Extract<Ability, { kind: 'spell' }> => ability.kind === 'spell')
.flatMap(ability => ability.effects)
return this.collectTargets(effects, source, playerId, 0)
}
/** Legal choices for an activated ability's targets. */
legalTargetsForAbility(playerId: string, sourceId: string, abilityIndex: number): TargetChoice[] {
const source = this.objects.get(sourceId)
const ability = source?.definition.abilities?.[abilityIndex]
if (!source || !ability || ability.kind !== 'activated') return []
return this.collectTargets(ability.effects, source, playerId, 0)
}
private collectTargets(
effects: Effect[],
source: GameObject,
controller: string,
mode: number,
): TargetChoice[] {
const choices = new Map<string, TargetChoice>()
const add = (target: Target, playerOnly?: 'opponent' | 'any'): void => {
if (target.kind === 'self' || target.kind === 'trigger_subject' || target.kind === 'previous_target') return
if ((target.kind === 'object' || target.kind === 'player') && target.mode === 'each') return
for (const choice of this.legalTargets(target, source, controller, playerOnly)) {
choices.set(`${choice.kind}:${choice.id}`, choice)
}
}
const walk = (list: Effect[]): void => {
for (const effect of list) {
if (effect.op === 'conditional') {
walk(effect.effects)
continue
}
if (effect.op === 'modal') {
walk(effect.modes[mode] ?? effect.modes[0] ?? [])
continue
}
if ('player' in effect && (effect.player === 'target_player' || effect.player === 'opponent')) {
add(
{ kind: 'player', who: effect.player, mode: 'target' },
effect.player === 'opponent' ? 'opponent' : 'any',
)
}
if ('target' in effect && effect.target) add(effect.target)
if (effect.op === 'create_token') {
if (effect.copyOf) add(effect.copyOf)
if (effect.attachTo) add(effect.attachTo)
}
if (effect.op === 'fight') {
add(effect.a)
add(effect.b)
}
if (effect.op === 'damage_divided') add(effect.target)
}
}
walk(effects)
return [...choices.values()]
}
private legalTargets( private legalTargets(
target: Target, target: Target,
source: GameObject, source: GameObject,
@@ -2046,16 +2235,29 @@ export class Game {
case 'create_token': { case 'create_token': {
const amount = Math.max(0, this.value(effect.amount, context)) const amount = Math.max(0, this.value(effect.amount, context))
const players = this.playersForEffect(effect.player, context) const players = this.playersForEffect(effect.player, context)
const created: GameObject[] = []
for (const playerId of players) { for (const playerId of players) {
for (let i = 0; i < amount; i++) { const source = effect.copyOf
? this.resolveTargets(context, effect.copyOf).find(target => target.kind === 'object')
: undefined
const creatureToken = source?.kind === 'object'
? this.isCreature(source.object)
: effect.token.types.includes('creature')
const count = amount * this.tokenMultiplier(playerId, creatureToken)
for (let i = 0; i < count; i++) {
if (effect.copyOf) { if (effect.copyOf) {
const source = this.resolveTargets(context, effect.copyOf).find(target => target.kind === 'object') if (source?.kind === 'object') created.push(this.createTokenCopy(playerId, source.object, effect.notLegendary))
if (source?.kind === 'object') this.createTokenCopy(playerId, source.object, effect.notLegendary)
} else { } else {
this.createToken(playerId, effect.token, context) created.push(this.createToken(playerId, effect.token, context))
} }
} }
} }
if (effect.attachTo) {
const target = this.resolveTargets(context, effect.attachTo)[0]
if (target?.kind === 'object') {
for (const token of created) this.attach(token, target.object)
}
}
break break
} }
case 'destroy': { case 'destroy': {
@@ -2148,7 +2350,7 @@ export class Game {
break break
} }
case 'add_mana': { case 'add_mana': {
for (const playerId of this.playersForEffect(effect.player, context)) this.addMana(playerId, effect.mana) for (const playerId of this.playersForEffect(effect.player, context)) this.addMana(playerId, effect.mana, context.manaColor)
break break
} }
case 'fight': { case 'fight': {
@@ -2186,16 +2388,28 @@ export class Game {
break break
} }
case 'keyword_action': case 'keyword_action':
if (effect.action === 'explore') this.explore(context, effect)
else if (effect.action === 'incubate') this.incubate(context, effect.amount)
else if (effect.action === 'impulse') this.impulse(context)
break break
case 'prevent_damage': case 'prevent_damage':
case 'gain_control': case 'gain_control':
case 'emblem': case 'emblem':
case 'transform':
case 'schedule': case 'schedule':
case 'level_up': case 'level_up':
case 'put_from_among': case 'put_from_among':
case 'look_top': case 'look_top':
break break
case 'transform': {
const target = this.resolveTargets(context, effect.target)[0]
if (target?.kind === 'object' && target.object.backFace) {
const front = target.object.definition
target.object.definition = target.object.backFace
target.object.backFace = front
this.logMessage(`${target.object.definition.name} transforms`)
}
break
}
case 'pay': case 'pay':
try { try {
this.payCosts(effect.costs, context.controller, context.source, context) this.payCosts(effect.costs, context.controller, context.source, context)
@@ -2241,24 +2455,28 @@ export class Game {
} }
private hideaway(context: EffectContext, effect: Extract<Effect, { op: 'hideaway' }>): void { private hideaway(context: EffectContext, effect: Extract<Effect, { op: 'hideaway' }>): void {
// shortcut: auto-pick the top card; face-down exile and the look/choice are not modelled. // The exiled card stays face down and is linked to the source until played.
const player = this.getPlayer(context.controller) const player = this.getPlayer(context.controller)
const amount = this.value(effect.amount, context) const amount = this.value(effect.amount, context)
const top = player.library.slice(0, amount).map(id => this.getObject(id)) const looked = player.library.slice(0, amount).map(id => this.getObject(id))
const hidden = top.shift() if (!looked.length) return
if (!hidden) return if (looked.length === 1) {
this.moveToZone(looked[0], 'exile', { silent: true })
this.moveToZone(hidden, 'exile', { silent: true }) if (looked[0].zone === 'exile') {
context.source.linkedExile = [...(context.source.linkedExile ?? []), hidden.id] looked[0].faceDown = true
context.source.linkedExile = [...(context.source.linkedExile ?? []), looked[0].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`) this.logMessage(`${player.name} hides away a card`)
return
}
this.pendingChoices.push({
playerId: context.controller,
sourceId: context.source.id,
what: 'hideaway',
cardIds: looked.map(object => object.id),
})
this.logMessage(`${player.name} looks at the top ${looked.length} cards of their library`)
} }
private playExiledCard(playerId: string, object: GameObject, free: boolean | undefined): boolean { private playExiledCard(playerId: string, object: GameObject, free: boolean | undefined): boolean {
@@ -2304,6 +2522,48 @@ export class Game {
return true return true
} }
private explore(context: EffectContext, effect: Extract<Effect, { op: 'keyword_action' }>): void {
const target = effect.target ? this.resolveTargets(context, effect.target)[0] : undefined
if (target?.kind !== 'object') return
const player = this.getPlayer(context.controller)
const cardId = player.library[0]
if (!cardId) return
const card = this.getObject(cardId)
if (this.isLand(card)) {
this.moveToZone(card, 'hand', { silent: false })
this.logMessage(`${player.name} explores and puts ${card.definition.name} into their hand`)
return
}
this.addCounters(target.object, '+1/+1', 1)
// shortcut: the explored card always goes to the graveyard instead of
// asking whether to put it on top. Upgrade when the choice matters.
this.moveToZone(card, 'graveyard', { silent: false })
this.logMessage(`${player.name} explores with ${target.object.definition.name}`)
}
private incubate(context: EffectContext, amount: Value | undefined): void {
const counters = amount ? Math.max(0, this.value(amount, context)) : 0
const count = this.tokenMultiplier(context.controller, false)
for (let i = 0; i < count; i++) {
const token = this.createToken(context.controller, {
types: ['artifact'],
subtypes: ['incubator'],
colors: [],
}, context)
this.addCounters(token, '+1/+1', counters)
}
}
private impulse(context: EffectContext): void {
const player = this.getPlayer(context.controller)
const cardId = player.library[0]
if (!cardId) return
const card = this.getObject(cardId)
this.moveToZone(card, 'exile', { silent: false })
card.playableFromExileTurn = this.turn
this.logMessage(`${player.name} exiles ${card.definition.name} and may play it this turn`)
}
private dig( private dig(
context: EffectContext, context: EffectContext,
effect: Extract<Effect, { op: 'dig' }>, effect: Extract<Effect, { op: 'dig' }>,
@@ -2467,7 +2727,7 @@ export class Game {
} }
private createToken(playerId: string, spec: TokenSpec, context: EffectContext): GameObject { private createToken(playerId: string, spec: TokenSpec, context: EffectContext): GameObject {
const definition = tokenCard({ const card = tokenCard({
...spec, ...spec,
power: spec.power ? this.value(spec.power, context) : undefined, power: spec.power ? this.value(spec.power, context) : undefined,
toughness: spec.toughness ? this.value(spec.toughness, context) : undefined, toughness: spec.toughness ? this.value(spec.toughness, context) : undefined,
@@ -2475,7 +2735,8 @@ export class Game {
const player = this.getPlayer(playerId) const player = this.getPlayer(playerId)
const object: GameObject = { const object: GameObject = {
id: this.generateId('token'), id: this.generateId('token'),
definition, definition: card.definition,
backFace: card.backFace,
owner: playerId, owner: playerId,
controller: playerId, controller: playerId,
zone: 'battlefield', zone: 'battlefield',
@@ -2503,6 +2764,7 @@ export class Game {
const object: GameObject = { const object: GameObject = {
id: this.generateId('token'), id: this.generateId('token'),
definition, definition,
backFace: source.backFace,
owner: playerId, owner: playerId,
controller: playerId, controller: playerId,
zone: 'battlefield', zone: 'battlefield',
@@ -2558,7 +2820,11 @@ export class Game {
for (const source of sources) { for (const source of sources) {
for (const ability of source.definition.abilities ?? []) { for (const ability of source.definition.abilities ?? []) {
if (ability.kind !== 'triggered') continue if (ability.kind !== 'triggered') continue
if (ability.condition && !this.checkCondition(ability.condition, source)) continue if (ability.condition) {
if (ability.condition.kind === 'event_subject_toughness_at_most') {
if (!event.subject || this.getToughness(event.subject) > ability.condition.amount) continue
} else if (!this.checkCondition(ability.condition, source)) continue
}
if (!this.matchesTrigger(event, ability.event, source)) continue if (!this.matchesTrigger(event, ability.event, source)) continue
let targets: TargetChoice[] let targets: TargetChoice[]
try { try {
@@ -2672,6 +2938,20 @@ export class Game {
return this.objectsMatching(target.selector, source) return this.objectsMatching(target.selector, source)
} }
/** Product of every token-doubling replacement that applies to this creation. */
private tokenMultiplier(playerId: string, creatureToken: boolean): number {
let multiplier = 1
for (const { source, ability } of this.staticAbilities()) {
for (const effect of ability.effects) {
if (effect.op !== 'token_multiplier') continue
if (effect.who === 'you' && source.controller !== playerId) continue
if (effect.creatureOnly && !creatureToken) continue
multiplier *= effect.multiplier
}
}
return multiplier
}
private exilesInsteadOfGraveyard(object: GameObject): boolean { private exilesInsteadOfGraveyard(object: GameObject): boolean {
for (const { source, ability } of this.staticAbilities()) { for (const { source, ability } of this.staticAbilities()) {
for (const effect of ability.effects) { for (const effect of ability.effects) {
@@ -2810,6 +3090,8 @@ export class Game {
return this.battlefieldObjects() return this.battlefieldObjects()
.filter(object => object.controller === controller && this.isCreature(object)) .filter(object => object.controller === controller && this.isCreature(object))
.reduce((total, object) => total + this.getPower(object), 0) >= condition.atLeast .reduce((total, object) => total + this.getPower(object), 0) >= condition.atLeast
case 'event_subject_toughness_at_most':
return false
default: default:
return false return false
} }
@@ -2914,7 +3196,7 @@ export class Game {
return true return true
} }
if ([...player.hand, ...player.command].some(id => this.canPlayCard(playerId, id))) return true if ([...player.hand, ...player.command, ...player.exile].some(id => this.canPlayCard(playerId, id))) return true
for (const id of player.battlefield) { for (const id of player.battlefield) {
const object = this.objects.get(id) const object = this.objects.get(id)
@@ -3241,6 +3523,12 @@ export class Game {
// Most search lines are a single effect. // Most search lines are a single effect.
if (this.pendingSearch) return if (this.pendingSearch) return
const player = this.getPlayer(playerId) const player = this.getPlayer(playerId)
// Searching then shuffling is the same as shuffling first when the picked
// cards go on top, and it keeps the shuffle from burying them again.
if (shuffle && (destination === 'top' || split?.destination === 'top')) {
this.shuffleLibrary(player)
shuffle = false
}
let remaining = amount let remaining = amount
let first = true let first = true
while (remaining > 0) { while (remaining > 0) {
@@ -3379,6 +3667,7 @@ export class Game {
const matches = selector.colors.map(color => colors.includes(color)) const matches = selector.colors.map(color => colors.includes(color))
if (selector.match === 'any' ? !matches.some(Boolean) : !matches.every(Boolean)) return false if (selector.match === 'any' ? !matches.some(Boolean) : !matches.every(Boolean)) return false
} }
if (selector.excludeColors?.some(color => color === 'C' ? colors.length === 0 : colors.includes(color))) return false
if (selector.tapped !== undefined && object.tapped !== selector.tapped) return false if (selector.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
@@ -3517,7 +3806,7 @@ export class Game {
const match = counter.match(/^([+-])(\d+)\/([+-])(\d+)$/) const match = counter.match(/^([+-])(\d+)\/([+-])(\d+)$/)
if (!match) continue if (!match) continue
const value = stat === 'power' ? `${match[1]}${match[2]}` : `${match[3]}${match[4]}` const value = stat === 'power' ? `${match[1]}${match[2]}` : `${match[3]}${match[4]}`
total += Number(value) total += Number(value) * count
} }
return total return total
} }

View File

@@ -5,7 +5,7 @@ import { getCardDefinition } from './catalog.js'
import { CREATURE_TYPES } from './creature-types.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, ManaColor, ManaPool, TargetChoice } from './types.js'
export class MatchError extends Error { export class MatchError extends Error {
constructor(message: string, readonly status = 400) { constructor(message: string, readonly status = 400) {
@@ -28,6 +28,8 @@ export interface ActionPayload {
mode?: number mode?: number
overload?: boolean overload?: boolean
choice?: string choice?: string
/** Mana color picked when activating a mana ability that can make several. */
color?: string
pay?: boolean pay?: boolean
position?: { x?: unknown; y?: unknown } position?: { x?: unknown; y?: unknown }
attackers?: { attackerId: string; defenderId: string }[] attackers?: { attackerId: string; defenderId: string }[]
@@ -60,7 +62,13 @@ export interface CardView {
blocking?: string blocking?: string
/** Creature type chosen as this permanent entered, if any. */ /** Creature type chosen as this permanent entered, if any. */
chosenType?: string chosenType?: string
abilities: { index: number; kind: string; text?: string }[] /** Number of face-down cards exiled under this permanent (hideaway). */
hiddenCards?: number
/** This exiled card is face down; its identity is not included. */
faceDown?: boolean
/** Legal choices for this card's targets, for the cast panel. */
targets?: TargetChoice[]
abilities: { index: number; kind: string; text?: string; targets?: TargetChoice[]; manaColors?: string[] }[]
/** Viewer-specific: can this card be played from hand right now? */ /** Viewer-specific: can this card be played from hand right now? */
playable?: boolean playable?: boolean
} }
@@ -136,6 +144,8 @@ export interface MatchView {
amount?: number amount?: number
/** Choices to offer, populated only for the chooser. */ /** Choices to offer, populated only for the chooser. */
options: string[] options: string[]
/** Cards to choose from for hideaway, populated only for the chooser. */
cards?: CardView[]
} }
} }
} }
@@ -426,6 +436,7 @@ export function performAction(matchId: string, token: string | undefined, action
x: Number.isFinite(action.x) ? Number(action.x) : 0, 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, overload: action.overload === true,
manaColor: manaColorOf(action.color),
} }
try { try {
@@ -457,6 +468,9 @@ 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_hideaway':
game.chooseHideawayCard(seat.playerId, requireId(action.cardId))
break
case 'choose_type': case 'choose_type':
if (typeof action.choice !== 'string') throw new MatchError('Missing type choice') if (typeof action.choice !== 'string') throw new MatchError('Missing type choice')
game.chooseCreatureType(seat.playerId, action.choice) game.chooseCreatureType(seat.playerId, action.choice)
@@ -503,9 +517,46 @@ function requireId(id: unknown): string {
return id return id
} }
function manaColorOf(value: unknown): ManaColor | undefined {
if (value === undefined) return undefined
if (typeof value !== 'string' || !/^[WUBRGCS]$/i.test(value)) throw new MatchError('Invalid mana color')
return value.toUpperCase() as ManaColor
}
function cardView(game: Game, object: GameObject, abilities = true): CardView { function cardView(game: Game, object: GameObject, abilities = true): CardView {
// Face-down exiled cards (hideaway) keep their identity server-side only.
if (object.faceDown) {
return {
id: object.id,
oracleId: '',
name: 'Face-down card',
typeLine: '',
colors: [],
colorIdentity: [],
tapped: false,
damage: 0,
counters: {},
isToken: false,
isCommander: false,
zone: object.zone,
controller: object.controller,
owner: object.owner,
blockedBy: [],
faceDown: true,
abilities: [],
}
}
const definition = object.definition const definition = object.definition
const creature = /creature/i.test(definition.typeLine) const creature = /creature/i.test(definition.typeLine)
const hiddenCards = object.zone === 'battlefield'
? (object.linkedExile ?? []).filter(id => {
const linked = game.objects.get(id)
return linked?.zone === 'exile' && linked.faceDown
}).length
: 0
const targets = object.zone === 'hand' || object.zone === 'command' || object.zone === 'exile'
? game.legalTargetsForCard(object.owner, object.id)
: []
return { return {
id: object.id, id: object.id,
oracleId: definition.oracleId, oracleId: definition.oracleId,
@@ -531,11 +582,17 @@ function cardView(game: Game, object: GameObject, abilities = true): CardView {
blockedBy: [...object.blockedBy], blockedBy: [...object.blockedBy],
blocking: object.blocking, blocking: object.blocking,
chosenType: object.chosenCreatureType, chosenType: object.chosenCreatureType,
hiddenCards: hiddenCards || undefined,
targets: targets.length ? targets : undefined,
abilities: abilities abilities: abilities
? (definition.abilities ?? []).map((ability, index) => ({ ? (definition.abilities ?? []).map((ability, index) => ({
index, index,
kind: ability.kind, kind: ability.kind,
text: 'text' in ability ? ability.text : undefined, text: 'text' in ability ? ability.text : undefined,
manaColors: game.manaColorChoices(object, index),
targets: ability.kind === 'activated' && object.zone === 'battlefield'
? game.legalTargetsForAbility(object.controller, object.id, index)
: undefined,
})) }))
: [], : [],
} }
@@ -560,6 +617,16 @@ function serialize(match: Match, viewerId: string): MatchView {
const game = match.game const game = match.game
if (!game) return view if (!game) return view
const hiddenUnderSource = new Set<string>()
for (const player of game.players) {
for (const id of player.battlefield) {
for (const linked of game.getObject(id).linkedExile ?? []) {
const object = game.objects.get(linked)
if (object?.zone === 'exile' && object.faceDown) hiddenUnderSource.add(linked)
}
}
}
view.players = match.seats.map(seat => { view.players = match.seats.map(seat => {
const player = game.getPlayer(seat.playerId) const player = game.getPlayer(seat.playerId)
return { return {
@@ -572,7 +639,15 @@ function serialize(match: Match, viewerId: string): MatchView {
libraryCount: player.library.length, libraryCount: player.library.length,
battlefield: player.battlefield.map(id => cardView(game, game.getObject(id))), battlefield: player.battlefield.map(id => cardView(game, game.getObject(id))),
graveyard: player.graveyard.map(id => cardView(game, game.getObject(id), false)), graveyard: player.graveyard.map(id => cardView(game, game.getObject(id), false)),
exile: player.exile.map(id => cardView(game, game.getObject(id), false)), exile: player.exile
.filter(id => !hiddenUnderSource.has(id))
.map(id => {
const playable = player.id === viewerId && game.canPlayCard(viewerId, id)
return {
...cardView(game, game.getObject(id), playable),
...(playable ? { playable } : {}),
}
}),
command: player.command.map(id => cardView(game, game.getObject(id), false)), command: player.command.map(id => cardView(game, game.getObject(id), false)),
commanderId: player.commanderId, commanderId: player.commanderId,
commanderDamage: Object.entries(player.commanderDamage) commanderDamage: Object.entries(player.commanderDamage)
@@ -621,6 +696,9 @@ function serialize(match: Match, viewerId: string): MatchView {
sourceName: game.objects.get(choice.sourceId)?.definition.name ?? 'Permanent', sourceName: game.objects.get(choice.sourceId)?.definition.name ?? 'Permanent',
amount: choice.amount, amount: choice.amount,
options: choice.playerId === viewerId && choice.what === 'creature_type' ? [...CREATURE_TYPES] : [], options: choice.playerId === viewerId && choice.what === 'creature_type' ? [...CREATURE_TYPES] : [],
cards: choice.playerId === viewerId && choice.what === 'hideaway'
? (choice.cardIds ?? []).map(id => cardView(game, game.getObject(id), false))
: undefined,
} }
: undefined, : undefined,
pendingSearch: search pendingSearch: search

414
backend/src/game/tokens.ts Normal file
View File

@@ -0,0 +1,414 @@
import type { Ability, Cost, Effect, StaticEffect } from '../effects/types.js'
/**
* The predefined tokens from rule 111.10. Effects that name one of these
* tokens ("create a Treasure token") use these characteristics instead of
* whatever the oracle parser managed to infer from the words.
*/
export interface PredefinedTokenFace {
name: string
types: string[]
subtypes: string[]
colors: string[]
power?: number
toughness?: number
keywords?: string[]
abilities?: Ability[]
}
export interface PredefinedToken extends PredefinedTokenFace {
/** Back face of a double-faced token, currently only Incubator. */
backFace?: PredefinedTokenFace
}
function activated(costs: Cost[], effects: Effect[], text: string, timing?: 'sorcery'): Ability {
return { kind: 'activated', costs, effects, timing, optional: false, text }
}
function anyColor(): Effect {
return {
op: 'add_mana',
player: 'you',
mana: { kind: 'any_color', amount: { kind: 'number', value: 1 }, oneColor: false },
}
}
function drawOne(): Effect {
return { op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } }
}
function pumpEnchanted(power: number, toughness: number): StaticEffect {
return {
op: 'pump',
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
power: { kind: 'number', value: power },
toughness: { kind: 'number', value: toughness },
}
}
function grantEnchanted(keyword: string, value?: string): StaticEffect {
return {
op: 'grant',
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
keyword,
...(value ? { value } : {}),
}
}
const tap: Cost = { kind: 'tap' }
const sacrificeSelf: Cost = { kind: 'sacrifice_self' }
const mana = (symbols: string): Cost => ({ kind: 'mana', symbols })
const enchantCreature: Ability = { kind: 'keyword', keyword: 'Enchant', value: 'creature' }
function attackTrigger(effects: Effect[], text: string, condition?: Extract<Ability, { kind: 'triggered' }>['condition']): Ability {
return {
kind: 'triggered',
event: {
kind: 'attacks',
subject: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
},
...(condition ? { condition } : {}),
effects,
optional: false,
text,
}
}
export const PREDEFINED_TOKENS: Record<string, PredefinedToken> = {
treasure: {
name: 'Treasure',
types: ['artifact'],
subtypes: ['treasure'],
colors: [],
abilities: [activated(
[tap, sacrificeSelf],
[anyColor()],
'{T}, Sacrifice this artifact: Add one mana of any color.',
)],
},
food: {
name: 'Food',
types: ['artifact'],
subtypes: ['food'],
colors: [],
abilities: [activated(
[mana('{2}'), tap, sacrificeSelf],
[{ op: 'life', player: 'you', amount: { kind: 'number', value: 3 }, mode: 'gain' }],
'{2}, {T}, Sacrifice this artifact: You gain 3 life.',
)],
},
gold: {
name: 'Gold',
types: ['artifact'],
subtypes: ['gold'],
colors: [],
abilities: [activated(
[sacrificeSelf],
[anyColor()],
'Sacrifice this artifact: Add one mana of any color.',
)],
},
walker: {
name: 'Walker',
types: ['creature'],
subtypes: ['zombie'],
colors: ['B'],
power: 2,
toughness: 2,
},
shard: {
name: 'Shard',
types: ['enchantment'],
subtypes: ['shard'],
colors: [],
abilities: [activated(
[mana('{2}'), sacrificeSelf],
[
{ op: 'scry', player: 'you', amount: { kind: 'number', value: 1 } },
drawOne(),
],
'{2}, Sacrifice this enchantment: Scry 1, then draw a card.',
)],
},
clue: {
name: 'Clue',
types: ['artifact'],
subtypes: ['clue'],
colors: [],
abilities: [activated(
[mana('{2}'), sacrificeSelf],
[drawOne()],
'{2}, Sacrifice this artifact: Draw a card.',
)],
},
blood: {
name: 'Blood',
types: ['artifact'],
subtypes: ['blood'],
colors: [],
abilities: [activated(
[mana('{1}'), tap, { kind: 'discard', amount: { kind: 'number', value: 1 }, player: 'you' }, sacrificeSelf],
[drawOne()],
'{1}, {T}, Discard a card, Sacrifice this artifact: Draw a card.',
)],
},
powerstone: {
name: 'Powerstone',
types: ['artifact'],
subtypes: ['powerstone'],
colors: [],
abilities: [activated(
[tap],
[{
op: 'add_mana',
player: 'you',
// shortcut: the pool does not track restricted mana yet, so this is
// usable for any spell. Upgrade when spell-type mana restrictions matter.
mana: { kind: 'symbols', symbols: ['{C}'], restriction: 'artifact spells' },
}],
'{T}: Add {C}. This mana can\'t be spent to cast a nonartifact spell.',
)],
},
incubator: {
name: 'Incubator',
types: ['artifact'],
subtypes: ['incubator'],
colors: [],
abilities: [activated(
[mana('{2}')],
[{ op: 'transform', target: { kind: 'self' } }],
'{2}: Transform this artifact.',
)],
backFace: {
name: 'Phyrexian',
types: ['artifact', 'creature'],
subtypes: ['phyrexian'],
colors: [],
power: 0,
toughness: 0,
},
},
map: {
name: 'Map',
types: ['artifact'],
subtypes: ['map'],
colors: [],
abilities: [activated(
[mana('{1}'), tap, sacrificeSelf],
[{
op: 'keyword_action',
action: 'explore',
target: { kind: 'object', selector: { types: ['creature'], controller: 'you' }, mode: 'target' },
}],
'{1}, {T}, Sacrifice this artifact: Target creature you control explores. Activate only as a sorcery.',
'sorcery',
)],
},
junk: {
name: 'Junk',
types: ['artifact'],
subtypes: ['junk'],
colors: [],
abilities: [activated(
[tap, sacrificeSelf],
[{ op: 'keyword_action', action: 'impulse' }],
'{T}, Sacrifice this artifact: Exile the top card of your library. You may play that card this turn. Activate only as a sorcery.',
'sorcery',
)],
},
lander: {
name: 'Lander',
types: ['artifact'],
subtypes: ['lander'],
colors: [],
abilities: [activated(
[mana('{2}'), tap, sacrificeSelf],
[{
op: 'search',
player: 'you',
selector: { supertypes: ['basic'], types: ['land'] },
amount: { kind: 'number', value: 1 },
destination: 'battlefield',
tapped: true,
shuffle: true,
}],
'{2}, {T}, Sacrifice this artifact: Search your library for a basic land card, put it onto the battlefield tapped, then shuffle.',
)],
},
mutagen: {
name: 'Mutagen',
types: ['artifact'],
subtypes: ['mutagen'],
colors: [],
abilities: [activated(
[mana('{1}'), tap, sacrificeSelf],
[{
op: 'put_counters',
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
counter: '+1/+1',
amount: { kind: 'number', value: 1 },
}],
'{1}, {T}, Sacrifice this artifact: Put a +1/+1 counter on target creature. Activate only as a sorcery.',
'sorcery',
)],
},
vibranium: {
name: 'Vibranium',
types: ['artifact'],
subtypes: ['vibranium'],
colors: [],
keywords: ['Indestructible'],
abilities: [activated(
[tap],
[{
op: 'add_mana',
player: 'you',
mana: { kind: 'symbols', symbols: ['{C}'], restriction: 'artifact spells' },
}],
'Indestructible\n{T}: Add {C}. This mana can\'t be spent to cast a nonartifact spell.',
)],
},
heartwood: {
name: 'Heartwood',
types: ['artifact'],
subtypes: ['heartwood'],
colors: ['R', 'G'],
abilities: [activated(
[tap],
[{
op: 'add_mana',
player: 'you',
mana: { kind: 'symbols', symbols: ['{R}', '{G}'], oneOf: true },
}],
'{T}: Add {R} or {G}.',
)],
},
cursed: {
name: 'Cursed Role',
types: ['enchantment'],
subtypes: ['aura', 'role'],
colors: [],
abilities: [
enchantCreature,
{
kind: 'static',
effects: [{
op: 'set_pt',
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
power: { kind: 'number', value: 1 },
toughness: { kind: 'number', value: 1 },
base: true,
}],
text: 'Enchanted creature has base power and toughness 1/1.',
},
],
},
monster: {
name: 'Monster Role',
types: ['enchantment'],
subtypes: ['aura', 'role'],
colors: [],
abilities: [
enchantCreature,
{ kind: 'static', effects: [pumpEnchanted(1, 1), grantEnchanted('Trample')], text: 'Enchanted creature gets +1/+1 and has trample.' },
],
},
royal: {
name: 'Royal Role',
types: ['enchantment'],
subtypes: ['aura', 'role'],
colors: [],
abilities: [
enchantCreature,
{ kind: 'static', effects: [pumpEnchanted(1, 1), grantEnchanted('Ward', '{1}')], text: 'Enchanted creature gets +1/+1 and has ward {1}.' },
],
},
sorcerer: {
name: 'Sorcerer Role',
types: ['enchantment'],
subtypes: ['aura', 'role'],
colors: [],
abilities: [
enchantCreature,
{ kind: 'static', effects: [pumpEnchanted(1, 1)], text: 'Enchanted creature gets +1/+1.' },
attackTrigger(
[{ op: 'scry', player: 'you', amount: { kind: 'number', value: 1 } }],
'Whenever enchanted creature attacks, scry 1.',
),
],
},
virtuous: {
name: 'Virtuous Role',
types: ['enchantment'],
subtypes: ['aura', 'role'],
colors: [],
abilities: [
enchantCreature,
{
kind: 'static',
effects: [{
op: 'pump',
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
power: { kind: 'count', selector: { types: ['enchantment'], controller: 'you' } },
toughness: { kind: 'count', selector: { types: ['enchantment'], controller: 'you' } },
}],
text: 'Enchanted creature gets +1/+1 for each enchantment you control.',
},
],
},
wicked: {
name: 'Wicked Role',
types: ['enchantment'],
subtypes: ['aura', 'role'],
colors: [],
abilities: [
enchantCreature,
{ kind: 'static', effects: [pumpEnchanted(1, 1)], text: 'Enchanted creature gets +1/+1.' },
{
kind: 'triggered',
// Curse of the Werefox and friends put this in the graveyard; the
// engine only distinguishes "died" for creatures, so any leave triggers it.
event: { kind: 'leaves_battlefield', subject: { kind: 'self' } },
effects: [{ op: 'life', player: 'each_opponent', amount: { kind: 'number', value: 1 }, mode: 'lose' }],
optional: false,
text: 'When this token is put into a graveyard from the battlefield, each opponent loses 1 life.',
},
],
},
'young hero': {
name: 'Young Hero Role',
types: ['enchantment'],
subtypes: ['aura', 'role'],
colors: [],
abilities: [
enchantCreature,
attackTrigger(
[{
op: 'put_counters',
target: { kind: 'trigger_subject' },
counter: '+1/+1',
amount: { kind: 'number', value: 1 },
}],
'Whenever enchanted creature attacks, if its toughness is 3 or less, put a +1/+1 counter on it.',
{ kind: 'event_subject_toughness_at_most', amount: 3 },
),
],
},
}
/** Finds a predefined token by subtype or name, including "Cursed Role". */
export function predefinedToken(spec: { name?: string; subtypes: string[] }): PredefinedToken | undefined {
const words = spec.subtypes.map(word => word.toLowerCase())
const roleIndex = words.indexOf('role')
const candidates = roleIndex >= 0 ? [words.slice(0, roleIndex).join(' ')] : []
candidates.push(...words)
for (const candidate of candidates) {
const token = PREDEFINED_TOKENS[candidate]
if (token) return token
}
if (spec.name) {
const name = spec.name.toLowerCase()
return PREDEFINED_TOKENS[name] ?? PREDEFINED_TOKENS[name.replace(/\s+role$/, '')]
}
return undefined
}

View File

@@ -94,6 +94,10 @@ export interface GameObject {
counters: Record<string, number> counters: Record<string, number>
isToken: boolean isToken: boolean
token?: TokenSpec token?: TokenSpec
/** Back face of a double-faced token (Incubator); transform swaps it in. */
backFace?: CardDefinition
/** Set by impulse effects; the card may be played from exile this turn. */
playableFromExileTurn?: number
isCommander?: boolean isCommander?: boolean
enteredTurn: number enteredTurn: number
/** Normalized center on the controller's mat; absent means auto-arranged. */ /** Normalized center on the controller's mat; absent means auto-arranged. */
@@ -105,6 +109,8 @@ export interface GameObject {
attachedTo?: string attachedTo?: string
/** Cards exiled with this object, such as a card hidden by hideaway. */ /** Cards exiled with this object, such as a card hidden by hideaway. */
linkedExile?: string[] linkedExile?: string[]
/** Exiled face down (hideaway); its identity is hidden from every view. */
faceDown?: boolean
/** Creature type chosen as this permanent entered (Cavern of Souls). */ /** Creature type chosen as this permanent entered (Cavern of Souls). */
chosenCreatureType?: string chosenCreatureType?: string
regenerationShields: number regenerationShields: number
@@ -136,6 +142,8 @@ export interface ActionOptions {
x?: number x?: number
mode?: number mode?: number
overload?: boolean overload?: boolean
/** Color chosen for a mana ability that can produce more than one. */
manaColor?: ManaColor
} }
/** A search that is waiting for its player to pick one of several matching cards. */ /** A search that is waiting for its player to pick one of several matching cards. */
@@ -151,15 +159,17 @@ export interface PendingSearch {
split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean } split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean }
} }
/** An "as this enters..." pause. Blocks all actions until its controller picks. */ /** A pause such as "as this enters..." or a hideaway look. Blocks all actions until its controller picks. */
export interface PendingChoice { export interface PendingChoice {
playerId: string playerId: string
sourceId: string sourceId: string
what: 'creature_type' | 'pay_cost' what: 'creature_type' | 'pay_cost' | 'hideaway'
/** Cost to pay to avoid entering tapped. */ /** Cost to pay to avoid entering tapped. */
cost?: Cost cost?: Cost
/** Life total to display for a `pay_life` cost. */ /** Life total to display for a `pay_life` cost. */
amount?: number amount?: number
/** Cards to choose from for `hideaway`. */
cardIds?: string[]
} }
export interface CombatAttack { export interface CombatAttack {

View File

@@ -84,6 +84,46 @@ Deck
assert.match(result.errors.join(' '), /exactly 100/) assert.match(result.errors.join(' '), /exactly 100/)
}) })
test('a commander identity mana source only offers colors in the identity', () => {
const game = new Game({
seed: 1,
startingHandSize: 0,
commander: true,
players: [
{ id: 'p1', deck: [basicLand('Forest')], commander: commanderDefinition('Test Commander', { colors: ['U', 'R'], colorIdentity: ['U', 'R'] }) },
{ id: 'p2', deck: [basicLand('Forest')], commander: commanderDefinition('Other Commander') },
],
})
game.start()
const tower = game.addCard('p1', {
oracleId: 'command-tower',
name: 'Command Tower',
typeLine: 'Land',
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{
op: 'add_mana',
player: 'you',
mana: {
kind: 'any_color',
amount: { kind: 'number', value: 1 },
oneColor: false,
restriction: "commander's color identity",
},
}],
optional: false,
text: "{T}: Add one mana of any color in your commander's color identity.",
}],
}, 'battlefield')
assert.deepEqual(game.manaColorChoices(tower, 0), ['U', 'R'])
assert.throws(() => game.activateAbility('p1', tower.id, 0, { manaColor: 'G' }), /cannot produce/)
assert.equal(tower.tapped, false)
game.activateAbility('p1', tower.id, 0, { manaColor: 'R' })
assert.equal(game.getPlayer('p1').manaPool.R, 1)
})
test('a commander starts in the command zone, pays tax, and returns there from the graveyard', () => { test('a commander starts in the command zone, pays tax, and returns there from the graveyard', () => {
const commander = commanderDefinition('Test Commander') const commander = commanderDefinition('Test Commander')
const game = new Game({ const game = new Game({
@@ -91,8 +131,8 @@ test('a commander starts in the command zone, pays tax, and returns there from t
startingHandSize: 0, startingHandSize: 0,
commander: true, commander: true,
players: [ players: [
{ id: 'p1', deck: [], commander }, { id: 'p1', deck: [basicLand('Forest')], commander },
{ id: 'p2', deck: [], commander: commanderDefinition('Other Commander') }, { id: 'p2', deck: [basicLand('Forest')], commander: commanderDefinition('Other Commander') },
], ],
}) })
game.start() game.start()
@@ -138,8 +178,8 @@ test('twenty-one commander damage loses the game', () => {
startingHandSize: 0, startingHandSize: 0,
commander: true, commander: true,
players: [ players: [
{ id: 'p1', deck: [], commander }, { id: 'p1', deck: [basicLand('Forest')], commander },
{ id: 'p2', deck: [], commander: commanderDefinition('Other Commander') }, { id: 'p2', deck: [basicLand('Forest')], commander: commanderDefinition('Other Commander') },
], ],
}) })
game.start() game.start()

View File

@@ -175,6 +175,24 @@ test('static anthem', () => {
assert.equal(target.selector.controller, 'you') assert.equal(target.selector.controller, 'you')
}) })
test('negative colors become an excluded color filter', () => {
const [ability] = spell('Destroy target nonblack creature.')
assert.equal(ability.kind, 'spell')
if (ability.kind !== 'spell') return
assert.deepEqual(ability.effects[0], {
op: 'destroy',
target: {
kind: 'object',
selector: { types: ['creature'], excludeColors: ['B'] },
mode: 'target',
},
})
const source = formatAbility(ability)
assert.match(source, /withoutColor\('black'\)/)
assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
})
test('enters-with-counters is a static replacement effect', () => { test('enters-with-counters is a static replacement effect', () => {
const [ability] = creature('This creature enters with X +1/+1 counters on it.') const [ability] = creature('This creature enters with X +1/+1 counters on it.')
assert.equal(ability.kind, 'static') assert.equal(ability.kind, 'static')
@@ -234,6 +252,36 @@ test('token copy of the triggering nontoken Dragon loses legendary', () => {
) )
}) })
test('token-doubling replacement lines compile and round-trip', () => {
const cases: Array<[string, object]> = [
[
'If an effect would create one or more tokens under your control, it creates twice that many of those tokens instead.',
{ op: 'token_multiplier', multiplier: 2, who: 'you' },
],
[
'If one or more tokens would be created under your control, twice that many of those tokens are created instead.',
{ op: 'token_multiplier', multiplier: 2, who: 'you' },
],
[
'If one or more tokens would be created, twice that many of those tokens are created instead.',
{ op: 'token_multiplier', multiplier: 2, who: 'each_player' },
],
[
'If one or more creature tokens would be created under your control, three times that many of those tokens are created instead.',
{ op: 'token_multiplier', multiplier: 3, who: 'you', creatureOnly: true },
],
]
for (const [text, expected] of cases) {
const [ability] = creature(text)
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
assert.deepEqual(ability.effects[0], expected)
const source = formatAbility(ability)
assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
}
})
test('all effects are typed', () => { test('all effects are typed', () => {
const [ability] = spell('Draw two cards, then discard a card.') const [ability] = spell('Draw two cards, then discard a card.')
assert.equal(ability.kind, 'spell') assert.equal(ability.kind, 'spell')
@@ -577,3 +625,24 @@ test('new abilities, effects and conditions round-trip through card source', ()
assert.equal(formatAbility(reparsed), source) assert.equal(formatAbility(reparsed), source)
} }
}) })
test('Role token creation compiles with the attachment target', () => {
for (const role of ['Cursed', 'Monster', 'Royal', 'Sorcerer', 'Virtuous', 'Wicked', 'Young Hero']) {
const [ability] = spell(`Create a ${role} Role token attached to target creature you control.`)
assert.equal(ability.kind, 'spell')
if (ability.kind !== 'spell') return
const effect = ability.effects[0]
assert.equal(effect.op, 'create_token')
if (effect.op !== 'create_token') return
assert.equal(effect.token.name, role)
assert.deepEqual(effect.token.subtypes, ['aura', 'role'])
assert.deepEqual(effect.attachTo, {
kind: 'object',
selector: { controller: 'you', types: ['creature'] },
mode: 'target',
})
const source = formatAbility(ability)
assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
}
})

View File

@@ -1,8 +1,8 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import test from 'node:test' import test from 'node:test'
import { Game, GameError } from '../src/game/game.js' import { Game, GameError } from '../src/game/game.js'
import type { Ability, Effect } from '../src/effects/types.js' import type { Ability, Effect, TokenSpec } from '../src/effects/types.js'
import type { CardDefinition } from '../src/game/types.js' import type { CardDefinition, GameObject } from '../src/game/types.js'
function card(name: string, overrides: Partial<CardDefinition> = {}): CardDefinition { function card(name: string, overrides: Partial<CardDefinition> = {}): CardDefinition {
return { return {
@@ -72,6 +72,71 @@ function setup(players: { id: string; deck?: CardDefinition[]; life?: number }[]
return game return game
} }
function tokenMaker(name: string, token: TokenSpec): CardDefinition {
return card(name, {
typeLine: 'Artifact',
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'create_token', player: 'you', amount: { kind: 'number', value: 1 }, token }],
optional: false,
text: '{T}: Create a token.',
}],
})
}
function tokenDoubler(
name: string,
multiplier: number,
who: 'you' | 'each_player' = 'you',
creatureOnly = false,
): CardDefinition {
return card(name, {
typeLine: 'Enchantment',
abilities: [{
kind: 'static',
effects: [{ op: 'token_multiplier', multiplier, who, ...(creatureOnly ? { creatureOnly: true } : {}) }],
text: 'Token replacement.',
}],
})
}
function makeToken(game: Game, token: TokenSpec, playerId = 'p1'): GameObject {
const maker = game.addCard(playerId, tokenMaker('Token Maker', token), 'battlefield')
game.activateAbility(playerId, maker.id, 0)
game.resolveStack()
const tokens = game.getPlayer(playerId).battlefield
.map(id => game.getObject(id))
.filter(object => object.isToken)
return tokens[tokens.length - 1]
}
function addMana(game: Game, ...symbols: string[]): void {
for (const symbol of symbols) {
const source = game.addCard('p1', land('Mana Land', symbol), 'battlefield')
game.activateAbility('p1', source.id, 0)
}
}
function roleMaker(name: string): CardDefinition {
return card(`${name} Role Maker`, {
typeLine: 'Enchantment',
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{
op: 'create_token',
player: 'you',
amount: { kind: 'number', value: 1 },
token: { name, types: ['enchantment'], subtypes: ['aura', 'role'], colors: [] },
attachTo: { kind: 'object', selector: { types: ['creature'], controller: 'you' }, mode: 'target' },
}],
optional: false,
text: `{T}: Create a ${name} Role token attached to target creature you control.`,
}],
})
}
test('turns start at the first main phase, draw opening hands, and pass to the next player', () => { test('turns start at the first main phase, draw opening hands, and pass to the next player', () => {
const forest = land('Forest', 'G') const forest = land('Forest', 'G')
const game = new Game({ const game = new Game({
@@ -90,8 +155,8 @@ test('turns start at the first main phase, draw opening hands, and pass to the n
assert.equal(game.step, 'main') assert.equal(game.step, 'main')
assert.equal(game.priority, 'p1') assert.equal(game.priority, 'p1')
assert.equal(game.getPlayer('p1').life, 40) assert.equal(game.getPlayer('p1').life, 40)
assert.equal(game.getPlayer('p1').hand.length, 7) assert.equal(game.getPlayer('p1').hand.length, 8)
assert.equal(game.getPlayer('p1').library.length, 3) assert.equal(game.getPlayer('p1').library.length, 2)
game.endTurn('p1') game.endTurn('p1')
@@ -143,7 +208,7 @@ test('mulligans draw a new seven and bottom one more card each time', () => {
assert.equal(game.status, 'active') assert.equal(game.status, 'active')
assert.equal(game.turn, 1) assert.equal(game.turn, 1)
assert.equal(game.step, 'main') assert.equal(game.step, 'main')
assert.equal(game.getPlayer('p1').hand.length, 5) assert.equal(game.getPlayer('p1').hand.length, 6)
}) })
test('passing priority twice advances from the main phase into combat', () => { test('passing priority twice advances from the main phase into combat', () => {
@@ -223,6 +288,9 @@ test('hideaway exiles a card and its linked ability plays it for free once the c
const game = setup([{ id: 'p1' }, { id: 'p2' }]) const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start() game.start()
const hidden = game.addCard('p1', creature('Hidden Bear', 2, 2), 'library') const hidden = game.addCard('p1', creature('Hidden Bear', 2, 2), 'library')
for (const name of ['Filler One', 'Filler Two', 'Filler Three']) {
game.addCard('p1', creature(name, 1, 1), 'library')
}
const library = game.getPlayer('p1').library const library = game.getPlayer('p1').library
library.splice(library.indexOf(hidden.id), 1) library.splice(library.indexOf(hidden.id), 1)
library.unshift(hidden.id) library.unshift(hidden.id)
@@ -231,8 +299,22 @@ test('hideaway exiles a card and its linked ability plays it for free once the c
game.playLand('p1', land.id) game.playLand('p1', land.id)
game.resolveStack() game.resolveStack()
assert.equal(game.pendingChoice?.what, 'hideaway')
assert.equal(game.pendingChoice?.playerId, 'p1')
assert.equal(game.pendingChoice?.cardIds?.length, 4)
assert.ok(game.pendingChoice?.cardIds?.includes(hidden.id))
assert.throws(() => game.chooseHideawayCard('p2', hidden.id), GameError)
const looked = [...game.getPlayer('p1').library.slice(0, 4)]
game.chooseHideawayCard('p1', hidden.id)
assert.equal(game.pendingChoice, undefined)
assert.equal(hidden.zone, 'exile') assert.equal(hidden.zone, 'exile')
assert.equal(hidden.faceDown, true)
assert.deepEqual(land.linkedExile, [hidden.id]) assert.deepEqual(land.linkedExile, [hidden.id])
assert.deepEqual(
game.getPlayer('p1').library.slice(-3).sort(),
looked.filter(id => id !== hidden.id).sort(),
)
game.activateAbility('p1', land.id, 1) game.activateAbility('p1', land.id, 1)
game.resolveStack() game.resolveStack()
@@ -243,6 +325,7 @@ test('hideaway exiles a card and its linked ability plays it for free once the c
game.resolveStack() game.resolveStack()
assert.equal(hidden.zone, 'battlefield') assert.equal(hidden.zone, 'battlefield')
assert.equal(hidden.faceDown, undefined)
assert.ok(game.getPlayer('p1').battlefield.includes(hidden.id)) assert.ok(game.getPlayer('p1').battlefield.includes(hidden.id))
}) })
@@ -281,6 +364,7 @@ test('playing a card hidden by hideaway uses the land drop', () => {
game.playLand('p1', source.id) game.playLand('p1', source.id)
game.resolveStack() game.resolveStack()
assert.equal(hidden.zone, 'exile') assert.equal(hidden.zone, 'exile')
assert.equal(hidden.faceDown, true)
game.getPlayer('p1').landPlayedThisTurn = true game.getPlayer('p1').landPlayedThisTurn = true
game.activateAbility('p1', source.id, 1) game.activateAbility('p1', source.id, 1)
@@ -399,6 +483,59 @@ test('Exotic Orchard produces nothing without an opponent land', () => {
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 }) assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 })
}) })
test('a mana ability that makes one of several colors uses the chosen color', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const dual = game.addCard('p1', card('Dual Land', {
typeLine: 'Land',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{W}', '{U}'], oneOf: true } }],
optional: false,
text: '{T}: Add {W} or {U}.',
}],
}), 'battlefield')
assert.deepEqual(game.manaColorChoices(dual, 0), ['W', 'U'])
game.activateAbility('p1', dual.id, 0, { manaColor: 'U' })
assert.equal(game.getPlayer('p1').manaPool.U, 1)
assert.equal(game.getPlayer('p1').manaPool.W, 0)
})
test('a mana color the ability cannot make is rejected before tapping', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const mono = game.addCard('p1', land('Mono Land', 'W'), 'battlefield')
assert.throws(() => game.activateAbility('p1', mono.id, 0, { manaColor: 'G' }), GameError)
assert.equal(mono.tapped, false)
assert.equal(game.getPlayer('p1').manaPool.G, 0)
})
test('an any-color mana source produces the chosen color and offers all five', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const rainbow = game.addCard('p1', card('Rainbow Land', {
typeLine: 'Land',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'any_color', amount: { kind: 'number', value: 1 }, oneColor: false } }],
optional: false,
text: '{T}: Add one mana of any color.',
}],
}), 'battlefield')
assert.deepEqual(game.manaColorChoices(rainbow, 0), ['W', 'U', 'B', 'R', 'G'])
game.activateAbility('p1', rainbow.id, 0, { manaColor: 'R' })
assert.equal(game.getPlayer('p1').manaPool.R, 1)
})
test('a restricted mana source is used before an unrestricted one', () => { test('a restricted mana source is used before an unrestricted one', () => {
const rainbow = card('Rainbow Land', { const rainbow = card('Rainbow Land', {
typeLine: 'Land', typeLine: 'Land',
@@ -475,6 +612,58 @@ test('temporary pump effects expire at end of turn', () => {
assert.equal(game.getPower(bear), 2) assert.equal(game.getPower(bear), 2)
}) })
test('the engine exposes legal creature targets for a card', () => {
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
game.start()
const bear = game.addCard('p2', creature('Grizzly Bears', 2, 2), 'battlefield')
const growth = game.addCard('p1', spell('Giant Growth', [{
op: 'pump',
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
power: { kind: 'number', value: 3 },
toughness: { kind: 'number', value: 3 },
duration: 'until_end_of_turn',
}]), 'hand')
assert.deepEqual(game.legalTargetsForCard('p1', growth.id), [{ kind: 'object', id: bear.id }])
})
test('excluded colors filter legal targets', () => {
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
game.start()
game.addCard('p2', card('Black Bear', { typeLine: 'Creature — Bear', colors: ['B'], power: 2, toughness: 2 }), 'battlefield')
const green = game.addCard('p2', card('Green Bear', { typeLine: 'Creature — Bear', colors: ['G'], power: 2, toughness: 2 }), 'battlefield')
const doomBlade = game.addCard('p1', spell('Doom Blade', [{
op: 'destroy',
target: { kind: 'object', selector: { types: ['creature'], excludeColors: ['B'] }, mode: 'target' },
}]), 'hand')
assert.deepEqual(game.legalTargetsForCard('p1', doomBlade.id), [{ kind: 'object', id: green.id }])
})
test('the engine exposes legal targets for an activated ability', () => {
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
game.start()
const bear = game.addCard('p2', creature('Grizzly Bears', 2, 2), 'battlefield')
const pinger = game.addCard('p1', card('Pinger', {
typeLine: 'Creature — Test',
power: 1,
toughness: 1,
abilities: [{
kind: 'activated',
costs: [],
optional: false,
text: '{T}: This creature deals 1 damage to target creature an opponent controls.',
effects: [{
op: 'damage',
target: { kind: 'object', selector: { controller: 'opponent', types: ['creature'] }, mode: 'target' },
amount: { kind: 'number', value: 1 },
}],
}],
}), 'battlefield')
assert.deepEqual(game.legalTargetsForAbility('p1', pinger.id, 0), [{ kind: 'object', id: bear.id }])
})
test('"until the end of your next turn" lasts through the controller next turn', () => { test('"until the end of your next turn" lasts through the controller next turn', () => {
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }]) const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
game.start() game.start()
@@ -590,6 +779,86 @@ test('activated abilities create tokens that enter the battlefield', () => {
assert.equal(game.getPower(tokens[0]), 1) assert.equal(game.getPower(tokens[0]), 1)
}) })
test('token doublers stack and only apply to their controller', () => {
const goblin: TokenSpec = {
types: ['creature'],
subtypes: ['goblin'],
colors: ['R'],
power: { kind: 'number', value: 1 },
toughness: { kind: 'number', value: 1 },
}
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const p1Maker = game.addCard('p1', tokenMaker('P1 Maker', goblin), 'battlefield')
game.addCard('p1', tokenDoubler('Parallel Lives', 2), 'battlefield')
game.addCard('p1', tokenDoubler('Anointed Procession', 2), 'battlefield')
const p2Maker = game.addCard('p2', tokenMaker('P2 Maker', goblin), 'battlefield')
game.addCard('p2', tokenDoubler('Adrix and Nev', 2), 'battlefield')
const tokensOf = (playerId: string): number => game.getPlayer(playerId).battlefield
.map(id => game.getObject(id)).filter(object => object.isToken).length
game.activateAbility('p1', p1Maker.id, 0)
game.resolveStack()
assert.equal(tokensOf('p1'), 4)
assert.equal(tokensOf('p2'), 0)
game.endTurn('p1')
game.activateAbility('p2', p2Maker.id, 0)
game.resolveStack()
assert.equal(tokensOf('p2'), 2)
})
test('Primal Vigor doubles tokens for every player', () => {
const goblin: TokenSpec = {
types: ['creature'],
subtypes: ['goblin'],
colors: ['R'],
power: { kind: 'number', value: 1 },
toughness: { kind: 'number', value: 1 },
}
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const p1Maker = game.addCard('p1', tokenMaker('P1 Maker', goblin), 'battlefield')
game.addCard('p1', tokenDoubler('Primal Vigor', 2, 'each_player'), 'battlefield')
const p2Maker = game.addCard('p2', tokenMaker('P2 Maker', goblin), 'battlefield')
const tokensOf = (playerId: string): number => game.getPlayer(playerId).battlefield
.map(id => game.getObject(id)).filter(object => object.isToken).length
game.activateAbility('p1', p1Maker.id, 0)
game.resolveStack()
assert.equal(tokensOf('p1'), 2)
game.endTurn('p1')
game.activateAbility('p2', p2Maker.id, 0)
game.resolveStack()
assert.equal(tokensOf('p2'), 2)
})
test('Ojer Taq triples creature tokens but not other tokens', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const creatureMaker = game.addCard('p1', tokenMaker('Creature Maker', {
types: ['creature'],
subtypes: ['goblin'],
colors: ['R'],
power: { kind: 'number', value: 1 },
toughness: { kind: 'number', value: 1 },
}), 'battlefield')
const treasureMaker = game.addCard('p1', tokenMaker('Treasure Maker', {
types: ['artifact'], subtypes: ['treasure'], colors: [],
}), 'battlefield')
game.addCard('p1', tokenDoubler('Ojer Taq', 3, 'you', true), 'battlefield')
game.activateAbility('p1', creatureMaker.id, 0)
game.resolveStack()
game.activateAbility('p1', treasureMaker.id, 0)
game.resolveStack()
const tokens = game.getPlayer('p1').battlefield.map(id => game.getObject(id)).filter(object => object.isToken)
assert.equal(tokens.filter(object => object.definition.typeLine.toLowerCase().includes('creature')).length, 3)
assert.equal(tokens.filter(object => object.definition.typeLine.toLowerCase().includes('treasure')).length, 1)
})
test('search effects find cards in the library and put them onto the battlefield tapped', () => { test('search effects find cards in the library and put them onto the battlefield tapped', () => {
const forest = land('Forest', 'G') const forest = land('Forest', 'G')
const game = setup([{ id: 'p1' }, { id: 'p2' }]) const game = setup([{ id: 'p1' }, { id: 'p2' }])
@@ -648,6 +917,33 @@ 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('a search that shuffles and puts the chosen card on top leaves it on top', () => {
const bear = creature('Bear', 2, 2)
const elf = creature('Elf', 1, 1)
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const bearObject = game.addCard('p1', bear, 'library')
const elfObject = game.addCard('p1', elf, 'library')
const worldlyTutor = game.addCard('p1', spell('Worldly Tutor', [{
op: 'search',
player: 'you',
selector: { types: ['creature'] },
amount: { kind: 'number', value: 1 },
destination: 'top',
tapped: false,
shuffle: true,
}]), 'hand')
game.castSpell('p1', worldlyTutor.id)
game.resolveStack()
assert.equal(game.pendingSearch?.playerId, 'p1')
game.chooseSearchCard('p1', elfObject.id)
assert.equal(game.getPlayer('p1').library[0], elfObject.id)
assert.ok(game.getPlayer('p1').library.includes(bearObject.id))
})
test('as-enters creature type choices pause until the controller picks', () => { test('as-enters creature type choices pause until the controller picks', () => {
const cavern = card('Cavern of Souls', { const cavern = card('Cavern of Souls', {
typeLine: 'Land', typeLine: 'Land',
@@ -1031,7 +1327,7 @@ test('counter-removal costs are paid and fail when counters run out', () => {
game.activateAbility('p1', source.id, 0) game.activateAbility('p1', source.id, 0)
game.resolveStack() game.resolveStack()
assert.equal(source.counters.spore, 1) assert.equal(source.counters.spore, 1)
assert.equal(game.getPlayer('p1').hand.length, 1) assert.equal(game.getPlayer('p1').hand.length, 2)
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)
@@ -1460,3 +1756,186 @@ test('Field of the Dead makes a Zombie at seven differently named lands', () =>
assert.equal(tokens.length, 1) assert.equal(tokens.length, 1)
assert.equal(tokens[0].definition.typeLine.toLowerCase().includes('zombie'), true) assert.equal(tokens[0].definition.typeLine.toLowerCase().includes('zombie'), true)
}) })
test('predefined Treasure, Gold, Powerstone, Heartwood, and Vibranium tokens produce mana', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const treasure = makeToken(game, { types: ['artifact'], subtypes: ['treasure'], colors: [] })
assert.equal(treasure.definition.name, 'Treasure')
game.activateAbility('p1', treasure.id, 0, { manaColor: 'G' })
assert.equal(game.getPlayer('p1').manaPool.G, 1)
assert.equal(treasure.zone, 'graveyard')
const gold = makeToken(game, { types: ['artifact'], subtypes: ['gold'], colors: [] })
game.activateAbility('p1', gold.id, 0, { manaColor: 'R' })
assert.equal(game.getPlayer('p1').manaPool.R, 1)
const powerstone = makeToken(game, { types: ['artifact'], subtypes: ['powerstone'], colors: [] })
game.activateAbility('p1', powerstone.id, 0)
assert.equal(game.getPlayer('p1').manaPool.C, 1)
const heartwood = makeToken(game, { types: ['artifact'], subtypes: ['heartwood'], colors: [] })
game.activateAbility('p1', heartwood.id, 0, { manaColor: 'G' })
assert.equal(game.getPlayer('p1').manaPool.G, 2)
const vibranium = makeToken(game, { types: ['artifact'], subtypes: ['vibranium'], colors: [] })
assert.equal(game.hasKeyword(vibranium, 'Indestructible'), true)
game.activateAbility('p1', vibranium.id, 0)
assert.equal(game.getPlayer('p1').manaPool.C, 2)
})
test('predefined Food, Clue, Blood, and Shard tokens sacrifice for their effects', () => {
const game = setup([{
id: 'p1',
deck: Array.from({ length: 6 }, (_, index) => card(`Filler ${index}`)),
}, { id: 'p2' }])
game.start()
const food = makeToken(game, { types: ['artifact'], subtypes: ['food'], colors: [] })
addMana(game, 'G', 'G')
game.activateAbility('p1', food.id, 0)
game.resolveStack()
assert.equal(game.getPlayer('p1').life, 43)
assert.equal(food.zone, 'graveyard')
game.addCard('p1', card('Discard Fodder'), 'hand')
const discard = game.getObject(game.getPlayer('p1').hand[0])
const handAfterFood = game.getPlayer('p1').hand.length
const blood = makeToken(game, { types: ['artifact'], subtypes: ['blood'], colors: [] })
addMana(game, 'G')
game.activateAbility('p1', blood.id, 0)
game.resolveStack()
assert.equal(discard.zone, 'graveyard')
assert.equal(game.getPlayer('p1').hand.length, handAfterFood)
const clue = makeToken(game, { types: ['artifact'], subtypes: ['clue'], colors: [] })
addMana(game, 'G', 'G')
game.activateAbility('p1', clue.id, 0)
game.resolveStack()
assert.equal(game.getPlayer('p1').hand.length, handAfterFood + 1)
const shard = makeToken(game, { types: ['enchantment'], subtypes: ['shard'], colors: [] })
addMana(game, 'G', 'G')
game.activateAbility('p1', shard.id, 0)
game.resolveStack()
assert.equal(game.getPlayer('p1').hand.length, handAfterFood + 2)
})
test('Walker and Incubator tokens use their predefined characteristics', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const walker = makeToken(game, { types: ['artifact'], subtypes: ['walker'], colors: [] })
assert.equal(walker.definition.name, 'Walker')
assert.equal(game.getPower(walker), 2)
assert.equal(game.getToughness(walker), 2)
assert.deepEqual(walker.definition.colors, ['B'])
const maker = game.addCard('p1', card('Incubator Maker', {
typeLine: 'Artifact',
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'keyword_action', action: 'incubate', amount: { kind: 'number', value: 2 } }],
optional: false,
text: '{T}: Incubate 2.',
}],
}), 'battlefield')
game.activateAbility('p1', maker.id, 0)
game.resolveStack()
const incubator = game.getPlayer('p1').battlefield
.map(id => game.getObject(id))
.find(object => object.isToken && object.definition.name === 'Incubator')
assert.ok(incubator)
assert.equal(incubator.counters['+1/+1'], 2)
addMana(game, 'G', 'G')
game.activateAbility('p1', incubator.id, 0)
game.resolveStack()
assert.equal(incubator.definition.name, 'Phyrexian')
assert.equal(game.getPower(incubator), 2)
assert.equal(game.getToughness(incubator), 2)
})
test('predefined Map, Lander, and Mutagen tokens use their activated abilities', () => {
const mapGame = setup([{ id: 'p1', deck: [card('Filler')] }, { id: 'p2' }])
mapGame.start()
const topCard = mapGame.addCard('p1', card('Top Card'), 'library')
const bear = mapGame.addCard('p1', creature('Bear', 2, 2), 'battlefield')
addMana(mapGame, 'G')
const map = makeToken(mapGame, { types: ['artifact'], subtypes: ['map'], colors: [] })
mapGame.activateAbility('p1', map.id, 0, { targets: [{ kind: 'object', id: bear.id }] })
mapGame.resolveStack()
assert.equal(bear.counters['+1/+1'], 1)
assert.equal(topCard.zone, 'graveyard')
addMana(mapGame, 'G')
const mutagen = makeToken(mapGame, { types: ['artifact'], subtypes: ['mutagen'], colors: [] })
mapGame.activateAbility('p1', mutagen.id, 0, { targets: [{ kind: 'object', id: bear.id }] })
mapGame.resolveStack()
assert.equal(bear.counters['+1/+1'], 2)
const landGame = setup([{ id: 'p1', deck: [card('Filler')] }, { id: 'p2' }])
landGame.start()
const forest = landGame.addCard('p1', land('Forest', 'G'), 'library')
addMana(landGame, 'G', 'G')
const lander = makeToken(landGame, { types: ['artifact'], subtypes: ['lander'], colors: [] })
landGame.activateAbility('p1', lander.id, 0)
landGame.resolveStack()
assert.equal(forest.zone, 'battlefield')
assert.equal(forest.tapped, true)
})
test('Junk exiles the top card and lets its controller cast it that turn', () => {
const game = setup([{ id: 'p1', deck: [card('Filler')] }, { id: 'p2' }])
game.start()
const exiled = game.addCard('p1', spell('Top Spell', [], ''), 'library')
const junk = makeToken(game, { types: ['artifact'], subtypes: ['junk'], colors: [] })
game.activateAbility('p1', junk.id, 0)
game.resolveStack()
assert.equal(exiled.zone, 'exile')
assert.equal(game.canPlayCard('p1', exiled.id), true)
game.castSpell('p1', exiled.id)
game.resolveStack()
assert.equal(exiled.zone, 'graveyard')
})
test('Role tokens attach to the target creature and apply their abilities', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const bear = game.addCard('p1', creature('Bear', 2, 2), 'battlefield')
const maker = game.addCard('p1', roleMaker('Monster'), 'battlefield')
assert.deepEqual(game.legalTargetsForAbility('p1', maker.id, 0), [{ kind: 'object', id: bear.id }])
game.activateAbility('p1', maker.id, 0, { targets: [{ kind: 'object', id: bear.id }] })
game.resolveStack()
const role = game.getPlayer('p1').battlefield
.map(id => game.getObject(id))
.find(object => object.isToken)
assert.ok(role)
assert.equal(role.definition.name, 'Monster Role')
assert.match(role.definition.typeLine.toLowerCase(), /enchantment — aura role/)
assert.equal(role.attachedTo, bear.id)
assert.equal(game.getPower(bear), 3)
assert.equal(game.getToughness(bear), 3)
assert.equal(game.hasKeyword(bear, 'Trample'), true)
})
test('Young Hero Role triggers when the enchanted creature attacks with toughness 3 or less', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
const bear = game.addCard('p1', creature('Bear', 2, 2), 'battlefield')
game.start()
const maker = game.addCard('p1', roleMaker('Young Hero'), 'battlefield')
game.activateAbility('p1', maker.id, 0, { targets: [{ kind: 'object', id: bear.id }] })
game.resolveStack()
game.declareAttackers('p1', [{ attackerId: bear.id, defenderId: 'p2' }])
game.resolveStack()
assert.equal(bear.counters['+1/+1'], 1)
assert.equal(game.getPower(bear), 3)
})

File diff suppressed because it is too large Load Diff