Kkdjskjd
This commit is contained in:
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import type { Card } from '../src/cards.js'
|
||||
import { matchesCardFilters } from '../src/cards.js'
|
||||
import { cardDefinitionFromCard } from '../src/game/catalog.js'
|
||||
|
||||
function card(overrides: Partial<Card> = {}): Card {
|
||||
return {
|
||||
@@ -51,3 +52,41 @@ test('card filters match format legality, color identity, type, rarity, and mana
|
||||
assert.equal(matchesCardFilters(cardByIdentity, { cmcMin: 4 }), false)
|
||||
assert.equal(matchesCardFilters(cardByIdentity, { cmcMax: 2 }), false)
|
||||
})
|
||||
|
||||
test('compiled card types reach the engine definition', () => {
|
||||
const definition = cardDefinitionFromCard(card(), {
|
||||
oracle_id: 'test',
|
||||
name: 'Test Card',
|
||||
typeLine: 'Artifact Creature — Golem',
|
||||
status: 'supported',
|
||||
abilities: [],
|
||||
})
|
||||
assert.equal(definition.typeLine, 'Artifact Creature — Golem')
|
||||
})
|
||||
|
||||
test('lands with basic land types get one intrinsic mana ability for their colors', () => {
|
||||
const vents = cardDefinitionFromCard(card({
|
||||
name: 'Steam Vents',
|
||||
type_line: 'Land — Island Mountain',
|
||||
colors: [],
|
||||
color_identity: ['U', 'R'],
|
||||
}))
|
||||
assert.deepEqual(vents.abilities, [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: { kind: 'symbols', symbols: ['{U}', '{R}'], oneOf: true },
|
||||
}],
|
||||
optional: false,
|
||||
text: '{T}: Add {U} or {R}.',
|
||||
}])
|
||||
|
||||
const forest = cardDefinitionFromCard(card({ name: 'Forest', type_line: 'Basic Land — Forest' }))
|
||||
assert.deepEqual(forest.abilities?.[0]?.effects, [{
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: { kind: 'symbols', symbols: ['{G}'] },
|
||||
}])
|
||||
})
|
||||
|
||||
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { compileText } from '../src/effects/compile.js'
|
||||
import { formatAbility } from '../src/effects/format.js'
|
||||
import { parsePseudoCard } from '../src/effects/pseudo.js'
|
||||
import { parseCardSource } from '../src/effects/source.js'
|
||||
import type { Ability, Effect, Target } from '../src/effects/types.js'
|
||||
|
||||
function creature(text: string, keywords: string[] = []): Ability[] {
|
||||
@@ -41,6 +41,33 @@ test('activated mana ability', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('"or" in a mana ability marks the symbols as a choice', () => {
|
||||
const [ability] = creature('{T}: Add {G} or {U}.')
|
||||
assert.equal(ability.kind, 'activated')
|
||||
if (ability.kind !== 'activated') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: { kind: 'symbols', symbols: ['{G}', '{U}'], oneOf: true },
|
||||
})
|
||||
})
|
||||
|
||||
test('paying life to enter untapped compiles to an enters-tapped replacement', () => {
|
||||
const [ability] = compileText(
|
||||
"As this land enters, you may pay 2 life. If you don't, it enters tapped.",
|
||||
'Steam Vents',
|
||||
[],
|
||||
'Land — Island Mountain',
|
||||
)
|
||||
assert.equal(ability.kind, 'static')
|
||||
if (ability.kind !== 'static') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'enters_tapped',
|
||||
target: { kind: 'self' },
|
||||
unlessCost: { kind: 'pay_life', amount: { kind: 'number', value: 2 } },
|
||||
})
|
||||
})
|
||||
|
||||
test('search effect keeps destination, tapped, and shuffle', () => {
|
||||
const [ability] = spell('Search your library for a basic land card, put it onto the battlefield tapped, then shuffle.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
@@ -169,10 +196,10 @@ test('trigger condition cards in graveyard', () => {
|
||||
assert.deepEqual(ability.condition, { kind: 'cards_in_graveyard', player: 'you', atLeast: 7 })
|
||||
})
|
||||
|
||||
test('formatter renders pseudocode', () => {
|
||||
test('formatter renders card source', () => {
|
||||
const [ability] = creature('When this creature enters, draw a card.')
|
||||
const text = formatAbility(ability)
|
||||
assert.match(text, /on enters\(this\)/)
|
||||
assert.match(text, /triggered\(when\.enters\(self\)/)
|
||||
assert.match(text, /draw\(you, 1\)/)
|
||||
})
|
||||
|
||||
@@ -201,7 +228,10 @@ test('token copy of the triggering nontoken Dragon loses legendary', () => {
|
||||
if (effect.op !== 'create_token') return
|
||||
assert.deepEqual(effect.copyOf, { kind: 'trigger_subject' })
|
||||
assert.equal(effect.notLegendary, true)
|
||||
assert.equal(formatAbility(ability), 'on enters(each other nontoken dragon creature you control):\n create_token(you, 1, copy of the triggering object, not legendary)')
|
||||
assert.equal(
|
||||
formatAbility(ability),
|
||||
"triggered(when.enters(each(permanents.other().nontoken().withSubtype('dragon').withType('creature').youControl())), () => createToken(you, 1, copyOf(triggerSubject, { notLegendary: true })))",
|
||||
)
|
||||
})
|
||||
|
||||
test('all effects are typed', () => {
|
||||
@@ -299,9 +329,9 @@ test('"until the end of your next turn" gets its own duration', () => {
|
||||
if (effect.op !== 'pump') return
|
||||
assert.equal(effect.duration, 'until_end_of_your_next_turn')
|
||||
|
||||
const pseudo = formatAbility(ability)
|
||||
assert.match(pseudo, /until the end of your next turn/)
|
||||
assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo)
|
||||
const source = formatAbility(ability)
|
||||
assert.match(source, /untilEndOfYourNextTurn/)
|
||||
assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -315,7 +345,7 @@ test('parameterized keywords accept an em dash', () => {
|
||||
assert.deepEqual(fabricate, { kind: 'keyword', keyword: 'Fabricate', value: '1' })
|
||||
})
|
||||
|
||||
test('counter-removal costs parse and round-trip through pseudocode', () => {
|
||||
test('counter-removal costs parse and round-trip through card source', () => {
|
||||
const [self] = creature('{2}{U}, Remove a +1/+1 counter from this: Draw a card, then discard a card.')
|
||||
assert.equal(self.kind, 'activated')
|
||||
if (self.kind !== 'activated') return
|
||||
@@ -324,9 +354,9 @@ test('counter-removal costs parse and round-trip through pseudocode', () => {
|
||||
{ kind: 'remove_counters', counter: '+1/+1', amount: { kind: 'number', value: 1 } },
|
||||
])
|
||||
|
||||
const pseudo = formatAbility(self)
|
||||
assert.match(pseudo, /remove 1 \+1\/\+1 counter\(s\) from this/)
|
||||
assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo)
|
||||
const source = formatAbility(self)
|
||||
assert.match(source, /removeCountersCost\('\+1\/\+1', 1\)/)
|
||||
assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
|
||||
|
||||
const [other] = creature('Remove three spore counters from a creature you control: Create a 1/1 green Saproling creature token.')
|
||||
assert.equal(other.kind, 'activated')
|
||||
@@ -520,7 +550,7 @@ test('spell cost reductions compile their conditions and mana symbols', () => {
|
||||
}])
|
||||
})
|
||||
|
||||
test('new abilities, effects and conditions round-trip through pseudocode', () => {
|
||||
test('new abilities, effects and conditions round-trip through card source', () => {
|
||||
const abilities: Ability[] = [
|
||||
...spell('If you control a commander, you may cast this without paying its mana cost.'),
|
||||
...spell('Overload {6}{U}'),
|
||||
@@ -541,9 +571,9 @@ test('new abilities, effects and conditions round-trip through pseudocode', () =
|
||||
),
|
||||
]
|
||||
for (const ability of abilities) {
|
||||
const pseudo = formatAbility(ability)
|
||||
const reparsed = parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]
|
||||
const source = formatAbility(ability)
|
||||
const reparsed = parseCardSource(`export default [${source}]`).abilities[0]
|
||||
assert.ok(reparsed)
|
||||
assert.equal(formatAbility(reparsed), pseudo)
|
||||
assert.equal(formatAbility(reparsed), source)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -39,6 +39,30 @@ function land(name: string, color: string): CardDefinition {
|
||||
})
|
||||
}
|
||||
|
||||
function exoticOrchard(): CardDefinition {
|
||||
return card('Exotic Orchard', {
|
||||
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,
|
||||
restriction: 'a land an opponent controls could produce',
|
||||
},
|
||||
}],
|
||||
optional: false,
|
||||
text: '{T}: Add one mana of any color that a land an opponent controls could produce.',
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
function setup(players: { id: string; deck?: CardDefinition[]; life?: number }[]): Game {
|
||||
const game = new Game({
|
||||
seed: 7,
|
||||
@@ -77,6 +101,51 @@ test('turns start at the first main phase, draw opening hands, and pass to the n
|
||||
assert.equal(game.getPlayer('p1').hand.length, 7)
|
||||
})
|
||||
|
||||
test('mulligans draw a new seven and bottom one more card each time', () => {
|
||||
const game = new Game({
|
||||
seed: 3,
|
||||
startingHandSize: 7,
|
||||
mulligans: true,
|
||||
players: [
|
||||
{ id: 'p1', deck: Array.from({ length: 40 }, (_, index) => card(`P1 Card ${index}`)) },
|
||||
{ id: 'p2', deck: Array.from({ length: 40 }, (_, index) => card(`P2 Card ${index}`)) },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
|
||||
assert.equal(game.status, 'mulligan')
|
||||
assert.equal(game.getPlayer('p1').hand.length, 7)
|
||||
game.keepHand('p2')
|
||||
|
||||
game.mulligan('p1')
|
||||
assert.equal(game.getPlayer('p1').hand.length, 7)
|
||||
assert.equal(game.mulligans.get('p1')?.count, 1)
|
||||
assert.equal(game.mulligans.get('p1')?.bottom, 0)
|
||||
|
||||
game.mulligan('p1')
|
||||
assert.equal(game.mulligans.get('p1')?.count, 2)
|
||||
assert.equal(game.mulligans.get('p1')?.bottom, 1)
|
||||
assert.throws(() => game.keepHand('p1'), /bottom/)
|
||||
|
||||
const bottomCard = game.getPlayer('p1').hand[0]
|
||||
game.putOnBottom('p1', bottomCard)
|
||||
assert.equal(game.getPlayer('p1').hand.length, 6)
|
||||
assert.equal(game.getPlayer('p1').library.at(-1), bottomCard)
|
||||
assert.equal(game.mulligans.get('p1')?.bottom, 0)
|
||||
|
||||
game.mulligan('p1')
|
||||
assert.equal(game.mulligans.get('p1')?.count, 3)
|
||||
assert.equal(game.mulligans.get('p1')?.bottom, 2)
|
||||
for (const cardId of [...game.getPlayer('p1').hand.slice(0, 2)]) game.putOnBottom('p1', cardId)
|
||||
assert.equal(game.getPlayer('p1').hand.length, 5)
|
||||
|
||||
game.keepHand('p1')
|
||||
assert.equal(game.status, 'active')
|
||||
assert.equal(game.turn, 1)
|
||||
assert.equal(game.step, 'main')
|
||||
assert.equal(game.getPlayer('p1').hand.length, 5)
|
||||
})
|
||||
|
||||
test('passing priority twice advances from the main phase into combat', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
@@ -290,6 +359,73 @@ test('activated mana abilities produce mana and creatures have summoning sicknes
|
||||
assert.equal(game.getPlayer('p1').manaPool.G, 1)
|
||||
})
|
||||
|
||||
test('Exotic Orchard is limited to colors an opponent land could produce', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const orchard = game.addCard('p1', exoticOrchard(), 'battlefield')
|
||||
game.addCard('p2', land('Forest', 'G'), 'battlefield')
|
||||
const green = game.addCard('p1', spell('Green Spell', [], '{G}'), 'hand')
|
||||
const blue = game.addCard('p1', spell('Blue Spell', [], '{U}'), 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', green.id), true)
|
||||
assert.equal(game.canPlayCard('p1', blue.id), false)
|
||||
assert.throws(() => game.castSpell('p1', blue.id), GameError)
|
||||
assert.equal(orchard.tapped, false)
|
||||
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 })
|
||||
|
||||
game.castSpell('p1', green.id)
|
||||
assert.equal(orchard.tapped, true)
|
||||
assert.equal(game.getPlayer('p1').manaPool.G, 0)
|
||||
})
|
||||
|
||||
test('Exotic Orchard adds an opponent land color when activated manually', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const orchard = game.addCard('p1', exoticOrchard(), 'battlefield')
|
||||
game.addCard('p2', land('Island', 'U'), 'battlefield')
|
||||
|
||||
game.activateAbility('p1', orchard.id, 0)
|
||||
assert.equal(game.getPlayer('p1').manaPool.U, 1)
|
||||
assert.equal(game.getPlayer('p1').manaPool.W, 0)
|
||||
})
|
||||
|
||||
test('Exotic Orchard produces nothing without an opponent land', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const orchard = game.addCard('p1', exoticOrchard(), 'battlefield')
|
||||
|
||||
game.activateAbility('p1', orchard.id, 0)
|
||||
assert.equal(orchard.tapped, true)
|
||||
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 })
|
||||
})
|
||||
|
||||
test('a restricted mana source is used before an unrestricted one', () => {
|
||||
const rainbow = 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.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const rainbowLand = game.addCard('p1', rainbow, 'battlefield')
|
||||
const orchard = game.addCard('p1', exoticOrchard(), 'battlefield')
|
||||
game.addCard('p2', land('Forest', 'G'), 'battlefield')
|
||||
const gold = game.addCard('p1', spell('Gold Spell', [], '{G}{U}'), 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', gold.id), true)
|
||||
game.castSpell('p1', gold.id)
|
||||
assert.equal(orchard.tapped, true)
|
||||
assert.equal(rainbowLand.tapped, true)
|
||||
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 })
|
||||
})
|
||||
|
||||
test('static pump effects apply to matching creatures only', () => {
|
||||
const anthem = card('Glorious Anthem', {
|
||||
typeLine: 'Enchantment',
|
||||
@@ -625,6 +761,63 @@ test('static replacement effects make permanents enter tapped with counters', ()
|
||||
assert.equal(game.getToughness(bear), 3)
|
||||
})
|
||||
|
||||
function shockLand(): CardDefinition {
|
||||
return card('Steam Vents', {
|
||||
typeLine: 'Land — Island Mountain',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'enters_tapped', target: { kind: 'self' }, unlessCost: { kind: 'pay_life', amount: { kind: 'number', value: 2 } } }],
|
||||
text: "As this land enters, you may pay 2 life. If you don't, it enters tapped.",
|
||||
}, {
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{U}', '{R}'], oneOf: true } }],
|
||||
optional: false,
|
||||
text: '{T}: Add {U} or {R}.',
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
test('a land can pay life to enter untapped or enter tapped', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const vents = game.addCard('p1', shockLand(), 'hand')
|
||||
game.playLand('p1', vents.id)
|
||||
|
||||
assert.equal(vents.tapped, false)
|
||||
assert.equal(game.pendingChoice?.what, 'pay_cost')
|
||||
assert.equal(game.pendingChoice?.amount, 2)
|
||||
assert.throws(() => game.chooseCostPayment('p2', true), GameError)
|
||||
|
||||
game.chooseCostPayment('p1', true)
|
||||
assert.equal(game.getPlayer('p1').life, 38)
|
||||
assert.equal(vents.tapped, false)
|
||||
assert.equal(game.pendingChoice, undefined)
|
||||
|
||||
const second = game.addCard('p1', shockLand(), 'hand')
|
||||
game.moveToZone(second, 'battlefield', { controller: 'p1', silent: false })
|
||||
assert.equal(game.pendingChoice?.what, 'pay_cost')
|
||||
|
||||
game.chooseCostPayment('p1', false)
|
||||
assert.equal(second.tapped, true)
|
||||
assert.equal(game.getPlayer('p1').life, 38)
|
||||
})
|
||||
|
||||
test('a choice mana ability adds only the color the spell needs', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const vents = game.addCard('p1', shockLand(), 'battlefield')
|
||||
const red = game.addCard('p1', spell('Red Spell', [], '{R}'), 'hand')
|
||||
|
||||
game.castSpell('p1', red.id)
|
||||
|
||||
assert.equal(vents.tapped, true)
|
||||
assert.equal(game.getPlayer('p1').manaPool.R, 0)
|
||||
assert.equal(game.getPlayer('p1').manaPool.U, 0)
|
||||
})
|
||||
|
||||
test('a player who runs out of cards loses and the last player wins', () => {
|
||||
const game = new Game({
|
||||
seed: 3,
|
||||
@@ -658,6 +851,43 @@ test('lethal damage to a player ends the game', () => {
|
||||
assert.equal(game.getPlayer('p2').life, 0)
|
||||
})
|
||||
|
||||
test('the legend rule leaves one legendary permanent per name under one controller', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const legend = card('Kiora, the Rising Tide', {
|
||||
typeLine: 'Legendary Creature — Merfolk Wizard',
|
||||
power: 1,
|
||||
toughness: 1,
|
||||
})
|
||||
const first = game.addCard('p1', legend, 'battlefield')
|
||||
const second = game.addCard('p1', legend, 'battlefield')
|
||||
const forest = game.addCard('p1', land('Forest', 'G'), 'hand')
|
||||
|
||||
game.playLand('p1', forest.id)
|
||||
|
||||
assert.equal(first.zone, 'battlefield')
|
||||
assert.equal(second.zone, 'graveyard')
|
||||
assert.ok(game.getPlayer('p1').graveyard.includes(second.id))
|
||||
})
|
||||
|
||||
test('the legend rule does not apply across controllers', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const legend = card('Kiora, the Rising Tide', {
|
||||
typeLine: 'Legendary Creature — Merfolk Wizard',
|
||||
power: 1,
|
||||
toughness: 1,
|
||||
})
|
||||
const mine = game.addCard('p1', legend, 'battlefield')
|
||||
const theirs = game.addCard('p2', legend, 'battlefield')
|
||||
const forest = game.addCard('p1', land('Forest', 'G'), 'hand')
|
||||
|
||||
game.playLand('p1', forest.id)
|
||||
|
||||
assert.equal(mine.zone, 'battlefield')
|
||||
assert.equal(theirs.zone, 'battlefield')
|
||||
})
|
||||
|
||||
test('a failed mana payment leaves mana sources untapped and the pool unchanged', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import type { Card } from '../src/cards.js'
|
||||
import { formatCard } from '../src/effects/format.js'
|
||||
import {
|
||||
compileImplementation,
|
||||
deleteOverride,
|
||||
readAllOverrides,
|
||||
readOverride,
|
||||
writeOverride,
|
||||
} from '../src/effects/implementations.js'
|
||||
import { parsePseudoCard, PseudoParseError } from '../src/effects/pseudo.js'
|
||||
|
||||
const CARD: Card = {
|
||||
oracle_id: '00000000-0000-4000-8000-000000000001',
|
||||
name: 'Test Card',
|
||||
layout: 'normal',
|
||||
cmc: 1,
|
||||
type_line: 'Creature — Human',
|
||||
colors: [],
|
||||
color_identity: [],
|
||||
keywords: [],
|
||||
}
|
||||
|
||||
const SOURCE = `on enters(this):
|
||||
choose 1:
|
||||
1. exile(target other creature you own); schedule(next_end_step):
|
||||
return_to_battlefield(the chosen target)
|
||||
static:
|
||||
grant_ability(each enchanted land):
|
||||
on upkeep(you) (may):
|
||||
pay({W}{W})
|
||||
if you do:
|
||||
gain_life(you, 1)`
|
||||
|
||||
test('pseudocode round-trips through the compiler and formatter', () => {
|
||||
const compiled = compileImplementation(CARD, SOURCE)
|
||||
assert.equal(compiled.manual, true)
|
||||
assert.equal(compiled.status, 'supported')
|
||||
|
||||
const rendered = formatCard(compiled)
|
||||
const reparsed = compileImplementation(CARD, rendered)
|
||||
assert.equal(formatCard(reparsed), rendered)
|
||||
assert.equal(reparsed.abilities.length, 2)
|
||||
|
||||
const [triggered] = reparsed.abilities
|
||||
assert.equal(triggered.kind, 'triggered')
|
||||
if (triggered.kind !== 'triggered') return
|
||||
assert.equal(triggered.effects[0].op, 'modal')
|
||||
if (triggered.effects[0].op !== 'modal') return
|
||||
assert.equal(triggered.effects[0].modes[0][1].op, 'schedule')
|
||||
|
||||
const staticAbility = reparsed.abilities[1]
|
||||
assert.equal(staticAbility.kind, 'static')
|
||||
if (staticAbility.kind !== 'static') return
|
||||
assert.equal(staticAbility.effects[0].op, 'grant_ability')
|
||||
if (staticAbility.effects[0].op !== 'grant_ability') return
|
||||
assert.equal(staticAbility.effects[0].ability.kind, 'triggered')
|
||||
})
|
||||
|
||||
test('invalid pseudocode reports its line', () => {
|
||||
assert.throws(
|
||||
() => parsePseudoCard('spell:\n draw(you)'),
|
||||
(error: unknown) => error instanceof PseudoParseError && error.line === 2,
|
||||
)
|
||||
})
|
||||
|
||||
test('manual implementations persist one file per card', async (t) => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'commander-overrides-'))
|
||||
const previous = process.env.CARD_OVERRIDES_DIR
|
||||
process.env.CARD_OVERRIDES_DIR = dir
|
||||
t.after(async () => {
|
||||
if (previous === undefined) delete process.env.CARD_OVERRIDES_DIR
|
||||
else process.env.CARD_OVERRIDES_DIR = previous
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
await writeOverride(CARD.oracle_id, SOURCE)
|
||||
const stored = await readOverride(CARD.oracle_id)
|
||||
assert.equal(stored?.source, `${SOURCE}\n`)
|
||||
assert.equal((await readAllOverrides()).get(CARD.oracle_id), `${SOURCE}\n`)
|
||||
|
||||
const compiled = compileImplementation(CARD, stored!.source)
|
||||
assert.equal(compiled.manual, true)
|
||||
assert.equal(compiled.status, 'supported')
|
||||
|
||||
await deleteOverride(CARD.oracle_id)
|
||||
assert.equal(await readOverride(CARD.oracle_id), undefined)
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { findCardByName } from '../src/cards.js'
|
||||
import { createMatch, getMatchView, joinMatch, leaveMatch, setDeck, startMatch } from '../src/game/rooms.js'
|
||||
import { createMatch, getMatchView, joinMatch, leaveMatch, performAction, setDeck, startMatch } from '../src/game/rooms.js'
|
||||
|
||||
function deck(commanderName: string) {
|
||||
const commander = findCardByName(commanderName)
|
||||
@@ -36,3 +36,20 @@ test('leaving a started game forfeits the seat instead of erroring', () => {
|
||||
assert.equal(view.status, 'finished')
|
||||
assert.equal(view.players.find(player => player.id === host.playerId)?.lost, true)
|
||||
})
|
||||
|
||||
test('started matches wait for both players to keep their opening hands', () => {
|
||||
const host = createMatch('Host', deck("Atraxa, Praetors' Voice"), 2)
|
||||
const guest = joinMatch(host.matchId, 'Guest', deck('Kenrith, the Returned King'))
|
||||
startMatch(host.matchId, host.token)
|
||||
|
||||
let view = getMatchView(host.matchId, host.token)
|
||||
assert.equal(view.status, 'active')
|
||||
assert.equal(view.game?.status, 'mulligan')
|
||||
assert.equal(view.game?.mulligans?.length, 2)
|
||||
|
||||
performAction(host.matchId, host.token, { type: 'keep_hand' })
|
||||
performAction(host.matchId, guest.token, { type: 'keep_hand' })
|
||||
|
||||
view = getMatchView(host.matchId, host.token)
|
||||
assert.equal(view.game?.status, 'active')
|
||||
})
|
||||
|
||||
194
backend/test/source.test.ts
Normal file
194
backend/test/source.test.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import type { Card } from '../src/cards.js'
|
||||
import { formatCard } from '../src/effects/format.js'
|
||||
import {
|
||||
compileImplementation,
|
||||
deleteOverride,
|
||||
readAllOverrides,
|
||||
readOverride,
|
||||
writeOverride,
|
||||
} from '../src/effects/implementations.js'
|
||||
import { parseCardSource, SourceParseError } from '../src/effects/source.js'
|
||||
|
||||
const CARD: Card = {
|
||||
oracle_id: '00000000-0000-4000-8000-000000000001',
|
||||
name: 'Test Card',
|
||||
layout: 'normal',
|
||||
cmc: 1,
|
||||
type_line: 'Creature — Human',
|
||||
colors: [],
|
||||
color_identity: [],
|
||||
keywords: [],
|
||||
}
|
||||
|
||||
const SOURCE = `export default [
|
||||
triggered(when.enters(self), [
|
||||
modal(1, 1, [
|
||||
[
|
||||
exile(target(permanents.withType('creature').other().ownedBy('you'))),
|
||||
schedule('next_end_step', [returnToBattlefield(previousTarget)]),
|
||||
],
|
||||
]),
|
||||
]),
|
||||
staticAbility([
|
||||
grantAbility(each(permanents.withType('land').enchanted()), triggered(when.upkeep(you), [
|
||||
pay([manaCost('{W}{W}')]),
|
||||
ifThen(ifYouDo(), [gainLife(you, 1)]),
|
||||
], { optional: true })),
|
||||
]),
|
||||
]`
|
||||
|
||||
test('card source round-trips through the compiler and formatter', () => {
|
||||
const compiled = compileImplementation(CARD, SOURCE)
|
||||
assert.equal(compiled.manual, true)
|
||||
assert.equal(compiled.status, 'supported')
|
||||
assert.equal(compiled.typeLine, CARD.type_line)
|
||||
|
||||
const rendered = formatCard(compiled)
|
||||
assert.match(rendered, /export default card\('Creature — Human', \[/)
|
||||
const reparsed = compileImplementation(CARD, rendered)
|
||||
assert.equal(formatCard(reparsed), rendered)
|
||||
assert.equal(reparsed.typeLine, CARD.type_line)
|
||||
assert.equal(reparsed.abilities.length, 2)
|
||||
|
||||
const [triggered] = reparsed.abilities
|
||||
assert.equal(triggered.kind, 'triggered')
|
||||
if (triggered.kind !== 'triggered') return
|
||||
assert.equal(triggered.effects[0].op, 'modal')
|
||||
if (triggered.effects[0].op !== 'modal') return
|
||||
assert.equal(triggered.effects[0].modes[0][1].op, 'schedule')
|
||||
|
||||
const staticAbility = reparsed.abilities[1]
|
||||
assert.equal(staticAbility.kind, 'static')
|
||||
if (staticAbility.kind !== 'static') return
|
||||
assert.equal(staticAbility.effects[0].op, 'grant_ability')
|
||||
if (staticAbility.effects[0].op !== 'grant_ability') return
|
||||
assert.equal(staticAbility.effects[0].ability.kind, 'triggered')
|
||||
})
|
||||
|
||||
test('card source declares the card type line for the engine', () => {
|
||||
const compiled = compileImplementation(CARD, `export default card('Artifact Creature — Golem', [keyword('Vigilance')])`)
|
||||
assert.equal(compiled.typeLine, 'Artifact Creature — Golem')
|
||||
assert.match(formatCard(compiled), /export default card\('Artifact Creature — Golem', \[/)
|
||||
})
|
||||
|
||||
test('multi-face card source declares one type line per face', () => {
|
||||
const faces: Card = {
|
||||
...CARD,
|
||||
layout: 'transform',
|
||||
card_faces: [
|
||||
{ name: 'Front', type_line: 'Sorcery', colors: [] },
|
||||
{ name: 'Back', type_line: 'Creature — Human', colors: [] },
|
||||
],
|
||||
}
|
||||
const source = `export default faces(
|
||||
face('Front', 'Instant', [spell([draw(you, 2)])]),
|
||||
face('Back', 'Creature — Human', [keyword('Flying')]),
|
||||
)`
|
||||
const compiled = compileImplementation(faces, source)
|
||||
assert.deepEqual(compiled.faces?.map(face => face.typeLine), ['Instant', 'Creature — Human'])
|
||||
const rendered = formatCard(compiled)
|
||||
assert.equal(formatCard(compileImplementation(faces, rendered)), rendered)
|
||||
})
|
||||
|
||||
test('effect lists accept callbacks in place of arrays', () => {
|
||||
const CALLBACK_SOURCE = `export default [
|
||||
triggered(when.enters(self), () => draw(you, 1)),
|
||||
triggered(when.dies(self), () => {
|
||||
draw(you, 1)
|
||||
gainLife(you, 1);
|
||||
}),
|
||||
staticAbility(() => staticPump(each(creatures.youControl()), 1, 1)),
|
||||
spell([
|
||||
modal(1, 1, [
|
||||
() => draw(you, 2),
|
||||
() => { gainLife(you, 3) },
|
||||
]),
|
||||
]),
|
||||
]`
|
||||
|
||||
const compiled = compileImplementation(CARD, CALLBACK_SOURCE)
|
||||
assert.equal(compiled.status, 'supported')
|
||||
|
||||
const [enters, dies, staticAbility, spell] = compiled.abilities
|
||||
assert.equal(enters.kind, 'triggered')
|
||||
if (enters.kind !== 'triggered') return
|
||||
assert.deepEqual(enters.effects.map(effect => effect.op), ['draw'])
|
||||
|
||||
assert.equal(dies.kind, 'triggered')
|
||||
if (dies.kind !== 'triggered') return
|
||||
assert.deepEqual(dies.effects.map(effect => effect.op), ['draw', 'life'])
|
||||
|
||||
assert.equal(staticAbility.kind, 'static')
|
||||
if (staticAbility.kind !== 'static') return
|
||||
assert.deepEqual(staticAbility.effects.map(effect => effect.op), ['pump'])
|
||||
|
||||
assert.equal(spell.kind, 'spell')
|
||||
if (spell.kind !== 'spell') return
|
||||
assert.equal(spell.effects[0].op, 'modal')
|
||||
if (spell.effects[0].op !== 'modal') return
|
||||
assert.deepEqual(spell.effects[0].modes.map(mode => mode.map(effect => effect.op)), [['draw'], ['life']])
|
||||
})
|
||||
|
||||
test('invalid source reports its line', () => {
|
||||
assert.throws(
|
||||
() => parseCardSource('export default [\n draw(you)\n]'),
|
||||
(error: unknown) => error instanceof SourceParseError && error.line === 2,
|
||||
)
|
||||
})
|
||||
|
||||
test('unknown AST discriminants are rejected', () => {
|
||||
assert.throws(
|
||||
() => parseCardSource("export default [spell([{ op: 'nope' }])]"),
|
||||
(error: unknown) => error instanceof SourceParseError && /expected an effect/.test(error.message),
|
||||
)
|
||||
assert.throws(
|
||||
() => parseCardSource("export default [{ kind: 'nope' }]"),
|
||||
(error: unknown) => error instanceof SourceParseError && /expected an ability/.test(error.message),
|
||||
)
|
||||
assert.throws(
|
||||
() => parseCardSource("export default [triggered(when.nope(self), [])]"),
|
||||
(error: unknown) => error instanceof SourceParseError,
|
||||
)
|
||||
})
|
||||
|
||||
test('manual implementations persist one file per card', async (t) => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'commander-overrides-'))
|
||||
const previous = process.env.CARD_OVERRIDES_DIR
|
||||
process.env.CARD_OVERRIDES_DIR = dir
|
||||
t.after(async () => {
|
||||
if (previous === undefined) delete process.env.CARD_OVERRIDES_DIR
|
||||
else process.env.CARD_OVERRIDES_DIR = previous
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
await writeOverride(CARD.oracle_id, SOURCE)
|
||||
const stored = await readOverride(CARD.oracle_id)
|
||||
assert.equal(stored?.source, `${SOURCE}\n`)
|
||||
assert.equal((await readAllOverrides()).get(CARD.oracle_id), `${SOURCE}\n`)
|
||||
|
||||
const compiled = compileImplementation(CARD, stored!.source)
|
||||
assert.equal(compiled.manual, true)
|
||||
assert.equal(compiled.status, 'supported')
|
||||
|
||||
await deleteOverride(CARD.oracle_id)
|
||||
assert.equal(await readOverride(CARD.oracle_id), undefined)
|
||||
})
|
||||
|
||||
test('entersTapped accepts an unlessCost builder and round-trips', () => {
|
||||
const source = `export default [
|
||||
staticAbility([entersTapped(self, { unlessCost: payLife(2) })]),
|
||||
]`
|
||||
const compiled = compileImplementation(CARD, source)
|
||||
assert.equal(compiled.status, 'supported')
|
||||
|
||||
const rendered = formatCard(compiled)
|
||||
assert.match(rendered, /entersTapped\(self, \{ unlessCost: payLife\(2\) \}\)/)
|
||||
|
||||
const reparsed = compileImplementation(CARD, rendered)
|
||||
assert.deepEqual(reparsed.abilities, compiled.abilities)
|
||||
})
|
||||
@@ -46,40 +46,40 @@ function fakeOpenRouter(content: string) {
|
||||
}
|
||||
}
|
||||
|
||||
test('translation asks for pseudocode only and validates the answer', async () => {
|
||||
const fake = fakeOpenRouter('spell:\n draw(you, 2)')
|
||||
test('translation asks for card source only and validates the answer', async () => {
|
||||
const fake = fakeOpenRouter('export default [spell([draw(you, 2)])]')
|
||||
const source = await translateCard(CARD, {
|
||||
apiKey: 'test-key',
|
||||
model: 'test/model',
|
||||
fetch: fake.fetchImpl,
|
||||
})
|
||||
|
||||
assert.equal(source, 'spell:\n draw(you, 2)')
|
||||
assert.equal(source, 'export default [spell([draw(you, 2)])]')
|
||||
assert.equal(fake.body.model, 'test/model')
|
||||
assert.equal(fake.body.temperature, 0)
|
||||
assert.equal(fake.body.max_tokens, 700)
|
||||
assert.equal(fake.body.max_tokens, 1200)
|
||||
assert.equal(fake.headers.Authorization, 'Bearer test-key')
|
||||
assert.match(fake.body.messages[0].content, /pseudocode only/i)
|
||||
assert.match(fake.body.messages[0].content, /card source only/i)
|
||||
assert.match(fake.body.messages[0].content, /Never invent an operation/)
|
||||
assert.match(fake.body.messages[1].content, /Draw two cards\./)
|
||||
})
|
||||
|
||||
test('a model code fence is removed before saving', async () => {
|
||||
const fake = fakeOpenRouter('```\nspell:\n draw(you, 2)\n```')
|
||||
const fake = fakeOpenRouter('```\nexport default [spell([draw(you, 2)])]\n```')
|
||||
const source = await translateCard(CARD, {
|
||||
apiKey: 'test-key',
|
||||
model: 'test/model',
|
||||
fetch: fake.fetchImpl,
|
||||
})
|
||||
assert.equal(source, 'spell:\n draw(you, 2)')
|
||||
assert.equal(cleanTranslation(' spell:\n draw(you, 2) '), 'spell:\n draw(you, 2)')
|
||||
assert.equal(source, 'export default [spell([draw(you, 2)])]')
|
||||
assert.equal(cleanTranslation(' export default [spell([draw(you, 2)])] '), 'export default [spell([draw(you, 2)])]')
|
||||
})
|
||||
|
||||
test('prose instead of pseudocode is rejected', async () => {
|
||||
test('prose instead of card source is rejected', async () => {
|
||||
const fake = fakeOpenRouter('Here is the translated card. It draws two cards.')
|
||||
await assert.rejects(
|
||||
translateCard(CARD, { apiKey: 'test-key', model: 'test/model', fetch: fake.fetchImpl }),
|
||||
(error: unknown) => error instanceof TranslationError && /valid pseudocode/.test(error.message),
|
||||
(error: unknown) => error instanceof TranslationError && /valid card source/.test(error.message),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -105,13 +105,13 @@ test('multi-face cards receive their face names in the prompt', async () => {
|
||||
{ name: 'Back', type_line: 'Creature', oracle_text: 'Flying', colors: [] },
|
||||
],
|
||||
}
|
||||
const fake = fakeOpenRouter('## Front\non enters(this):\n draw(you, 1)\n\n## Back\nkeyword Flying')
|
||||
const fake = fakeOpenRouter("export default faces(face('Front', [triggered(when.enters(self), [draw(you, 1)])]), face('Back', [keyword('Flying')]))")
|
||||
const source = await translateCard(faces, {
|
||||
apiKey: 'test-key',
|
||||
model: 'test/model',
|
||||
fetch: fake.fetchImpl,
|
||||
})
|
||||
assert.equal(source, '## Front\non enters(this):\n draw(you, 1)\n\n## Back\nkeyword Flying')
|
||||
assert.equal(source, "export default faces(face('Front', [triggered(when.enters(self), [draw(you, 1)])]), face('Back', [keyword('Flying')]))")
|
||||
assert.match(fake.body.messages[1].content, /## Front/)
|
||||
assert.match(fake.body.messages[1].content, /## Back/)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user