From 9ec486274f863350d2edbb0330403b04af7a8383 Mon Sep 17 00:00:00 2001 From: Aran Roig Date: Thu, 29 Oct 2026 20:30:29 +0100 Subject: [PATCH] Fa triggers malament --- backend/docs/card-effects.md | 21 +- backend/docs/game-engine.md | 54 ++- backend/src/effects/compile.ts | 36 ++ backend/src/effects/format.ts | 12 +- backend/src/effects/parse.ts | 18 +- backend/src/effects/source.ts | 42 +- backend/src/effects/translate.ts | 1 + backend/src/effects/types.ts | 5 +- backend/src/game/game.ts | 373 +++++++++++++-- backend/src/game/rooms.ts | 84 +++- backend/src/game/tokens.ts | 414 +++++++++++++++++ backend/src/game/types.ts | 14 +- backend/test/commander.test.ts | 48 +- backend/test/effects.test.ts | 69 +++ backend/test/game.test.ts | 491 +++++++++++++++++++- frontend/app/pages/games/[id].vue | 733 ++++++++++++++++++++++++++++-- 16 files changed, 2287 insertions(+), 128 deletions(-) create mode 100644 backend/src/game/tokens.ts diff --git a/backend/docs/card-effects.md b/backend/docs/card-effects.md index 473d278..c95279b 100644 --- a/backend/docs/card-effects.md +++ b/backend/docs/card-effects.md @@ -162,7 +162,7 @@ permanents.withType('creature').withSubtype('dragon').withColor('red') ``` 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`, `youControl`, `opponentControls`, `controlledBy`, `ownedBy`, `named`, `inZone`, `withCounter`, `powerAtLeast`/`powerAtMost`, @@ -198,6 +198,7 @@ damage(target(permanents.withType('creature')), 3) draw(you, 2) gainLife(you, 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) destroy(target(permanents.withType('creature'))) 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: `staticPump`, `staticGrant`, `staticRestrict`, `staticSetPt`, `grantAbility`, `entersTapped`, `entersWithCounters`, `control`, `choose`, `replace`, -`costReduction`, `costIncrease`, `searchRestriction` and -`exileInsteadOfGraveyard`. `entersTapped` takes an optional `unlessCost` builder +`costReduction`, `costIncrease`, `searchRestriction`, +`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": `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` | | `grant` | `target`, `keyword`, optional `value`, `duration` | | `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` | | `sacrifice` | `player`, `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` | | `attach` | target to attach this/trigger object to | | `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 | -| `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` | | `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 diff --git a/backend/docs/game-engine.md b/backend/docs/game-engine.md index eb14bcc..c525259 100644 --- a/backend/docs/game-engine.md +++ b/backend/docs/game-engine.md @@ -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. | | `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. | -| `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. | | `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. | | `resolveCombatDamage()` | Deals combat damage manually; passing priority also does this. | | `pass(playerId?)` | Passes priority; when everyone passes, resolves the top of the stack or advances the phase. | | `chooseSearchCard(playerId, cardId)` | Finishes one pick of a paused library search. | +| `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. | | `resolveStack()` | Convenience for tests/scripts: passes priority until the stack is empty. Does not advance phases. | | `endTurn(playerId)` | Ends the active player's turn, skipping remaining phases. Requires an empty stack. | | `canPlayCard(playerId, cardId)` | Whether a hand or command-zone card can legally be played now, including timing, mana, and targets. | +| `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. | | `getPower`, `getToughness`, `hasKeyword` | Current characteristics after static and continuous effects. | | `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 ``` -The starting player skips their first draw. Cleanup discards down to seven cards, -clears damage, expires `until_end_of_turn` and `until_end_of_your_next_turn` -effects, and empties mana pools. The engine advances phases when every living -player passes in turn; it does not stop at every rules-defined priority window. -The match manager calls `autoAdvance()` after each action, so priority is only -shown to players who can actually do something. +The starting player draws on their first turn, as in multiplayer Commander. Cleanup +discards down to seven cards, clears damage, expires `until_end_of_turn` and +`until_end_of_your_next_turn` effects, and empties mana pools. The engine advances +phases when every living player passes in turn; it does not stop at every +rules-defined priority window. The match manager calls `autoAdvance()` after each +action, so priority is only shown to players who can actually do something. ## 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, regenerate, energy, attach, restrictions, conditional and modal effects, dig, 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 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 @@ -148,9 +158,27 @@ shown to players who can actually do something. ## Known limitations - Some effect nodes are accepted but intentionally do nothing yet: - `prevent_damage`, `gain_control`, `emblem`, `transform`, `schedule`, `level_up`, - `put_from_among`, `look_top`, `scry`, `surveil`, and `keyword_action`. - Unsupported oracle lines are already marked by the compiler and never reach here. + `prevent_damage`, `gain_control`, `emblem`, `schedule`, `level_up`, + `put_from_among`, `look_top`, `scry`, and `surveil`. Scry and surveil are + 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, and "choose a commander" variants are not modelled. The engine always takes the 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 Souls' mana is not restricted to the chosen type and does not make the spell uncounterable. -- Hideaway automatically exiles the top card and does not track cards as face down. - `play_exiled` only supports the free "without paying its mana cost" case. +- Hideaway pauses for its controller to exile one of the looked-at cards; the + 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 keeps its printed target. Free alternative costs are modelled only for controlling a commander, and search restrictions cap the searching player's own library. diff --git a/backend/src/effects/compile.ts b/backend/src/effects/compile.ts index 2372ec4..ef4d3a5 100644 --- a/backend/src/effects/compile.ts +++ b/backend/src/effects/compile.ts @@ -7,6 +7,7 @@ import { parseSelector, parseTarget, parseValue, + ROLE_NAMES, } from './parse.js' import type { Ability, @@ -397,6 +398,11 @@ function parseTokenBody(text: string, tapped: boolean): TokenSpec | undefined { } if (/\bcolorless\b/.test(rest)) colors.push('C') + const role = Object.entries(ROLE_NAMES).find(([name]) => rest.endsWith(`${name} role`)) + if (role) { + return { name: role[1], types: ['enchantment'], subtypes: ['aura', 'role'], colors, tapped: tapped || undefined } + } + let power: Value | undefined let toughness: Value | undefined const pt = rest.match(/^(\d+|x)\/(\d+|x)\b/) @@ -777,6 +783,16 @@ function parseEffect(text: string): Effect | Effect[] | undefined { } } + match = sentence.match(/^create (?:(\w+) )?(?:a |an )?(.+?) tokens? attached to (.+)$/) + if (match) { + const amount = match[1] && !['a', 'an'].includes(match[1]) + ? parseValue(match[1]) + : ({ kind: 'number', value: 1 } as Value) + const token = parseToken(match[2]) + const attachTo = parseTarget(match[3]) + if (amount && token && attachTo) return { op: 'create_token', player: 'you', amount, token, attachTo } + } + match = sentence.match(/^create (?:((?:that many)|\w+) )?(.+?) tokens?(?: (with .+))?$/) if (match) { const amount = match[1] ? parseValue(match[1]) : ({ kind: 'number', value: 1 } as Value) @@ -1944,6 +1960,26 @@ function parseStaticEffects(text: string): StaticEffect[] | undefined { if (what) return [{ op: 'choose', what }] } + match = sentence.match(/^if an effect would create one or more (tokens?|creature tokens?) under your control, it creates (twice|three times) that many of those tokens instead$/) + if (match) { + return [{ + op: 'token_multiplier', + multiplier: match[2] === 'twice' ? 2 : 3, + who: 'you', + ...(match[1] === 'creature tokens' ? { creatureOnly: true } : {}), + }] + } + + match = sentence.match(/^if one or more (tokens?|creature tokens?) would be created( under your control)?, (twice|three times) that many of those tokens are created instead$/) + if (match) { + return [{ + op: 'token_multiplier', + multiplier: match[3] === 'twice' ? 2 : 3, + who: match[2] ? 'you' : 'each_player', + ...(match[1] === 'creature tokens' ? { creatureOnly: true } : {}), + }] + } + match = sentence.match(/^if this would be put into (?:a|your) graveyard from anywhere, exile it instead$/) if (match) { return [{ op: 'replacement', what: 'dies', instead: 'exile', target: { kind: 'self' } }] diff --git a/backend/src/effects/format.ts b/backend/src/effects/format.ts index bc7ab82..dac4e42 100644 --- a/backend/src/effects/format.ts +++ b/backend/src/effects/format.ts @@ -116,6 +116,9 @@ function formatSelector(selector: ObjectSelector): string { if (selector.colors?.length) { text += `.withColor(${selector.colors.map(color => quote(COLOR_NAMES[color] ?? color)).join(', ')})` } + if (selector.excludeColors?.length) { + text += `.withoutColor(${selector.excludeColors.map(color => quote(COLOR_NAMES[color] ?? color)).join(', ')})` + } if (selector.supertypes?.length) { text += `.withSupertype(${selector.supertypes.map(quote).join(', ')})` } @@ -315,7 +318,7 @@ export function formatEffect(effect: Effect): string { case 'create_token': return effect.copyOf ? `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, copyOf(${formatTarget(effect.copyOf)}${effect.notLegendary ? ', { notLegendary: true }' : ''}))` - : `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, ${formatToken(effect.token)})` + : `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, ${formatToken(effect.token)}${effect.attachTo ? `, { attachTo: ${formatTarget(effect.attachTo)} }` : ''})` case 'destroy': return `destroy(${formatTarget(effect.target)})` case 'exile': @@ -560,6 +563,8 @@ function formatCondition(condition: Condition): string { return `attackedWithCreatures(${condition.atLeast})` case 'library_at_most': return `libraryAtMost(${condition.atMost})` + case 'event_subject_toughness_at_most': + return `eventSubjectToughnessAtMost(${condition.amount})` } } @@ -651,6 +656,11 @@ function formatStaticEffect(effect: StaticEffect): string { return `searchRestriction(${quote(effect.who)}, ${formatValue(effect.amount)})` case 'exile_instead_of_graveyard': return `exileInsteadOfGraveyard(${effect.owner ? quote(effect.owner) : ''})` + case 'token_multiplier': + return `tokenMultiplier(${effect.multiplier}${optionArg([ + ['who', effect.who === 'each_player' ? quote('each_player') : undefined], + ['creatureOnly', effect.creatureOnly ? 'true' : undefined], + ])})` } } diff --git a/backend/src/effects/parse.ts b/backend/src/effects/parse.ts index 32ec982..2c533db 100644 --- a/backend/src/effects/parse.ts +++ b/backend/src/effects/parse.ts @@ -144,6 +144,16 @@ const NON_CREATURE_SUBTYPES: Record = { desert: 'land', } +export const ROLE_NAMES: Record = { + cursed: 'Cursed', + monster: 'Monster', + royal: 'Royal', + sorcerer: 'Sorcerer', + virtuous: 'Virtuous', + wicked: 'Wicked', + 'young hero': 'Young Hero', +} + function typeForSubtype(subtype: string): string { return NON_CREATURE_SUBTYPES[subtype] ?? 'creature' } @@ -462,6 +472,7 @@ export function parseSelector(text: string): ObjectSelector | undefined { const supertypes: string[] = [] const subtypes: string[] = [] const colors: string[] = [] + const excludeColors: string[] = [] let match: ObjectSelector['match'] for (const rawWord of words) { @@ -506,6 +517,10 @@ export function parseSelector(text: string): ObjectSelector | undefined { excludeTypes.push(negative[1]) continue } + if (negative && COLOR_WORDS[negative[1]]) { + excludeColors.push(COLOR_WORDS[negative[1]]) + continue + } if (STATE_WORDS.has(word)) { if (word === 'token') selector.token = true @@ -528,7 +543,7 @@ export function parseSelector(text: string): ObjectSelector | undefined { if (!types.length) { if (subtypes.length) { types.push(typeForSubtype(subtypes[0])) - } else if (!(excludeTypes.length || colors.length || supertypes.length || selector.name)) { + } else if (!(excludeTypes.length || excludeColors.length || colors.length || supertypes.length || selector.name)) { return undefined } } @@ -536,6 +551,7 @@ export function parseSelector(text: string): ObjectSelector | undefined { selector.types = types if (match) selector.match = match if (excludeTypes.length) selector.excludeTypes = excludeTypes + if (excludeColors.length) selector.excludeColors = excludeColors if (supertypes.length) selector.supertypes = supertypes if (subtypes.length) selector.subtypes = subtypes if (colors.length) selector.colors = colors diff --git a/backend/src/effects/source.ts b/backend/src/effects/source.ts index d72c81f..bf7dea9 100644 --- a/backend/src/effects/source.ts +++ b/backend/src/effects/source.ts @@ -522,7 +522,7 @@ const STATIC_OPS = new Set([ 'pump', 'grant', 'grant_ability', 'restriction', 'enters_tapped', 'enters_with_counters', 'set_pt', 'control', 'choose', 'replacement', 'cost_reduction', 'cost_increase', 'search_restriction', - 'exile_instead_of_graveyard', + 'exile_instead_of_graveyard', 'token_multiplier', ]) const COST_KINDS = new Set([ @@ -766,6 +766,18 @@ class Selector { }) } + withoutColor(...colors: unknown[]): Selector { + return this.with({ + excludeColors: [ + ...(this.fields.excludeColors ?? []), + ...colors.map(color => { + const text = asString(color, 'color').toLowerCase() + return COLOR_CODES[text] ?? text.toUpperCase() + }), + ], + }) + } + matchingAny(): Selector { return this.with({ match: 'any' }) } @@ -1249,7 +1261,10 @@ function proliferate(): Effect { return { op: 'proliferate' } } -function createToken(player: unknown, amount: unknown, tokenValue: unknown): Effect { +function createToken(player: unknown, amount: unknown, tokenValue: unknown, options?: unknown): Effect { + const attachTo = options && typeof options === 'object' && 'attachTo' in options + ? asTarget((options as { attachTo: unknown }).attachTo) + : undefined if (tokenValue instanceof CopyOf) { return { op: 'create_token', @@ -1258,9 +1273,16 @@ function createToken(player: unknown, amount: unknown, tokenValue: unknown): Eff token: { types: [], subtypes: [], colors: [] }, copyOf: tokenValue.target, ...(tokenValue.notLegendary ? { notLegendary: true } : {}), + ...(attachTo ? { attachTo } : {}), } } - return { op: 'create_token', player: asPlayer(player), amount: asValue(amount), token: asToken(tokenValue) } + return { + op: 'create_token', + player: asPlayer(player), + amount: asValue(amount), + token: asToken(tokenValue), + ...(attachTo ? { attachTo } : {}), + } } function destroy(targetValue: unknown): Effect { @@ -1603,6 +1625,19 @@ function replace(what: unknown, options?: unknown): StaticEffect { } } +function tokenMultiplier(multiplier: unknown, options?: unknown): StaticEffect { + const data = asOptions(options) + if (data.who !== undefined && data.who !== 'you' && data.who !== 'each_player') { + throw new Error("tokenMultiplier() who must be 'you' or 'each_player'") + } + return { + op: 'token_multiplier', + multiplier: asNumber(multiplier, 'token multiplier'), + who: data.who === 'each_player' ? 'each_player' : 'you', + ...(data.creatureOnly === true ? { creatureOnly: true } : {}), + } +} + function costReduction(targetValue: unknown, amount: unknown, options?: unknown): StaticEffect { const data = asOptions(options) return { @@ -2351,6 +2386,7 @@ function createApi(): Record { costIncrease, searchRestriction, exileInsteadOfGraveyard, + tokenMultiplier, // abilities keyword, diff --git a/backend/src/effects/translate.ts b/backend/src/effects/translate.ts index fc08167..38d35cd 100644 --- a/backend/src/effects/translate.ts +++ b/backend/src/effects/translate.ts @@ -73,6 +73,7 @@ Selectors (chainable): permanents, cards, creatures .withType('land'), .withSubtype('dragon'), .withSupertype('legendary') .withColor('white'|'blue'|'black'|'red'|'green'|'colorless') + .withoutColor('white'|'blue'|'black'|'red'|'green'|'colorless') .withoutType('creature'), .withKeyword('flying'), .withoutKeyword('flying') .other(), .tapped(), .untapped(), .attacking(), .token(), .nontoken() .equipped(), .enchanted(), .youControl(), .opponentControls(), .controlledBy('you'|'opponent'|'any') diff --git a/backend/src/effects/types.ts b/backend/src/effects/types.ts index 2ba78fa..0f2315a 100644 --- a/backend/src/effects/types.ts +++ b/backend/src/effects/types.ts @@ -25,6 +25,7 @@ export interface ObjectSelector { controller?: 'you' | 'opponent' | 'any' owner?: 'you' | 'opponent' colors?: string[] + excludeColors?: string[] other?: boolean attached?: 'equipped' | 'enchanted' zone?: Zone @@ -191,6 +192,7 @@ export type Condition = | { kind: 'opponent_damaged_this_turn'; atLeast: number } | { kind: 'attacked_with_creatures'; atLeast: number } | { kind: 'library_at_most'; atMost: number } + | { kind: 'event_subject_toughness_at_most'; amount: number } export type TriggerEvent = | { kind: 'enters'; subject: Target } @@ -225,7 +227,7 @@ export type Effect = | { op: 'put_counters'; target: Target; counter: string; amount: Value } | { op: 'remove_counters'; target: Target; counter: string; amount: Value } | { op: 'proliferate' } - | { op: 'create_token'; player: PlayerRef; amount: Value; token: TokenSpec; copyOf?: Target; notLegendary?: boolean } + | { op: 'create_token'; player: PlayerRef; amount: Value; token: TokenSpec; copyOf?: Target; notLegendary?: boolean; attachTo?: Target } | { op: 'destroy'; target: Target } | { op: 'exile'; target: Target } | { op: 'sacrifice'; player: PlayerRef; target: Target; unless?: Cost } @@ -278,6 +280,7 @@ export type StaticEffect = | { op: 'cost_increase'; amount: Value; spellType?: 'noncreature' | 'creature' } | { op: 'search_restriction'; who: 'opponent' | 'you'; amount: Value } | { op: 'exile_instead_of_graveyard'; owner?: 'opponent' | 'you' } + | { op: 'token_multiplier'; multiplier: number; who: 'you' | 'each_player'; creatureOnly?: boolean } export type Ability = | KeywordAbility diff --git a/backend/src/game/game.ts b/backend/src/game/game.ts index 892a267..bfe8b1d 100644 --- a/backend/src/game/game.ts +++ b/backend/src/game/game.ts @@ -33,6 +33,7 @@ import type { TargetChoice, } from './types.js' import { CREATURE_TYPES } from './creature-types.js' +import { predefinedToken } from './tokens.js' export class GameError extends Error {} @@ -65,6 +66,8 @@ interface EffectContext { eventAmount?: number x: number mode: number + /** Color picked for a mana ability, so choice effects produce it. */ + manaColor?: ManaColor } interface ContinuousEffect { @@ -167,19 +170,66 @@ function colorOfSymbol(symbol: string): ManaColor { return 'C' } -function tokenCard(token: { types: string[]; subtypes: string[]; name?: string; colors: string[]; power?: number; toughness?: number; keywords?: string[] }): CardDefinition { +function tokenCard(token: { + name?: string + types: string[] + subtypes: string[] + colors: string[] + power?: number + toughness?: number + keywords?: string[] +}): { definition: CardDefinition; backFace?: CardDefinition } { + const predefined = predefinedToken(token) + const types = predefined?.types ?? token.types + const subtypes = predefined?.subtypes ?? token.subtypes + const colors = [...new Set([...(predefined?.colors ?? []), ...token.colors])] + const keywords = [...(predefined?.keywords ?? []), ...(token.keywords ?? [])] + const definition = tokenFace({ + name: predefined?.name ?? token.name ?? (subtypes.map(capitalize).join(' ') || 'Token'), + types, + subtypes, + colors, + power: token.power ?? predefined?.power, + toughness: token.toughness ?? predefined?.toughness, + keywords, + abilities: predefined?.abilities, + }) + const backFace = predefined?.backFace + ? tokenFace({ ...predefined.backFace, keywords: predefined.backFace.keywords ?? [] }) + : undefined + return { definition, backFace } +} + +function capitalize(word: string): string { + return word[0]?.toUpperCase() + word.slice(1) +} + +function tokenFace(fields: { + name: string + types: string[] + subtypes: string[] + colors: string[] + power?: number + toughness?: number + keywords?: string[] + abilities?: Ability[] +}): CardDefinition { return { - oracleId: `token:${token.name ?? (token.subtypes.join(' ') || token.types.join(' '))}`, - name: token.name ?? (token.subtypes.map(word => word[0]?.toUpperCase() + word.slice(1)).join(' ') || 'Token'), - typeLine: [token.types.join(' '), token.subtypes.length ? `— ${token.subtypes.join(' ')}` : ''].join(' ').trim(), + oracleId: `token:${fields.name}`, + name: fields.name, + typeLine: [fields.types.join(' '), fields.subtypes.length ? `— ${fields.subtypes.join(' ')}` : ''].join(' ').trim(), manaValue: 0, - colors: token.colors, - power: token.power, - toughness: token.toughness, - abilities: (token.keywords ?? []).map(keyword => ({ kind: 'keyword', keyword })), + colors: fields.colors, + power: fields.power, + toughness: fields.toughness, + abilities: [ + ...(fields.abilities ?? []), + ...(fields.keywords ?? []).map(keyword => ({ kind: 'keyword' as const, keyword })), + ], } } + /** * A deliberately small but real Magic rules engine: zones, priority, the stack, * turn phases, combat, state-based actions, mana, triggered/activated/static @@ -431,6 +481,7 @@ export class Game { const from = object.zone this.removeFromZone(object) object.zone = destination + if (destination !== 'exile') object.faceDown = undefined if (destination === 'battlefield') { object.controller = options.controller ?? object.owner @@ -617,8 +668,10 @@ export class Game { } if (this.stack.length) throw new GameError('Cannot play a land while the stack is not empty') if (player.landPlayedThisTurn) throw new GameError('Already played a land this turn') - if (!player.hand.includes(cardId)) throw new GameError('Card is not in hand') const object = this.getObject(cardId) + if (!player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) { + throw new GameError('Card is not in hand') + } if (!this.isLand(object)) throw new GameError('That card is not a land') player.landPlayedThisTurn = true @@ -634,8 +687,10 @@ export class Game { if (this.status !== 'active') throw new GameError('Game is not active') const player = this.getPlayer(playerId) const fromCommand = player.command.includes(cardId) - if (!fromCommand && !player.hand.includes(cardId)) throw new GameError('Card is not in hand') const object = this.getObject(cardId) + if (!fromCommand && !player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) { + throw new GameError('Card is not in hand') + } if (fromCommand && !object.isCommander) throw new GameError('That card cannot be cast from the command zone') if (this.isLand(object)) throw new GameError('Land cards are played, not cast') if (!this.canCastAtThisTime(playerId, object)) { @@ -773,9 +828,13 @@ export class Game { if (ability.activationsPerTurn !== undefined && activations >= ability.activationsPerTurn) { throw new GameError('Ability activation limit reached') } + if (options.manaColor && !this.manaColorChoices(source, abilityIndex)?.includes(options.manaColor)) { + throw new GameError('That ability cannot produce that mana') + } const targets = this.selectTargets(ability.effects, source, playerId, options.targets ?? [], options.mode ?? 0) const context = this.contextFor(source, playerId, targets, options.x ?? 0, options.mode ?? 0) + context.manaColor = options.manaColor this.payCosts(ability.costs, playerId, source, context) source.activations[abilityIndex] = activations + 1 @@ -980,8 +1039,8 @@ export class Game { if (this.status !== 'active' || this.priority !== playerId || this.pendingSearch || this.pendingChoice) return false const player = this.getPlayer(playerId) const fromCommand = player.command.includes(cardId) - if (!fromCommand && !player.hand.includes(cardId)) return false const object = this.getObject(cardId) + if (!fromCommand && !player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) return false if (fromCommand && !object.isCommander) return false if (this.isLand(object)) { @@ -1010,6 +1069,13 @@ export class Game { return this.hasLegalTargets(object, playerId) } + /** Junk and other impulse effects grant a one-turn play permission from exile. */ + private playableFromExile(playerId: string, object: GameObject): boolean { + return object.zone === 'exile' + && object.owner === playerId + && object.playableFromExileTurn === this.turn + } + /** * Finishes one pick of a paused library search. Searches pause when several * cards match so the player chooses instead of taking the first one. @@ -1056,6 +1122,37 @@ export class Game { return this.searchableObjects(playerId, pending.zones) } + /** + * Answers the hideaway look: exiles the chosen card linked to the source and + * puts the rest on the bottom of the library in a random order. + */ + chooseHideawayCard(playerId: string, cardId: string): void { + const pending = this.pendingChoice + if (!pending || pending.what !== 'hideaway') throw new GameError('No hideaway choice is waiting') + if (pending.playerId !== playerId) throw new GameError('You are not choosing this hideaway card') + const looked = (pending.cardIds ?? []).map(id => this.getObject(id)) + const hidden = looked.find(object => object.id === cardId && object.zone === 'library') + if (!hidden) throw new GameError('That card is not a legal choice') + + this.pendingChoices.shift() + this.moveToZone(hidden, 'exile', { silent: true }) + const source = this.objects.get(pending.sourceId) + if (hidden.zone === 'exile') { + hidden.faceDown = true + if (source) source.linkedExile = [...(source.linkedExile ?? []), hidden.id] + } + + const rest = looked.filter(object => object.id !== hidden.id) + for (let index = rest.length - 1; index > 0; index--) { + const swap = Math.floor(this.rng() * (index + 1)) + const temp = rest[index] + rest[index] = rest[swap] + rest[swap] = temp + } + for (const object of rest) this.moveToZone(object, 'library', { silent: true }) + this.logMessage(`${this.getPlayer(playerId).name} hides away a card`) + } + /** * Answers an "as this enters, choose a creature type" prompt. The match API * uses the `choose_type` action. @@ -1153,11 +1250,8 @@ export class Game { if (this.status !== 'active') return this.step = 'draw' - // The first player skips their first draw step, as in Commander. - if (this.turn > 1) { - this.drawCard(player.id, false) - if (this.status !== 'active') return - } + this.drawCard(player.id, false) + if (this.status !== 'active') return this.phase = 'precombat_main' this.step = 'main' @@ -1441,6 +1535,28 @@ export class Game { return this.neededColor(player, cost, this.manaAbilityAllowedColors(source, ability)) } + /** + * Colors a mana ability lets its controller choose between. Undefined when + * the ability has no choice, such as fixed or single-color mana. + */ + manaColorChoices(source: GameObject, abilityIndex: number): ManaColor[] | undefined { + const ability = (source.definition.abilities ?? [])[abilityIndex] + if (!ability || ability.kind !== 'activated') return undefined + let colors: ManaColor[] | undefined + for (const effect of ability.effects) { + if (effect.op !== 'add_mana') continue + if (effect.mana.kind === 'symbols' && effect.mana.oneOf) { + colors = [...new Set(effect.mana.symbols.map(colorOfSymbol))] + } else if (effect.mana.kind === 'any_color') { + const allowed = this.anyColorRestrictionColors(effect.mana, source.controller) + colors = allowed + ? MANA_COLORS.filter(color => color !== 'C' && allowed.has(color)) + : ['W', 'U', 'B', 'R', 'G'] + } + } + return colors && colors.length > 1 ? colors : undefined + } + private manaAbilityAllowedColors( source: GameObject, ability: Extract, @@ -1543,6 +1659,11 @@ export class Game { if (mana.restriction === 'a land you control could produce') { return this.landManaColors(playerId, false, seen) } + if (mana.restriction === "commander's color identity") { + const commander = this.objects.get(this.getPlayer(playerId).commanderId ?? '') + const identity = commander?.definition.colorIdentity ?? [] + return new Set(identity.filter((color): color is ManaColor => /^[WUBRG]$/.test(color))) + } return undefined } @@ -1747,6 +1868,10 @@ export class Game { take({ kind: 'player', who: effect.player, mode: 'target' }, who) } if ('target' in effect && effect.target) take(effect.target, undefined) + if (effect.op === 'create_token') { + if (effect.copyOf) take(effect.copyOf, undefined) + if (effect.attachTo) take(effect.attachTo, undefined) + } if (effect.op === 'fight') { take(effect.a, undefined) take(effect.b, undefined) @@ -1758,6 +1883,70 @@ export class Game { return selected } + /** Legal choices for a card's targets, so the UI can offer only real targets. */ + legalTargetsForCard(playerId: string, cardId: string): TargetChoice[] { + const source = this.objects.get(cardId) + if (!source) return [] + const effects = (source.definition.abilities ?? []) + .filter((ability): ability is Extract => ability.kind === 'spell') + .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() + const add = (target: Target, playerOnly?: 'opponent' | 'any'): void => { + if (target.kind === 'self' || target.kind === 'trigger_subject' || target.kind === 'previous_target') return + if ((target.kind === 'object' || target.kind === 'player') && target.mode === 'each') return + for (const choice of this.legalTargets(target, source, controller, playerOnly)) { + choices.set(`${choice.kind}:${choice.id}`, choice) + } + } + const walk = (list: Effect[]): void => { + for (const effect of list) { + if (effect.op === 'conditional') { + walk(effect.effects) + continue + } + if (effect.op === 'modal') { + walk(effect.modes[mode] ?? effect.modes[0] ?? []) + continue + } + if ('player' in effect && (effect.player === 'target_player' || effect.player === 'opponent')) { + add( + { kind: 'player', who: effect.player, mode: 'target' }, + effect.player === 'opponent' ? 'opponent' : 'any', + ) + } + if ('target' in effect && effect.target) add(effect.target) + if (effect.op === 'create_token') { + if (effect.copyOf) add(effect.copyOf) + if (effect.attachTo) add(effect.attachTo) + } + if (effect.op === 'fight') { + add(effect.a) + add(effect.b) + } + if (effect.op === 'damage_divided') add(effect.target) + } + } + walk(effects) + return [...choices.values()] + } + private legalTargets( target: Target, source: GameObject, @@ -2046,16 +2235,29 @@ export class Game { case 'create_token': { const amount = Math.max(0, this.value(effect.amount, context)) const players = this.playersForEffect(effect.player, context) + const created: GameObject[] = [] for (const playerId of players) { - for (let i = 0; i < amount; i++) { + const source = effect.copyOf + ? this.resolveTargets(context, effect.copyOf).find(target => target.kind === 'object') + : undefined + const creatureToken = source?.kind === 'object' + ? this.isCreature(source.object) + : effect.token.types.includes('creature') + const count = amount * this.tokenMultiplier(playerId, creatureToken) + for (let i = 0; i < count; i++) { if (effect.copyOf) { - const source = this.resolveTargets(context, effect.copyOf).find(target => target.kind === 'object') - if (source?.kind === 'object') this.createTokenCopy(playerId, source.object, effect.notLegendary) + if (source?.kind === 'object') created.push(this.createTokenCopy(playerId, source.object, effect.notLegendary)) } else { - this.createToken(playerId, effect.token, context) + created.push(this.createToken(playerId, effect.token, context)) } } } + if (effect.attachTo) { + const target = this.resolveTargets(context, effect.attachTo)[0] + if (target?.kind === 'object') { + for (const token of created) this.attach(token, target.object) + } + } break } case 'destroy': { @@ -2148,7 +2350,7 @@ export class Game { break } case 'add_mana': { - for (const playerId of this.playersForEffect(effect.player, context)) this.addMana(playerId, effect.mana) + for (const playerId of this.playersForEffect(effect.player, context)) this.addMana(playerId, effect.mana, context.manaColor) break } case 'fight': { @@ -2186,16 +2388,28 @@ export class Game { break } case 'keyword_action': + if (effect.action === 'explore') this.explore(context, effect) + else if (effect.action === 'incubate') this.incubate(context, effect.amount) + else if (effect.action === 'impulse') this.impulse(context) break case 'prevent_damage': case 'gain_control': case 'emblem': - case 'transform': case 'schedule': case 'level_up': case 'put_from_among': case 'look_top': break + case 'transform': { + const target = this.resolveTargets(context, effect.target)[0] + if (target?.kind === 'object' && target.object.backFace) { + const front = target.object.definition + target.object.definition = target.object.backFace + target.object.backFace = front + this.logMessage(`${target.object.definition.name} transforms`) + } + break + } case 'pay': try { this.payCosts(effect.costs, context.controller, context.source, context) @@ -2241,24 +2455,28 @@ export class Game { } private hideaway(context: EffectContext, effect: Extract): void { - // shortcut: auto-pick the top card; face-down exile and the look/choice are not modelled. + // The exiled card stays face down and is linked to the source until played. const player = this.getPlayer(context.controller) const amount = this.value(effect.amount, context) - const top = player.library.slice(0, amount).map(id => this.getObject(id)) - const hidden = top.shift() - if (!hidden) return - - this.moveToZone(hidden, 'exile', { silent: true }) - context.source.linkedExile = [...(context.source.linkedExile ?? []), hidden.id] - - for (let index = top.length - 1; index > 0; index--) { - const swap = Math.floor(this.rng() * (index + 1)) - const temp = top[index] - top[index] = top[swap] - top[swap] = temp + const looked = player.library.slice(0, amount).map(id => this.getObject(id)) + if (!looked.length) return + if (looked.length === 1) { + this.moveToZone(looked[0], 'exile', { silent: true }) + if (looked[0].zone === 'exile') { + looked[0].faceDown = true + context.source.linkedExile = [...(context.source.linkedExile ?? []), looked[0].id] + } + this.logMessage(`${player.name} hides away a card`) + return } - for (const object of top) this.moveToZone(object, 'library', { silent: true }) - this.logMessage(`${player.name} hides away a card`) + + this.pendingChoices.push({ + playerId: context.controller, + sourceId: context.source.id, + what: 'hideaway', + cardIds: looked.map(object => object.id), + }) + this.logMessage(`${player.name} looks at the top ${looked.length} cards of their library`) } private playExiledCard(playerId: string, object: GameObject, free: boolean | undefined): boolean { @@ -2304,6 +2522,48 @@ export class Game { return true } + private explore(context: EffectContext, effect: Extract): void { + const target = effect.target ? this.resolveTargets(context, effect.target)[0] : undefined + if (target?.kind !== 'object') return + const player = this.getPlayer(context.controller) + const cardId = player.library[0] + if (!cardId) return + const card = this.getObject(cardId) + if (this.isLand(card)) { + this.moveToZone(card, 'hand', { silent: false }) + this.logMessage(`${player.name} explores and puts ${card.definition.name} into their hand`) + return + } + this.addCounters(target.object, '+1/+1', 1) + // shortcut: the explored card always goes to the graveyard instead of + // asking whether to put it on top. Upgrade when the choice matters. + this.moveToZone(card, 'graveyard', { silent: false }) + this.logMessage(`${player.name} explores with ${target.object.definition.name}`) + } + + private incubate(context: EffectContext, amount: Value | undefined): void { + const counters = amount ? Math.max(0, this.value(amount, context)) : 0 + const count = this.tokenMultiplier(context.controller, false) + for (let i = 0; i < count; i++) { + const token = this.createToken(context.controller, { + types: ['artifact'], + subtypes: ['incubator'], + colors: [], + }, context) + this.addCounters(token, '+1/+1', counters) + } + } + + private impulse(context: EffectContext): void { + const player = this.getPlayer(context.controller) + const cardId = player.library[0] + if (!cardId) return + const card = this.getObject(cardId) + this.moveToZone(card, 'exile', { silent: false }) + card.playableFromExileTurn = this.turn + this.logMessage(`${player.name} exiles ${card.definition.name} and may play it this turn`) + } + private dig( context: EffectContext, effect: Extract, @@ -2467,7 +2727,7 @@ export class Game { } private createToken(playerId: string, spec: TokenSpec, context: EffectContext): GameObject { - const definition = tokenCard({ + const card = tokenCard({ ...spec, power: spec.power ? this.value(spec.power, context) : undefined, toughness: spec.toughness ? this.value(spec.toughness, context) : undefined, @@ -2475,7 +2735,8 @@ export class Game { const player = this.getPlayer(playerId) const object: GameObject = { id: this.generateId('token'), - definition, + definition: card.definition, + backFace: card.backFace, owner: playerId, controller: playerId, zone: 'battlefield', @@ -2503,6 +2764,7 @@ export class Game { const object: GameObject = { id: this.generateId('token'), definition, + backFace: source.backFace, owner: playerId, controller: playerId, zone: 'battlefield', @@ -2558,7 +2820,11 @@ export class Game { for (const source of sources) { for (const ability of source.definition.abilities ?? []) { if (ability.kind !== 'triggered') continue - if (ability.condition && !this.checkCondition(ability.condition, source)) continue + if (ability.condition) { + if (ability.condition.kind === 'event_subject_toughness_at_most') { + if (!event.subject || this.getToughness(event.subject) > ability.condition.amount) continue + } else if (!this.checkCondition(ability.condition, source)) continue + } if (!this.matchesTrigger(event, ability.event, source)) continue let targets: TargetChoice[] try { @@ -2672,6 +2938,20 @@ export class Game { return this.objectsMatching(target.selector, source) } + /** Product of every token-doubling replacement that applies to this creation. */ + private tokenMultiplier(playerId: string, creatureToken: boolean): number { + let multiplier = 1 + for (const { source, ability } of this.staticAbilities()) { + for (const effect of ability.effects) { + if (effect.op !== 'token_multiplier') continue + if (effect.who === 'you' && source.controller !== playerId) continue + if (effect.creatureOnly && !creatureToken) continue + multiplier *= effect.multiplier + } + } + return multiplier + } + private exilesInsteadOfGraveyard(object: GameObject): boolean { for (const { source, ability } of this.staticAbilities()) { for (const effect of ability.effects) { @@ -2810,6 +3090,8 @@ export class Game { return this.battlefieldObjects() .filter(object => object.controller === controller && this.isCreature(object)) .reduce((total, object) => total + this.getPower(object), 0) >= condition.atLeast + case 'event_subject_toughness_at_most': + return false default: return false } @@ -2914,7 +3196,7 @@ export class Game { return true } - if ([...player.hand, ...player.command].some(id => this.canPlayCard(playerId, id))) return true + if ([...player.hand, ...player.command, ...player.exile].some(id => this.canPlayCard(playerId, id))) return true for (const id of player.battlefield) { const object = this.objects.get(id) @@ -3241,6 +3523,12 @@ export class Game { // Most search lines are a single effect. if (this.pendingSearch) return const player = this.getPlayer(playerId) + // Searching then shuffling is the same as shuffling first when the picked + // cards go on top, and it keeps the shuffle from burying them again. + if (shuffle && (destination === 'top' || split?.destination === 'top')) { + this.shuffleLibrary(player) + shuffle = false + } let remaining = amount let first = true while (remaining > 0) { @@ -3379,6 +3667,7 @@ export class Game { const matches = selector.colors.map(color => colors.includes(color)) if (selector.match === 'any' ? !matches.some(Boolean) : !matches.every(Boolean)) return false } + if (selector.excludeColors?.some(color => color === 'C' ? colors.length === 0 : colors.includes(color))) return false if (selector.tapped !== undefined && object.tapped !== selector.tapped) return false if (selector.attacking !== undefined && Boolean(object.attacking) !== selector.attacking) return false if (selector.token !== undefined && object.isToken !== selector.token) return false @@ -3517,7 +3806,7 @@ export class Game { const match = counter.match(/^([+-])(\d+)\/([+-])(\d+)$/) if (!match) continue const value = stat === 'power' ? `${match[1]}${match[2]}` : `${match[3]}${match[4]}` - total += Number(value) + total += Number(value) * count } return total } diff --git a/backend/src/game/rooms.ts b/backend/src/game/rooms.ts index 3fdab05..ff5e312 100644 --- a/backend/src/game/rooms.ts +++ b/backend/src/game/rooms.ts @@ -5,7 +5,7 @@ import { getCardDefinition } from './catalog.js' import { CREATURE_TYPES } from './creature-types.js' import { validateCommanderDeck } from './commander.js' import { Game, GameError } from './game.js' -import type { CardDefinition, GameObject, ManaPool, TargetChoice } from './types.js' +import type { CardDefinition, GameObject, ManaColor, ManaPool, TargetChoice } from './types.js' export class MatchError extends Error { constructor(message: string, readonly status = 400) { @@ -28,6 +28,8 @@ export interface ActionPayload { mode?: number overload?: boolean choice?: string + /** Mana color picked when activating a mana ability that can make several. */ + color?: string pay?: boolean position?: { x?: unknown; y?: unknown } attackers?: { attackerId: string; defenderId: string }[] @@ -60,7 +62,13 @@ export interface CardView { blocking?: string /** Creature type chosen as this permanent entered, if any. */ chosenType?: string - abilities: { index: number; kind: string; text?: string }[] + /** Number of face-down cards exiled under this permanent (hideaway). */ + hiddenCards?: number + /** This exiled card is face down; its identity is not included. */ + faceDown?: boolean + /** Legal choices for this card's targets, for the cast panel. */ + targets?: TargetChoice[] + abilities: { index: number; kind: string; text?: string; targets?: TargetChoice[]; manaColors?: string[] }[] /** Viewer-specific: can this card be played from hand right now? */ playable?: boolean } @@ -136,6 +144,8 @@ export interface MatchView { amount?: number /** Choices to offer, populated only for the chooser. */ options: string[] + /** Cards to choose from for hideaway, populated only for the chooser. */ + cards?: CardView[] } } } @@ -426,6 +436,7 @@ export function performAction(matchId: string, token: string | undefined, action x: Number.isFinite(action.x) ? Number(action.x) : 0, mode: Number.isFinite(action.mode) ? Number(action.mode) : 0, overload: action.overload === true, + manaColor: manaColorOf(action.color), } try { @@ -457,6 +468,9 @@ export function performAction(matchId: string, token: string | undefined, action case 'choose_search': game.chooseSearchCard(seat.playerId, requireId(action.cardId)) break + case 'choose_hideaway': + game.chooseHideawayCard(seat.playerId, requireId(action.cardId)) + break case 'choose_type': if (typeof action.choice !== 'string') throw new MatchError('Missing type choice') game.chooseCreatureType(seat.playerId, action.choice) @@ -503,9 +517,46 @@ function requireId(id: unknown): string { return id } +function manaColorOf(value: unknown): ManaColor | undefined { + if (value === undefined) return undefined + if (typeof value !== 'string' || !/^[WUBRGCS]$/i.test(value)) throw new MatchError('Invalid mana color') + return value.toUpperCase() as ManaColor +} + function cardView(game: Game, object: GameObject, abilities = true): CardView { + // Face-down exiled cards (hideaway) keep their identity server-side only. + if (object.faceDown) { + return { + id: object.id, + oracleId: '', + name: 'Face-down card', + typeLine: '', + colors: [], + colorIdentity: [], + tapped: false, + damage: 0, + counters: {}, + isToken: false, + isCommander: false, + zone: object.zone, + controller: object.controller, + owner: object.owner, + blockedBy: [], + faceDown: true, + abilities: [], + } + } const definition = object.definition const creature = /creature/i.test(definition.typeLine) + const hiddenCards = object.zone === 'battlefield' + ? (object.linkedExile ?? []).filter(id => { + const linked = game.objects.get(id) + return linked?.zone === 'exile' && linked.faceDown + }).length + : 0 + const targets = object.zone === 'hand' || object.zone === 'command' || object.zone === 'exile' + ? game.legalTargetsForCard(object.owner, object.id) + : [] return { id: object.id, oracleId: definition.oracleId, @@ -531,11 +582,17 @@ function cardView(game: Game, object: GameObject, abilities = true): CardView { blockedBy: [...object.blockedBy], blocking: object.blocking, chosenType: object.chosenCreatureType, + hiddenCards: hiddenCards || undefined, + targets: targets.length ? targets : undefined, abilities: abilities ? (definition.abilities ?? []).map((ability, index) => ({ index, kind: ability.kind, text: 'text' in ability ? ability.text : undefined, + manaColors: game.manaColorChoices(object, index), + targets: ability.kind === 'activated' && object.zone === 'battlefield' + ? game.legalTargetsForAbility(object.controller, object.id, index) + : undefined, })) : [], } @@ -560,6 +617,16 @@ function serialize(match: Match, viewerId: string): MatchView { const game = match.game if (!game) return view + const hiddenUnderSource = new Set() + for (const player of game.players) { + for (const id of player.battlefield) { + for (const linked of game.getObject(id).linkedExile ?? []) { + const object = game.objects.get(linked) + if (object?.zone === 'exile' && object.faceDown) hiddenUnderSource.add(linked) + } + } + } + view.players = match.seats.map(seat => { const player = game.getPlayer(seat.playerId) return { @@ -572,7 +639,15 @@ function serialize(match: Match, viewerId: string): MatchView { libraryCount: player.library.length, battlefield: player.battlefield.map(id => cardView(game, game.getObject(id))), graveyard: player.graveyard.map(id => cardView(game, game.getObject(id), false)), - exile: player.exile.map(id => cardView(game, game.getObject(id), false)), + exile: player.exile + .filter(id => !hiddenUnderSource.has(id)) + .map(id => { + const playable = player.id === viewerId && game.canPlayCard(viewerId, id) + return { + ...cardView(game, game.getObject(id), playable), + ...(playable ? { playable } : {}), + } + }), command: player.command.map(id => cardView(game, game.getObject(id), false)), commanderId: player.commanderId, commanderDamage: Object.entries(player.commanderDamage) @@ -621,6 +696,9 @@ function serialize(match: Match, viewerId: string): MatchView { sourceName: game.objects.get(choice.sourceId)?.definition.name ?? 'Permanent', amount: choice.amount, options: choice.playerId === viewerId && choice.what === 'creature_type' ? [...CREATURE_TYPES] : [], + cards: choice.playerId === viewerId && choice.what === 'hideaway' + ? (choice.cardIds ?? []).map(id => cardView(game, game.getObject(id), false)) + : undefined, } : undefined, pendingSearch: search diff --git a/backend/src/game/tokens.ts b/backend/src/game/tokens.ts new file mode 100644 index 0000000..eb06998 --- /dev/null +++ b/backend/src/game/tokens.ts @@ -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['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 = { + 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 +} diff --git a/backend/src/game/types.ts b/backend/src/game/types.ts index 4f55067..b2043c7 100644 --- a/backend/src/game/types.ts +++ b/backend/src/game/types.ts @@ -94,6 +94,10 @@ export interface GameObject { counters: Record isToken: boolean token?: TokenSpec + /** Back face of a double-faced token (Incubator); transform swaps it in. */ + backFace?: CardDefinition + /** Set by impulse effects; the card may be played from exile this turn. */ + playableFromExileTurn?: number isCommander?: boolean enteredTurn: number /** Normalized center on the controller's mat; absent means auto-arranged. */ @@ -105,6 +109,8 @@ export interface GameObject { attachedTo?: string /** Cards exiled with this object, such as a card hidden by hideaway. */ linkedExile?: string[] + /** Exiled face down (hideaway); its identity is hidden from every view. */ + faceDown?: boolean /** Creature type chosen as this permanent entered (Cavern of Souls). */ chosenCreatureType?: string regenerationShields: number @@ -136,6 +142,8 @@ export interface ActionOptions { x?: number mode?: number overload?: boolean + /** Color chosen for a mana ability that can produce more than one. */ + manaColor?: ManaColor } /** A search that is waiting for its player to pick one of several matching cards. */ @@ -151,15 +159,17 @@ export interface PendingSearch { split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean } } -/** An "as this enters..." pause. Blocks all actions until its controller picks. */ +/** A pause such as "as this enters..." or a hideaway look. Blocks all actions until its controller picks. */ export interface PendingChoice { playerId: string sourceId: string - what: 'creature_type' | 'pay_cost' + what: 'creature_type' | 'pay_cost' | 'hideaway' /** Cost to pay to avoid entering tapped. */ cost?: Cost /** Life total to display for a `pay_life` cost. */ amount?: number + /** Cards to choose from for `hideaway`. */ + cardIds?: string[] } export interface CombatAttack { diff --git a/backend/test/commander.test.ts b/backend/test/commander.test.ts index d2c8d54..2bbdfc9 100644 --- a/backend/test/commander.test.ts +++ b/backend/test/commander.test.ts @@ -84,6 +84,46 @@ Deck 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', () => { const commander = commanderDefinition('Test Commander') 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, commander: true, players: [ - { id: 'p1', deck: [], commander }, - { id: 'p2', deck: [], commander: commanderDefinition('Other Commander') }, + { id: 'p1', deck: [basicLand('Forest')], commander }, + { id: 'p2', deck: [basicLand('Forest')], commander: commanderDefinition('Other Commander') }, ], }) game.start() @@ -138,8 +178,8 @@ test('twenty-one commander damage loses the game', () => { startingHandSize: 0, commander: true, players: [ - { id: 'p1', deck: [], commander }, - { id: 'p2', deck: [], commander: commanderDefinition('Other Commander') }, + { id: 'p1', deck: [basicLand('Forest')], commander }, + { id: 'p2', deck: [basicLand('Forest')], commander: commanderDefinition('Other Commander') }, ], }) game.start() diff --git a/backend/test/effects.test.ts b/backend/test/effects.test.ts index 163495f..aa0ae89 100644 --- a/backend/test/effects.test.ts +++ b/backend/test/effects.test.ts @@ -175,6 +175,24 @@ test('static anthem', () => { 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', () => { const [ability] = creature('This creature enters with X +1/+1 counters on it.') 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', () => { const [ability] = spell('Draw two cards, then discard a card.') 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) } }) + +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) + } +}) diff --git a/backend/test/game.test.ts b/backend/test/game.test.ts index 494bc75..bae54a5 100644 --- a/backend/test/game.test.ts +++ b/backend/test/game.test.ts @@ -1,8 +1,8 @@ import assert from 'node:assert/strict' import test from 'node:test' import { Game, GameError } from '../src/game/game.js' -import type { Ability, Effect } from '../src/effects/types.js' -import type { CardDefinition } from '../src/game/types.js' +import type { Ability, Effect, TokenSpec } from '../src/effects/types.js' +import type { CardDefinition, GameObject } from '../src/game/types.js' function card(name: string, overrides: Partial = {}): CardDefinition { return { @@ -72,6 +72,71 @@ function setup(players: { id: string; deck?: CardDefinition[]; life?: number }[] 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', () => { const forest = land('Forest', 'G') 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.priority, 'p1') assert.equal(game.getPlayer('p1').life, 40) - assert.equal(game.getPlayer('p1').hand.length, 7) - assert.equal(game.getPlayer('p1').library.length, 3) + assert.equal(game.getPlayer('p1').hand.length, 8) + assert.equal(game.getPlayer('p1').library.length, 2) 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.turn, 1) 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', () => { @@ -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' }]) game.start() 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 library.splice(library.indexOf(hidden.id), 1) 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.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.faceDown, true) 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.resolveStack() @@ -243,6 +325,7 @@ test('hideaway exiles a card and its linked ability plays it for free once the c game.resolveStack() assert.equal(hidden.zone, 'battlefield') + assert.equal(hidden.faceDown, undefined) 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.resolveStack() assert.equal(hidden.zone, 'exile') + assert.equal(hidden.faceDown, true) game.getPlayer('p1').landPlayedThisTurn = true 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 }) }) +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', () => { const rainbow = card('Rainbow Land', { typeLine: 'Land', @@ -475,6 +612,58 @@ test('temporary pump effects expire at end of turn', () => { 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', () => { const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }]) game.start() @@ -590,6 +779,86 @@ test('activated abilities create tokens that enter the battlefield', () => { 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', () => { const forest = land('Forest', 'G') 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)) }) +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', () => { const cavern = card('Cavern of Souls', { 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.resolveStack() 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.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[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) +}) diff --git a/frontend/app/pages/games/[id].vue b/frontend/app/pages/games/[id].vue index b1dc7a0..9523a70 100644 --- a/frontend/app/pages/games/[id].vue +++ b/frontend/app/pages/games/[id].vue @@ -4,10 +4,19 @@ import { loadPlaymatChoice, savePlaymatChoice, type PlaymatSelection } from '~/u import { cardBackVars } from '~/utils/cardBack' import { diffGameState, type GameAnimations } from '~/utils/gameAnimations' +interface TargetChoice { + kind: 'player' | 'object' | 'spell' + id: string +} + interface AbilityView { index: number kind: string text?: string + /** Offered when the ability can produce more than one mana color. */ + manaColors?: string[] + /** Legal targets for an activated ability. */ + targets?: TargetChoice[] } interface CardView { @@ -35,6 +44,10 @@ interface CardView { blockedBy: string[] blocking?: string chosenType?: string + hiddenCards?: number + faceDown?: boolean + /** Legal targets for a card in hand or the command zone. */ + targets?: TargetChoice[] abilities: AbilityView[] playable?: boolean } @@ -86,6 +99,7 @@ interface MatchView { sourceName: string amount?: number options: string[] + cards?: CardView[] } pendingSearch?: { player: string @@ -106,6 +120,24 @@ interface MatchSummary { players: string[] } +interface Point { + x: number + y: number +} + +interface Box { + center: Point + halfWidth: number + halfHeight: number +} + +interface CombatArrow { + key: string + from: Point + to: Point + tone: 'attack' | 'block' +} + interface FloatingLabel { id: number targetId: string @@ -133,15 +165,22 @@ const token = ref('') const error = ref('') const notice = ref('') const busy = ref(false) +const autoPassInstants = ref(false) const connection = ref<'connecting' | 'live' | 'reconnecting' | 'offline'>('connecting') const castCardId = ref('') const selectedTarget = ref('') const castX = ref(0) const castOverload = ref(false) +const pendingAbility = ref<{ card: CardView; ability: AbilityView; color?: string } | null>(null) +const abilityTarget = ref('') const selectedAttackers = ref([]) const attackTargets = reactive>({}) const attackDropId = ref('') const blockSelection = reactive>({}) +const blockDragLine = ref<{ from: Point; to: Point } | null>(null) +const blockDragId = ref('') +const blockHoverId = ref('') +const combatArrows = ref([]) const selectedCardId = ref('') const menu = ref<{ cardId: string; x: number; y: number } | null>(null) const menuEl = ref(null) @@ -163,6 +202,7 @@ let previousState: MatchView | null = null let animationCounter = 0 const tableEl = ref(null) +const canvasEl = ref(null) const sidebarEl = ref(null) const panning = ref(false) const showLog = ref(true) @@ -185,6 +225,13 @@ let cardDrag: { halfHeight: number moved: boolean } | null = null +let blockDrag: { + blockerId: string + pointerId: number + startX: number + startY: number + moved: boolean +} | null = null let suppressCardClick = '' const canvasStyle = computed(() => ({ @@ -255,12 +302,26 @@ const blockWindow = computed(() => Boolean(state.value?.status === 'active' && !game.value.pendingChoice && game.value.step === 'declare_blockers' && game.value.priority === viewerId.value)) +const instantWindow = computed(() => { + const current = game.value + if (!current || !canAct.value) return false + const mainPhase = current.phase === 'precombat_main' || current.phase === 'postcombat_main' + if (mainPhase && !current.stack.length) return false + if (!current.stack.length && attackWindow.value && myUntappedCreatures.value.length) return false + if (!current.stack.length && blockWindow.value && incomingAttackers.value.length + && myUntappedCreatures.value.length) return false + return true +}) const castCard = computed(() => { if (!state.value || !castCardId.value) return undefined return state.value.game?.hand.find(card => card.id === castCardId.value) ?? me.value?.command?.find(card => card.id === castCardId.value) + ?? me.value?.exile?.find(card => card.id === castCardId.value) }) const overloadAbility = computed(() => castCard.value?.abilities.find(ability => ability.kind === 'overload')) +const castTargetOptions = computed(() => targetOptionsFor(castCard.value?.targets)) +const castNeedsTarget = computed(() => Boolean(castCard.value?.targets?.length) && !castOverload.value) +const abilityTargetOptions = computed(() => targetOptionsFor(pendingAbility.value?.ability.targets)) const pendingSearch = computed(() => game.value?.pendingSearch) const searchFilter = ref('') const searchInput = ref(null) @@ -297,6 +358,7 @@ const browseView = computed(() => { const sidebarOpen = computed(() => Boolean((pendingSearch.value && pendingSearch.value.player !== viewerId.value) || (pendingChoice.value && pendingChoice.value.player !== viewerId.value) || castCard.value + || pendingAbility.value || browseView.value || playmatOpen.value || attackWindow.value @@ -326,6 +388,36 @@ const targetOptions = computed(() => { } return options }) + +function visibleCard(id: string): CardView | undefined { + for (const player of state.value?.players ?? []) { + const card = player.battlefield?.find(entry => entry.id === id) + ?? player.graveyard?.find(entry => entry.id === id) + ?? player.exile?.find(entry => entry.id === id) + ?? player.command?.find(entry => entry.id === id) + if (card) return card + } + return state.value?.game?.hand.find(entry => entry.id === id) +} + +function targetLabel(target: TargetChoice): string { + if (target.kind === 'player') return playerName(target.id) + if (target.kind === 'spell') { + const item = game.value?.stack.find(entry => entry.id === target.id) + return item ? `Spell: ${item.label}` : 'Spell' + } + const card = visibleCard(target.id) + return card ? `${card.name} (${playerName(card.controller)})` : 'Card' +} + +function targetOptionsFor(targets: TargetChoice[] | undefined): { value: string; label: string }[] { + if (!targets) return targetOptions.value + const options = [{ value: '', label: 'Auto (first legal target)' }] + for (const target of targets) { + options.push({ value: `${target.kind}:${target.id}`, label: targetLabel(target) }) + } + return options +} const connectionClass = computed(() => connection.value === 'live' ? 'good' : connection.value === 'offline' ? 'bad' : '') function playerName(id?: string): string { @@ -341,11 +433,27 @@ function activatedAbilities(card: CardView): AbilityView[] { return card.abilities.filter(ability => ability.kind === 'activated') } +const MANA_COLOR_NAMES: Record = { + W: 'white', + U: 'blue', + B: 'black', + R: 'red', + G: 'green', + C: 'colorless', +} + function toggleCard(card: CardView, event?: MouseEvent | KeyboardEvent) { if (suppressCardClick === card.id) { suppressCardClick = '' return } + // While choosing a target, clicking a legal creature picks it. + const targets = castCard.value ? castCard.value.targets : pendingAbility.value?.ability.targets + if (targets?.some(target => target.kind === 'object' && target.id === card.id)) { + if (castCard.value) selectedTarget.value = `object:${card.id}` + else abilityTarget.value = `object:${card.id}` + return + } const open = selectedCardId.value !== card.id selectedCardId.value = open ? card.id : '' if (!open || card.controller !== viewerId.value || !activatedAbilities(card).length) { @@ -430,11 +538,123 @@ function commanderTax(player: PlayerView, card: CardView): number { return (player.commanderCasts?.[card.id] ?? 0) * 2 } -function blockersFor(attackerId: string): CardView[] { - const used = new Set(Object.entries(blockSelection) - .filter(([id, blocker]) => id !== attackerId && blocker) - .map(([, blocker]) => blocker)) - return myUntappedCreatures.value.filter(card => !used.has(card.id)) +function blockerName(blockerId: string): string { + return myBattlefield.value.find(card => card.id === blockerId)?.name ?? 'Creature' +} + +function assignBlock(attackerId: string, blockerId: string) { + for (const [attacker, blocker] of Object.entries(blockSelection)) { + if (blocker === blockerId) delete blockSelection[attacker] + } + blockSelection[attackerId] = blockerId +} + +function removeBlock(attackerId: string) { + delete blockSelection[attackerId] +} + +function blockTargetAt(x: number, y: number): string { + for (const element of document.elementsFromPoint(x, y)) { + const id = element.closest('.perm')?.dataset.cardId + if (id && incomingAttackers.value.some(entry => entry.card.id === id)) return id + } + return '' +} + +/** Board-space box (the canvas is transformed, the SVG inside it is not). */ +function elementBox(element: Element | null | undefined): Box | null { + const canvas = canvasEl.value + if (!canvas || !element) return null + const rect = element.getBoundingClientRect() + const base = canvas.getBoundingClientRect() + const scale = view.scale || 1 + return { + center: { + x: (rect.left + rect.width / 2 - base.left) / scale, + y: (rect.top + rect.height / 2 - base.top) / scale, + }, + halfWidth: rect.width / 2 / scale, + halfHeight: rect.height / 2 / scale, + } +} + +function cardBox(cardId: string): Box | null { + const cards = canvasEl.value?.querySelectorAll('[data-card-id]') ?? [] + return elementBox([...cards].find(element => element.dataset.cardId === cardId)) +} + +function playerHeadBox(playerId: string): Box | null { + const players = canvasEl.value?.querySelectorAll('.player[data-player-id]') ?? [] + const player = [...players].find(element => element.dataset.playerId === playerId) + return elementBox(player?.querySelector('.player-head')) +} + +/** Point on the box border facing `toward`, with a small gap so the arrowhead stays visible. */ +function edgePoint(box: Box, toward: Point): Point { + const dx = toward.x - box.center.x + const dy = toward.y - box.center.y + const length = Math.hypot(dx, dy) + if (!length) return { ...box.center } + const ux = dx / length + const uy = dy / length + const reach = Math.min( + ux ? box.halfWidth / Math.abs(ux) : Infinity, + uy ? box.halfHeight / Math.abs(uy) : Infinity, + ) + return { + x: box.center.x + ux * (reach + 8), + y: box.center.y + uy * (reach + 8), + } +} + +function pointerPoint(x: number, y: number): Point | null { + const canvas = canvasEl.value + if (!canvas) return null + const rect = canvas.getBoundingClientRect() + const scale = view.scale || 1 + return { x: (x - rect.left) / scale, y: (y - rect.top) / scale } +} + +function refreshCombatArrows() { + if (!blockWindow.value) { + combatArrows.value = [] + return + } + const arrows: CombatArrow[] = [] + const head = playerHeadBox(viewerId.value) + for (const { card } of incomingAttackers.value) { + const attacker = cardBox(card.id) + if (!attacker || !head) continue + arrows.push({ + key: `attack-${card.id}`, + from: edgePoint(attacker, head.center), + to: edgePoint(head, attacker.center), + tone: 'attack', + }) + } + for (const [attackerId, blockerId] of Object.entries(blockSelection)) { + if (!blockerId) continue + const attacker = cardBox(attackerId) + const blocker = cardBox(blockerId) + if (!attacker || !blocker) continue + arrows.push({ + key: `block-${attackerId}-${blockerId}`, + from: edgePoint(blocker, attacker.center), + to: edgePoint(attacker, blocker.center), + tone: 'block', + }) + } + combatArrows.value = arrows +} + +function arrowPath(from: Point, to: Point): string { + const dx = to.x - from.x + const dy = to.y - from.y + const length = Math.hypot(dx, dy) || 1 + const bend = Math.min(80, length * 0.12) + const mx = (from.x + to.x) / 2 - (dy / length) * bend + const my = (from.y + to.y) / 2 + (dx / length) * bend + return `M ${from.x.toFixed(1)} ${from.y.toFixed(1)} Q ${mx.toFixed(1)} ${my.toFixed(1)} ${to.x.toFixed(1)} ${to.y.toFixed(1)}` } function parseTarget(value: string): { kind: 'player' | 'object' | 'spell'; id: string } | null { @@ -464,6 +684,22 @@ async function act(action: Record): Promise { } } +let autoPassedVersion = -1 + +async function maybeAutoPass() { + if (busy.value || !autoPassInstants.value || !instantWindow.value) return + const version = state.value?.version ?? -1 + if (version === autoPassedVersion) return + autoPassedVersion = version + await act({ type: 'pass' }) +} + +watch(autoPassInstants, enabled => { + if (enabled) autoPassedVersion = -1 + void maybeAutoPass() +}) +watch([() => state.value?.version, busy], () => { void maybeAutoPass() }) + async function loadSummary() { try { const data = await $fetch<{ games: MatchSummary[] }>(`${apiBase}/games`) @@ -640,9 +876,19 @@ async function playCard(card: CardView) { await playLand(card) return } + if (needsCastOptions(card) || card.targets?.length) { + openCast(card) + return + } await act({ type: 'cast', cardId: card.id, targets: [], x: 0 }) } +/** Impulse cards are cast or played from the exile browser. */ +async function playExiled(card: CardView) { + browsingZone.value = null + await playCard(card) +} + /** Place a hand card on the fan: spread, tilt and arc drop around the middle card. */ function fanStyle(index: number, total: number) { const offset = index - (total - 1) / 2 @@ -716,6 +962,19 @@ function startCardMove(card: CardView, event: PointerEvent) { if (!board) return event.stopPropagation() perm.setPointerCapture(event.pointerId) + if (blockWindow.value + && incomingAttackers.value.length + && myUntappedCreatures.value.some(entry => entry.id === card.id)) { + blockDrag = { + blockerId: card.id, + pointerId: event.pointerId, + startX: event.clientX, + startY: event.clientY, + moved: false, + } + blockDragId.value = card.id + return + } const rect = perm.getBoundingClientRect() cardDrag = { cardId: card.id, @@ -732,6 +991,17 @@ function startCardMove(card: CardView, event: PointerEvent) { } function moveCardPreview(event: PointerEvent) { + if (blockDrag) { + if (blockDrag.pointerId !== event.pointerId) return + if (!blockDrag.moved && Math.hypot(event.clientX - blockDrag.startX, event.clientY - blockDrag.startY) < 4) return + blockDrag.moved = true + const to = pointerPoint(event.clientX, event.clientY) + const box = cardBox(blockDrag.blockerId) + const from = box && to ? edgePoint(box, to) : null + blockDragLine.value = from && to ? { from, to } : null + blockHoverId.value = blockTargetAt(event.clientX, event.clientY) + return + } const drag = cardDrag if (!drag || drag.pointerId !== event.pointerId) return if (!drag.moved && Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) < 4) return @@ -763,6 +1033,21 @@ function attackDropTargetAt(cardId: string, x: number, y: number): string { } async function endCardMove(event: PointerEvent) { + if (blockDrag) { + if (blockDrag.pointerId !== event.pointerId) return + const drag = blockDrag + blockDrag = null + blockDragId.value = '' + blockDragLine.value = null + blockHoverId.value = '' + if (!drag.moved) return + // The click that follows a drag must not open the ability menu. + suppressCardClick = drag.blockerId + setTimeout(() => { suppressCardClick = '' }, 0) + const attackerId = blockTargetAt(event.clientX, event.clientY) + if (attackerId) assignBlock(attackerId, drag.blockerId) + return + } const drag = cardDrag if (!drag || drag.pointerId !== event.pointerId) return cardDrag = null @@ -801,6 +1086,13 @@ async function endCardMove(event: PointerEvent) { } function cancelCardMove(event: PointerEvent) { + if (blockDrag?.pointerId === event.pointerId) { + blockDrag = null + blockDragId.value = '' + blockDragLine.value = null + blockHoverId.value = '' + return + } if (cardDrag?.pointerId !== event.pointerId) return cardDrag = null dragPreview.value = null @@ -808,6 +1100,8 @@ function cancelCardMove(event: PointerEvent) { } function openCast(card: CardView) { + pendingAbility.value = null + abilityTarget.value = '' castCardId.value = card.id selectedTarget.value = '' castX.value = 0 @@ -834,13 +1128,38 @@ async function confirmCast() { if (ok) cancelCast() } -async function activate(card: CardView, ability: AbilityView) { - await act({ type: 'activate', sourceId: card.id, abilityIndex: ability.index }) +async function activate(card: CardView, ability: AbilityView, color?: string) { + cancelCast() + if (ability.targets?.length) { + pendingAbility.value = { card, ability, color } + abilityTarget.value = '' + return + } + await act({ type: 'activate', sourceId: card.id, abilityIndex: ability.index, color }) } -async function activateFromMenu(card: CardView, ability: AbilityView) { +async function activateFromMenu(card: CardView, ability: AbilityView, color?: string) { closeMenu() - await activate(card, ability) + await activate(card, ability, color) +} + +function cancelActivation() { + pendingAbility.value = null + abilityTarget.value = '' +} + +async function confirmActivation() { + const pending = pendingAbility.value + if (!pending) return + const target = parseTarget(abilityTarget.value) + const ok = await act({ + type: 'activate', + sourceId: pending.card.id, + abilityIndex: pending.ability.index, + color: pending.color, + targets: target ? [target] : [], + }) + if (ok) cancelActivation() } async function chooseSearchCard(card: CardView) { @@ -858,6 +1177,11 @@ async function chooseCost(pay: boolean) { await act({ type: 'choose_cost', pay }) } +async function chooseHideawayCard(card: CardView) { + if (busy.value) return + await act({ type: 'choose_hideaway', cardId: card.id }) +} + async function attack() { const attackers = selectedAttackers.value .filter(attackerId => attackTargets[attackerId]) @@ -1002,10 +1326,17 @@ function resetAnimations() { watch(() => game.value?.step, () => { selectedAttackers.value = [] attackDropId.value = '' + blockDrag = null + blockDragId.value = '' + blockDragLine.value = null + blockHoverId.value = '' for (const key of Object.keys(attackTargets)) delete attackTargets[key] for (const key of Object.keys(blockSelection)) delete blockSelection[key] }) +watch([blockWindow, () => state.value?.version], refreshCombatArrows, { flush: 'post' }) +watch(blockSelection, refreshCombatArrows, { flush: 'post' }) + watch(() => Boolean(pendingSearch.value), async active => { if (!active) return searchFilter.value = '' @@ -1022,6 +1353,7 @@ watch(() => pendingChoice.value?.sourceId, async sourceId => { onMounted(async () => { window.addEventListener('keydown', onKeydown) + window.addEventListener('resize', refreshCombatArrows) decks.value = (await loadDecks(apiBase)).sort((a, b) => b.updatedAt - a.updatedAt) joinName.value = localStorage.getItem('commander-player-name') ?? '' deckId.value = decks.value.find(deck => !deckValidation(deck).length)?.id @@ -1047,6 +1379,7 @@ onMounted(async () => { onUnmounted(() => { window.removeEventListener('keydown', onKeydown) + window.removeEventListener('resize', refreshCombatArrows) events?.close() for (const timer of animationTimers) clearTimeout(timer) animationTimers.clear() @@ -1190,7 +1523,46 @@ onUnmounted(() => { @pointercancel="endPan" @wheel.prevent="zoomTable" > -
+
+
{ v-for="card in player.battlefield" :key="card.id" class="perm" + :data-card-id="card.id" :class="{ selected: selectedCardId === card.id, positioned: isPositioned(card), dragging: dragPreview?.cardId === card.id, movable: card.controller === viewerId, + 'block-source': blockDragId === card.id, + 'block-hover': blockHoverId === card.id, 'pending-attack': attackTargets[card.id], 'anim-enter': cardEnterAnimations[card.id], 'anim-damage': cardDamageAnimations[card.id], 'anim-attack': cardAttackAnimations[card.id], + 'has-hidden': card.hiddenCards, }" :style="permStyle(card)" :title="card.oracleText" @@ -1316,6 +1692,19 @@ onUnmounted(() => { @keydown.enter.prevent="toggleCard(card, $event)" @keydown.space.prevent="toggleCard(card, $event)" > +
+ +
♛ @@ -1483,14 +1872,26 @@ onUnmounted(() => {

Empty.

- - - +
@@ -1500,12 +1901,14 @@ onUnmounted(() => {
-

{{ pendingChoice.what === 'pay_cost' ? 'Pay a cost' : 'Choose a type' }}

+

{{ pendingChoice.what === 'pay_cost' ? 'Pay a cost' : pendingChoice.what === 'hideaway' ? 'Hideaway' : 'Choose a type' }}

{{ playerName(pendingChoice.player) }} {{ pendingChoice.what === 'pay_cost' ? `is deciding whether to pay ${pendingCostLabel} for ${pendingChoice.sourceName}.` - : `is choosing a creature type for ${pendingChoice.sourceName}.` }} + : pendingChoice.what === 'hideaway' + ? 'is looking at the top cards of their library.' + : `is choosing a creature type for ${pendingChoice.sourceName}.` }}

@@ -1523,10 +1926,10 @@ onUnmounted(() => { {{ overloadAbility.text ?? 'Overload' }} -