import type { Ability, CompiledCard, Condition, Cost, Duration, Effect, ManaSpec, ObjectSelector, PlayerRef, StaticEffect, Target, TokenSpec, TriggerEvent, Value, } from './types.js' const COLOR_NAMES: Record = { W: 'white', U: 'blue', B: 'black', R: 'red', G: 'green', C: 'colorless' } const PLAYER_NAMES: Record = { you: 'you', opponent: 'opponent', each_opponent: 'eachOpponent', each_player: 'eachPlayer', target_player: 'targetPlayer', that_player: 'thatPlayer', its_controller: 'itsController', its_owner: 'itsOwner', } const DURATION_NAMES: Record = { permanent: 'permanent', until_end_of_turn: 'untilEndOfTurn', until_your_next_turn: 'untilYourNextTurn', until_end_of_your_next_turn: 'untilEndOfYourNextTurn', until_end_of_combat: 'untilEndOfCombat', until_controllers_next_untap_step: 'untilControllersNextUntapStep', while_source_on_battlefield: 'whileSourceOnBattlefield', } function quote(text: string): string { return `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n').replace(/\r/g, '\\r')}'` } function indent(text: string, spaces = 2): string { const pad = ' '.repeat(spaces) return text.split('\n').map(line => `${pad}${line}`).join('\n') } function list(items: string[]): string { if (!items.length) return '[]' return `[\n${items.map(item => indent(item)).join(',\n')},\n]` } function callback(items: string[]): string { if (!items.length) return '() => {}' if (items.length === 1) return `() => ${items[0]}` return `() => {\n${items.map(item => indent(item)).join('\n')}\n}` } function options(entries: Array<[string, string | undefined]>): string | undefined { const parts = entries.filter(([, value]) => value !== undefined).map(([key, value]) => `${key}: ${value}`) return parts.length ? `{ ${parts.join(', ')} }` : undefined } function optionArg(entries: Array<[string, string | undefined]>): string { const value = options(entries) return value ? `, ${value}` : '' } function formatPlayer(player: PlayerRef): string { return PLAYER_NAMES[player] } function formatValue(value: Value): string { switch (value.kind) { case 'number': return String(value.value) case 'x': return 'X' case 'count': return `count(${formatSelector(value.selector)})` case 'source_power': return 'itsPower' case 'source_toughness': return 'itsToughness' case 'cards_in_hand': return `cardsInHand(${formatPlayer(value.player)})` case 'max_cards_in_hand': return 'maxCardsInHand()' case 'max_opponent_count': return `maxOpponentCount(${formatSelector(value.selector)})` case 'total_mana_value': return `totalManaValue(${formatSelector(value.selector)})` case 'total_power': return `totalPower(${formatSelector(value.selector)})` case 'any_number': return 'anyNumber()' case 'event_amount': return 'eventAmount()' } } function formatSelector(selector: ObjectSelector): string { let text = 'permanents' if (selector.other) text += '.other()' if (selector.tapped === true) text += '.tapped()' if (selector.tapped === false) text += '.untapped()' if (selector.attacking) text += '.attacking()' if (selector.token === true) text += '.token()' if (selector.token === false) text += '.nontoken()' if (selector.attached === 'equipped') text += '.equipped()' if (selector.attached === 'enchanted') text += '.enchanted()' 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(', ')})` } if (selector.subtypes?.length) { text += `.withSubtype(${selector.subtypes.map(quote).join(', ')})` } if (selector.types?.length) { text += `.withType(${selector.types.map(quote).join(', ')})` } if (selector.excludeTypes?.length) { text += `.withoutType(${selector.excludeTypes.map(quote).join(', ')})` } if (selector.counters) { text += `.withCounter(${quote(selector.counters.counter)}, ${selector.counters.atLeast})` } if (selector.keywords?.length) { text += `.withKeyword(${selector.keywords.map(quote).join(', ')})` } if (selector.excludeKeywords?.length) { text += `.withoutKeyword(${selector.excludeKeywords.map(quote).join(', ')})` } if (selector.power?.atLeast !== undefined) text += `.powerAtLeast(${selector.power.atLeast})` if (selector.power?.atMost !== undefined) text += `.powerAtMost(${selector.power.atMost})` if (selector.toughness?.atLeast !== undefined) text += `.toughnessAtLeast(${selector.toughness.atLeast})` if (selector.toughness?.atMost !== undefined) text += `.toughnessAtMost(${selector.toughness.atMost})` if (selector.manaValue?.atLeast !== undefined) text += `.manaValueAtLeast(${selector.manaValue.atLeast})` if (selector.manaValue?.atMost !== undefined) text += `.manaValueAtMost(${selector.manaValue.atMost})` if (selector.name) text += `.named(${quote(selector.name)})` if (selector.controller === 'you') text += '.youControl()' else if (selector.controller === 'opponent') text += '.opponentControls()' else if (selector.controller === 'any') text += `.controlledBy('any')` if (selector.owner === 'you') text += `.ownedBy('you')` else if (selector.owner === 'opponent') text += `.ownedBy('opponent')` if (selector.zone) text += `.inZone(${quote(selector.zone)})` if (selector.match === 'any') text += '.matchingAny()' return text } function isBareSelector(selector: ObjectSelector): boolean { return selector.types?.length === 0 && Object.keys(selector).every(key => key === 'types') } function formatTargetOptions(target: Extract): string { return optionArg([ ['count', target.count !== undefined ? String(target.count) : undefined], ['upTo', target.upTo ? 'true' : undefined], ['includeSelf', target.includeSelf ? 'true' : undefined], ]).replace(/^, /, '') } export function formatTarget(target: Target): string { switch (target.kind) { case 'self': return 'self' case 'trigger_subject': return 'triggerSubject' case 'previous_target': return 'previousTarget' case 'any': return 'anyTarget' case 'player_or_planeswalker': return 'targetPlayerOrPlaneswalker' case 'player': return target.mode === 'each' ? `each(${formatPlayer(target.who)})` : `target(${formatPlayer(target.who)})` case 'object': { const name = target.mode === 'target' ? 'target' : target.mode === 'each' ? 'each' : 'pick' const extra = formatTargetOptions(target) return `${name}(${formatSelector(target.selector)}${extra ? `, ${extra}` : ''})` } case 'spell': return isBareSelector(target.selector) ? 'targetSpell()' : `targetSpell(${formatSelector(target.selector)})` case 'ability': return target.selector ? `targetAbility(${formatSelector(target.selector)})` : 'targetAbility()' case 'divided': return `divided(${target.max === 'any' ? quote('any') : target.max}${target.selector ? `, ${formatSelector(target.selector)}` : ''})` } } function formatMana(mana: ManaSpec): string { if (mana.kind === 'symbols') { return `mana(${quote(mana.symbols.join(''))}${optionArg([ ['oneOf', mana.oneOf ? 'true' : undefined], ['restriction', mana.restriction ? quote(mana.restriction) : undefined], ])})` } return `anyColor(${formatValue(mana.amount)}${optionArg([ ['oneColor', mana.oneColor ? 'true' : undefined], ['restriction', mana.restriction ? quote(mana.restriction) : undefined], ])})` } function formatCost(cost: Cost): string { switch (cost.kind) { case 'mana': return `manaCost(${quote(cost.symbols)})` case 'tap': return 'tapCost()' case 'untap': return 'untapCost()' case 'tap_other': return `tapOther(${formatSelector(cost.selector)})` case 'energy': return `energyCost(${cost.amount})` case 'loyalty': return `loyalty(${cost.amount})` case 'pay_life': return `payLife(${formatValue(cost.amount)})` case 'discard': return `discardCost(${formatValue(cost.amount)}${optionArg([ ['player', cost.player === 'you' ? undefined : formatPlayer(cost.player)], ['random', cost.random ? 'true' : undefined], ])})` case 'sacrifice': return `sacrificeCost(${formatSelector(cost.selector)})` case 'sacrifice_self': return 'sacrificeSelf()' case 'exile_self': return 'exileSelf()' case 'exile_from_graveyard': return `exileFromGraveyard(${formatSelector(cost.selector)}${cost.amount ? `, ${formatValue(cost.amount)}` : ''})` case 'reveal': return `reveal(${formatSelector(cost.selector)})` case 'choice': return `choice([${cost.options.map(option => `[${option.map(formatCost).join(', ')}]`).join(', ')}])` case 'return_to_hand': return `returnToHandCost(${formatSelector(cost.selector)})` case 'behold': return `behold(${formatSelector(cost.selector)})` case 'waterbend': return `waterbend(${formatValue(cost.amount)})` case 'blight': return `blight(${formatValue(cost.amount)})` case 'choose': return `chooseCost(${quote(cost.what)})` case 'put_counter': return `putCounterCost(${quote(cost.counter)}, ${formatSelector(cost.selector)})` case 'remove_counters': return `removeCountersCost(${quote(cost.counter)}, ${formatValue(cost.amount)}${cost.selector ? `, ${formatSelector(cost.selector)}` : ''})` case 'forage': return 'forage()' case 'collect_evidence': return `collectEvidence(${cost.amount})` case 'mill': return `millCost(${formatValue(cost.amount)})` } } function formatDuration(duration: Duration): string | undefined { return duration === 'permanent' ? undefined : DURATION_NAMES[duration] } function formatToken(token: TokenSpec): string { return `token(${options([ ['name', token.name ? quote(token.name) : undefined], ['types', token.types.length ? `[${token.types.map(quote).join(', ')}]` : undefined], ['subtypes', token.subtypes.length ? `[${token.subtypes.map(quote).join(', ')}]` : undefined], ['colors', token.colors.length ? `[${token.colors.map(color => quote(COLOR_NAMES[color] ?? color)).join(', ')}]` : undefined], ['power', token.power ? formatValue(token.power) : undefined], ['toughness', token.toughness ? formatValue(token.toughness) : undefined], ['keywords', token.keywords?.length ? `[${token.keywords.map(quote).join(', ')}]` : undefined], ['tapped', token.tapped ? 'true' : undefined], ])})` } function formatEffectList(effects: Effect[]): string { return callback(effects.map(formatEffect)) } export function formatEffect(effect: Effect): string { switch (effect.op) { case 'damage': return `damage(${formatTarget(effect.target)}, ${formatValue(effect.amount)}${effect.source ? `, ${formatTarget(effect.source)}` : ''})` case 'draw': return `draw(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'discard': return `discard(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}${optionArg([['random', effect.random ? 'true' : undefined]])})` case 'mill': return `mill(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'life': return `${effect.mode === 'gain' ? 'gainLife' : 'loseLife'}(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'pump': return `pump(${formatTarget(effect.target)}, ${formatValue(effect.power)}, ${formatValue(effect.toughness)}${formatDuration(effect.duration) ? `, ${formatDuration(effect.duration)}` : ''})` case 'grant': return `grant(${formatTarget(effect.target)}, ${quote(effect.keyword)}${optionArg([ ['value', effect.value ? quote(effect.value) : undefined], ['duration', formatDuration(effect.duration)], ])})` case 'put_counters': return `putCounters(${formatTarget(effect.target)}, ${quote(effect.counter)}, ${formatValue(effect.amount)})` case 'remove_counters': return `removeCounters(${formatTarget(effect.target)}, ${quote(effect.counter)}, ${formatValue(effect.amount)})` case 'proliferate': return 'proliferate()' 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)}${effect.attachTo ? `, { attachTo: ${formatTarget(effect.attachTo)} }` : ''})` case 'destroy': return `destroy(${formatTarget(effect.target)})` case 'exile': return `exile(${formatTarget(effect.target)})` case 'sacrifice': return `sacrifice(${formatPlayer(effect.player)}, ${formatTarget(effect.target)}${effect.unless ? `, ${formatCost(effect.unless)}` : ''})` case 'counter': return `counter(${quote(effect.what)}, ${formatTarget(effect.target)}${effect.unless ? `, ${formatCost(effect.unless)}` : ''})` case 'return_to_hand': return `returnToHand(${formatTarget(effect.target)})` case 'return_to_battlefield': return `returnToBattlefield(${formatTarget(effect.target)}${optionArg([ ['tapped', effect.tapped ? 'true' : undefined], ['transformed', effect.transformed ? 'true' : undefined], ['counters', effect.counters ? `{ counter: ${quote(effect.counters.counter)}, amount: ${formatValue(effect.counters.amount)} }` : undefined], ])})` case 'set_pt': return `setPt(${formatTarget(effect.target)}, ${formatValue(effect.power)}, ${formatValue(effect.toughness)}${optionArg([['duration', formatDuration(effect.duration)]])})` case 'put_on_top': return `putOnTop(${formatTarget(effect.target)})` case 'tap': return `tap(${formatTarget(effect.target)})` case 'untap': return `untap(${formatTarget(effect.target)})` case 'scry': return `scry(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'surveil': return `surveil(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'search': return `search(${formatPlayer(effect.player)}, ${formatSelector(effect.selector)}, ${formatValue(effect.amount)}${optionArg([ ['destination', quote(effect.destination)], ['tapped', effect.tapped ? 'true' : undefined], ['shuffle', effect.shuffle ? 'true' : undefined], ['zones', effect.zones?.length ? `[${effect.zones.map(quote).join(', ')}]` : undefined], ['split', effect.split ? `{ destination: ${quote(effect.split.destination)}, tapped: ${effect.split.tapped ? 'true' : 'false'} }` : undefined], ])})` case 'shuffle': return `shuffle(${formatPlayer(effect.player)})` case 'add_mana': return `addMana(${formatPlayer(effect.player)}, ${formatMana(effect.mana)})` case 'fight': return `fight(${formatTarget(effect.a)}, ${formatTarget(effect.b)})` case 'regenerate': return `regenerate(${formatTarget(effect.target)})` case 'energy': return `energy(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'attach': return `attach(${formatTarget(effect.target)})` case 'restriction': return `restrict(${formatTarget(effect.target)}, ${quote(effect.rule)}${formatDuration(effect.duration) ? `, ${formatDuration(effect.duration)}` : ''})` case 'keyword_action': return `keywordAction(${quote(effect.action)}${optionArg([ ['target', effect.target ? formatTarget(effect.target) : undefined], ['amount', effect.amount ? formatValue(effect.amount) : undefined], ['detail', effect.detail ? quote(effect.detail) : undefined], ])})` case 'prevent_damage': return `preventDamage(${formatTarget(effect.target)}, ${effect.amount === 'all' ? quote('all') : formatValue(effect.amount)}${optionArg([ ['combatOnly', effect.combatOnly ? 'true' : undefined], ['duration', formatDuration(effect.duration)], ])})` case 'gain_control': return `gainControl(${formatTarget(effect.target)}${formatDuration(effect.duration) ? `, ${formatDuration(effect.duration)}` : ''})` case 'emblem': return `emblem(${quote(effect.text)})` case 'transform': return `transform(${formatTarget(effect.target)})` case 'pay': return `pay([${effect.costs.map(formatCost).join(', ')}])` case 'conditional': return `ifThen(${formatCondition(effect.condition)}, ${formatEffectList(effect.effects)})` case 'modal': return `modal(${effect.min}, ${effect.max}, ${list(effect.modes.map(mode => formatEffectList(mode)))})` case 'look_top': return `lookTop(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}${optionArg([['reorder', effect.reorder ? 'true' : undefined]])})` case 'schedule': return `schedule(${quote(effect.when)}, ${formatEffectList(effect.effects)})` case 'level_up': return `levelUp(${effect.level})` case 'put_from_among': return `putFromAmong(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}${optionArg([ ['selector', effect.selector ? formatSelector(effect.selector) : undefined], ['destination', quote(effect.destination)], ])})` case 'dig': return `dig(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}${optionArg([ ['pick', formatValue(effect.pick)], ['upTo', effect.upTo ? 'true' : undefined], ['pickSelector', effect.pickSelector ? formatSelector(effect.pickSelector) : undefined], ['to', quote(effect.to)], ['rest', quote(effect.rest)], ['order', effect.order ? quote(effect.order) : undefined], ['optional', effect.optional ? 'true' : undefined], ['tapped', effect.tapped ? 'true' : undefined], ])})` case 'damage_divided': return `damageDivided(${formatValue(effect.amount)}, ${formatTarget(effect.target)})` case 'exile_graveyards': return 'exileGraveyards()' case 'hideaway': return `hideaway(${formatValue(effect.amount)})` case 'play_exiled': return `playExiled(${formatPlayer(effect.player)}${optionArg([['free', effect.free ? 'true' : undefined]])})` } } function formatCondition(condition: Condition): string { switch (condition.kind) { case 'you_control': return `youControl(${formatSelector(condition.selector)}${condition.atLeast !== undefined ? `, ${condition.atLeast}` : ''})` case 'opponent_controls': return `opponentControls(${formatSelector(condition.selector)}${condition.atLeast !== undefined ? `, ${condition.atLeast}` : ''})` case 'your_turn': return 'yourTurn()' case 'not_your_turn': return 'notYourTurn()' case 'source_tapped': return 'sourceTapped()' case 'source_untapped': return 'sourceUntapped()' case 'source_attacking': return 'sourceAttacking()' case 'life_at_least': return `lifeAtLeast(${formatPlayer(condition.player)}, ${condition.amount})` case 'life_at_most': return `lifeAtMost(${formatPlayer(condition.player)}, ${condition.amount})` case 'life_above_starting': return `lifeAboveStarting(${formatPlayer(condition.player)}, ${condition.amount})` case 'cards_in_graveyard': return `cardsInGraveyard(${formatPlayer(condition.player)}, ${condition.atLeast})` case 'hand_empty': return `handEmpty(${formatPlayer(condition.player)})` case 'creature_died_this_turn': return `creatureDiedThisTurn(${condition.controller ? quote(condition.controller) : ''})` case 'you_gained_life_this_turn': return `youGainedLifeThisTurn(${condition.atLeast !== undefined ? condition.atLeast : ''})` case 'you_drew_cards_this_turn': return `youDrewCardsThisTurn(${condition.atLeast !== undefined ? condition.atLeast : ''})` case 'spells_cast_last_turn': return `spellsCastLastTurn(${quote(condition.who)}, ${condition.atLeast})` case 'no_spells_last_turn': return 'noSpellsLastTurn()' case 'attacked_this_turn': return 'attackedThisTurn()' case 'you_attacked_this_turn': return 'youAttackedThisTurn()' case 'defending_player_controls': return `defendingPlayerControls(${formatSelector(condition.selector)})` case 'targets': return `targets(${formatSelector(condition.selector)})` case 'was_kicked': return 'wasKicked()' case 'cast': return `youCastIt(${condition.fromHand ? `{ fromHand: true }` : ''})` case 'in_graveyard': return 'inGraveyard()' case 'on_battlefield': return 'onBattlefield()' case 'monarch': return 'monarch()' case 'initiative': return 'initiative()' case 'citys_blessing': return 'citysBlessing()' case 'suspended': return 'suspended()' case 'bargained': return 'bargained()' case 'was_creature': return 'wasCreature()' case 'opponent_lost_life_this_turn': return 'opponentLostLifeThisTurn()' case 'life_changed_this_turn': return 'lifeChangedThisTurn()' case 'descended_this_turn': return 'descendedThisTurn()' case 'permanent_left_battlefield_this_turn': return 'permanentLeftBattlefieldThisTurn()' case 'nonland_permanents_entered_this_turn': return `nonlandPermanentsEnteredThisTurn(${condition.atLeast})` case 'attacked_with_total_power': return `attackedWithTotalPower(${condition.atLeast})` case 'total_power': return `yourCreaturesTotalPower(${condition.atLeast})` case 'opponent_controls_more_lands': return 'opponentControlsMoreLands()' case 'distinct_powers': return `distinctPowers(${condition.atLeast})` case 'graveyard_card_types': return `graveyardCardTypes(${condition.atLeast})` case 'no_objects': return `noObjects(${formatSelector(condition.selector)})` case 'cards_in_hand_at_most': return `cardsInHandAtMost(${formatPlayer(condition.who)}, ${condition.atMost})` case 'not_their_turn': return 'notTheirTurn()' case 'no_attackers': return 'noAttackers()' case 'opponent_poison': return `opponentPoison(${condition.atLeast})` case 'tribute_not_paid': return 'tributeNotPaid()' case 'had_counters': return `hadCounters(${condition.counter ? quote(condition.counter) : ''})` case 'mana_from_treasure': return 'manaFromTreasure()' case 'mana_spent': return `manaSpent(${condition.atLeast})` case 'no_mana_spent': return 'noManaSpent()' case 'mana_symbol_spent': return `manaSymbolSpent(${quote(condition.symbols)})` case 'kicked_with': return `kickedWith(${quote(condition.cost)})` case 'more_cards_than_each_opponent': return 'moreCardsThanEachOpponent()' case 'first_combat_phase': return 'firstCombatPhase()' case 'not_token': return 'notToken()' case 'cast_spell_this_turn': return `castSpellThisTurn(${condition.noncreature ? `{ noncreature: true }` : ''})` case 'full_party': return 'fullParty()' case 'graveyard_count': return `graveyardCount(${formatSelector(condition.selector)}, ${condition.atLeast})` case 'creature_power_greater_than_base': return `creaturePowerGreaterThanBase(${quote(condition.stat)})` case 'if_you_do': return 'ifYouDo()' case 'if_you_dont': return 'ifYouDont()' case 'otherwise': return 'otherwise()' case 'you_control_commander': return 'youControlCommander()' case 'distinct_names': return `distinctNames(${formatSelector(condition.selector)}, ${condition.atLeast})` case 'opponent_damaged_this_turn': return `opponentDamagedThisTurn(${condition.atLeast})` case 'attacked_with_creatures': return `attackedWithCreatures(${condition.atLeast})` case 'library_at_most': return `libraryAtMost(${condition.atMost})` case 'event_subject_toughness_at_most': return `eventSubjectToughnessAtMost(${condition.amount})` } } function formatTrigger(event: TriggerEvent): string { switch (event.kind) { case 'enters': return `when.enters(${formatTarget(event.subject)})` case 'dies': return `when.dies(${formatTarget(event.subject)})` case 'attacks': return `when.attacks(${formatTarget(event.subject)})` case 'blocks': return `when.blocks(${formatTarget(event.subject)})` case 'attacks_or_blocks': return `when.attacksOrBlocks(${formatTarget(event.subject)})` case 'enters_or_attacks': return `when.entersOrAttacks(${formatTarget(event.subject)})` case 'enters_or_dies': return `when.entersOrDies(${formatTarget(event.subject)})` case 'leaves_battlefield': return `when.leavesBattlefield(${formatTarget(event.subject)})` case 'deals_damage': return `when.dealsDamage(${formatTarget(event.subject)}, ${quote(event.recipient)}${optionArg([['combat', event.combat ? 'true' : undefined]])})` case 'upkeep': return `when.upkeep(${formatPlayer(event.who)})` case 'end_step': return `when.endStep(${formatPlayer(event.who)})` case 'begin_combat': return `when.beginCombat(${formatPlayer(event.who)})` case 'main_phase': return `when.${event.phase === 'first' ? 'firstMainPhase' : 'postcombatMainPhase'}(${formatPlayer(event.who)})` case 'cast': return `when.cast(${formatPlayer(event.who)}${isBareSelector(event.spell) ? '' : `, ${formatSelector(event.spell)}`}${optionArg([ ['targetsSelf', event.targetsSelf ? 'true' : undefined], ['orCopy', event.orCopy ? 'true' : undefined], ['ordinal', event.ordinal !== undefined ? String(event.ordinal) : undefined], ])})` case 'becomes_level': return `when.becomesLevel(${event.level})` case 'draw': return `when.draw(${formatPlayer(event.who)}${event.ordinal !== undefined ? `, ${event.ordinal}` : ''})` case 'counter_placed': return `when.counterPlaced(${formatTarget(event.subject)}${event.counter ? `, ${quote(event.counter)}` : ''})` case 'becomes_target': return `when.becomesTarget(${formatTarget(event.subject)})` case 'life': return `when.${event.mode === 'gain' ? 'lifeGained' : 'lifeLost'}(${formatPlayer(event.who)})` } } function formatStaticEffect(effect: StaticEffect): string { switch (effect.op) { case 'pump': return `staticPump(${formatTarget(effect.target)}, ${formatValue(effect.power)}, ${formatValue(effect.toughness)})` case 'grant': return `staticGrant(${formatTarget(effect.target)}, ${quote(effect.keyword)}${optionArg([['value', effect.value ? quote(effect.value) : undefined]])})` case 'grant_ability': return `grantAbility(${formatTarget(effect.target)}, ${formatAbility(effect.ability)})` case 'restriction': return `staticRestrict(${formatTarget(effect.target)}, ${quote(effect.rule)}${optionArg([ ['value', effect.value ? formatValue(effect.value) : undefined], ['comparison', effect.comparison ? quote(effect.comparison) : undefined], ['detail', effect.detail ? quote(effect.detail) : undefined], ['condition', effect.condition ? formatCondition(effect.condition) : undefined], ])})` case 'enters_tapped': return `entersTapped(${formatTarget(effect.target)}${optionArg([ ['unless', effect.unless ? formatCondition(effect.unless) : undefined], ['unlessCost', effect.unlessCost ? formatCost(effect.unlessCost) : undefined], ])})` case 'enters_with_counters': return `entersWithCounters(${formatTarget(effect.target)}, ${quote(effect.counter)}, ${formatValue(effect.amount)})` case 'set_pt': return `staticSetPt(${formatTarget(effect.target)}, ${effect.power ? formatValue(effect.power) : 'null'}, ${effect.toughness ? formatValue(effect.toughness) : 'null'}${optionArg([['base', effect.base ? 'true' : undefined]])})` case 'control': return `control(${formatTarget(effect.target)})` case 'choose': return `choose(${quote(effect.what)})` case 'replacement': return `replace(${quote(effect.what)}${optionArg([ ['target', effect.target ? formatTarget(effect.target) : undefined], ['instead', quote(effect.instead)], ])})` case 'cost_reduction': return `costReduction(${formatTarget(effect.target)}, ${effect.symbols ? quote(effect.symbols) : effect.amount ? formatValue(effect.amount) : '0'}${optionArg([['condition', effect.condition ? formatCondition(effect.condition) : undefined]])})` case 'cost_increase': return `costIncrease(${formatValue(effect.amount)}${optionArg([['spellType', effect.spellType ? quote(effect.spellType) : undefined]])})` case 'search_restriction': 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], ])})` } } function formatStaticEffectList(effects: StaticEffect[]): string { return callback(effects.map(formatStaticEffect)) } export function formatAbility(ability: Ability): string { switch (ability.kind) { case 'keyword': return `keyword(${quote(ability.keyword)}${ability.value ? `, ${quote(ability.value)}` : ''})` case 'keywords': return `keywords(${ability.keywords.map(keyword => quote(`${keyword.keyword}${keyword.value ? ` ${keyword.value}` : ''}`)).join(', ')})` case 'triggered': return `triggered(${formatTrigger(ability.event)}, ${formatEffectList(ability.effects)}${optionArg([ ['condition', ability.condition ? formatCondition(ability.condition) : undefined], ['optional', ability.optional ? 'true' : undefined], ])})` case 'activated': return `activated([${ability.costs.map(formatCost).join(', ')}], ${formatEffectList(ability.effects)}${optionArg([ ['condition', ability.condition ? formatCondition(ability.condition) : undefined], ['timing', ability.timing ? quote(ability.timing) : undefined], ['activationsPerTurn', ability.activationsPerTurn !== undefined ? String(ability.activationsPerTurn) : undefined], ['optional', ability.optional ? 'true' : undefined], ])})` case 'static': return `staticAbility(${formatStaticEffectList(ability.effects)}${optionArg([ ['condition', ability.condition ? formatCondition(ability.condition) : undefined], ])})` case 'spell': return `spell(${formatEffectList(ability.effects)}${optionArg([['optional', ability.optional ? 'true' : undefined]])})` case 'additional_cost': return `additionalCost([${ability.costs.map(formatCost).join(', ')}]${optionArg([['optional', ability.optional ? 'true' : undefined]])})` case 'alternative_cost': return `alternativeCost([${ability.costs.map(formatCost).join(', ')}]${optionArg([ ['condition', ability.condition ? formatCondition(ability.condition) : undefined], ])})` case 'overload': return `overload(${quote(ability.cost)})` case 'chapter': return `chapter([${ability.chapters.map(quote).join(', ')}], ${formatEffectList(ability.effects)}${optionArg([['optional', ability.optional ? 'true' : undefined]])})` case 'level_band': return `levelBand(${ability.min}, ${ability.max !== undefined ? ability.max : 'null'}${ability.power ? `, ${formatValue(ability.power)}, ${formatValue(ability.toughness!)}` : ''})` case 'level_pt': return `levelPt(${formatValue(ability.power)}, ${formatValue(ability.toughness)})` case 'unsupported': return `unsupported(${quote(ability.reason)}, ${quote(ability.text)})` } } function formatAbilityList(abilities: Ability[]): string { return list(abilities.map(formatAbility)) } export function formatCard(card: CompiledCard): string { const header = `// ${card.name} [${card.status}]` if (card.faces?.length) { const faces = card.faces.map(face => { const typeLine = face.typeLine ? `${quote(face.typeLine)}, ` : '' return `face(${quote(face.name)}, ${typeLine}${formatAbilityList(face.abilities)})` }) return `${header}\nexport default faces(\n${faces.map(face => indent(face)).join(',\n')},\n)` } const abilities = formatAbilityList(card.abilities) const body = card.typeLine ? `card(${quote(card.typeLine)}, ${abilities})` : abilities return `${header}\nexport default ${body}` }